context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Runtime.Serialization.Formatters.Tests
{
public class BinaryFormatterTests : RemoteExecutorTestBase
{
public static IEnumerable<object> SerializableObjects()
{
// Primitive types
yield return byte.MinValue;
yield return byte.MaxValue;
yield return sbyte.MinValue;
yield return sbyte.MaxValue;
yield return short.MinValue;
yield return short.MaxValue;
yield return int.MinValue;
yield return int.MaxValue;
yield return uint.MinValue;
yield return uint.MaxValue;
yield return long.MinValue;
yield return long.MaxValue;
yield return ulong.MinValue;
yield return ulong.MaxValue;
yield return char.MinValue;
yield return char.MaxValue;
yield return float.MinValue;
yield return float.MaxValue;
yield return double.MinValue;
yield return double.MaxValue;
yield return decimal.MinValue;
yield return decimal.MaxValue;
yield return decimal.MinusOne;
yield return true;
yield return false;
yield return "";
yield return "c";
yield return "\u4F60\u597D";
yield return "some\0data\0with\0null\0chars";
yield return "<>&\"\'";
yield return " < ";
yield return "minchar" + char.MinValue + "minchar";
// Enum values
yield return DayOfWeek.Monday;
yield return DateTimeKind.Local;
// Nullables
yield return (int?)1;
yield return (StructWithIntField?)new StructWithIntField() { X = 42 };
// Other core serializable types
yield return IntPtr.Zero;
yield return UIntPtr.Zero;
yield return DateTime.Now;
yield return DateTimeOffset.Now;
yield return DateTimeKind.Local;
yield return TimeSpan.FromDays(7);
yield return new Version(1, 2, 3, 4);
yield return new Guid("0CACAA4D-C6BD-420A-B660-2F557337CA89");
yield return new AttributeUsageAttribute(AttributeTargets.Class);
yield return new List<int>();
yield return new List<int>() { 1, 2, 3, 4, 5 };
yield return new Dictionary<int, string>() { { 1, "test" }, { 2, "another test" } };
yield return Tuple.Create(1);
yield return Tuple.Create(1, "2");
yield return Tuple.Create(1, "2", 3u);
yield return Tuple.Create(1, "2", 3u, 4L);
yield return Tuple.Create(1, "2", 3u, 4L, 5.6);
yield return Tuple.Create(1, "2", 3u, 4L, 5.6, 7.8f);
yield return Tuple.Create(1, "2", 3u, 4L, 5.6, 7.8f, 9m);
yield return Tuple.Create(1, "2", 3u, 4L, 5.6, 7.8f, 9m, Tuple.Create(10));
yield return new KeyValuePair<int, byte>(42, 84);
// Arrays of primitive types
yield return Enumerable.Range(0, 256).Select(i => (byte)i).ToArray();
yield return new int[] { };
yield return new int[] { 1 };
yield return new int[] { 1, 2, 3, 4, 5 };
yield return new char[] { 'a', 'b', 'c', 'd', 'e' };
yield return new string[] { };
yield return new string[] { "hello", "world" };
yield return new short[] { short.MaxValue };
yield return new long[] { long.MaxValue };
yield return new ushort[] { ushort.MaxValue };
yield return new uint[] { uint.MaxValue };
yield return new ulong[] { ulong.MaxValue };
yield return new bool[] { true, false };
yield return new double[] { 1.2 };
yield return new float[] { 1.2f, 3.4f };
// Arrays of other types
yield return new object[] { };
yield return new Guid[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
yield return new DayOfWeek[] { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday };
yield return new Point[] { new Point(1, 2), new Point(3, 4) };
yield return new ObjectWithArrays
{
IntArray = new int[0],
StringArray = new string[] { "hello", "world" },
ByteArray = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 },
JaggedArray = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 } },
MultiDimensionalArray = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } },
TreeArray = new Tree<int>[] { new Tree<int>(1, new Tree<int>(2, null, null), new Tree<int>(3, null, null)) }
};
yield return new object[] { new int[,] { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 } } };
yield return new object[] { new int[,,] { { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 } } } };
yield return new object[] { new int[,,,] { { { { 1 } } } } };
yield return new ArraySegment<int>(new int[] { 1, 2, 3, 4, 5 }, 1, 2);
yield return Enumerable.Range(0, 10000).Select(i => (object)i).ToArray();
yield return new object[200]; // fewer than 256 nulls
yield return new object[300]; // more than 256 nulls
// Non-vector arrays
yield return Array.CreateInstance(typeof(uint), new[] { 5 }, new[] { 1 });
yield return Array.CreateInstance(typeof(int), new[] { 0, 0, 0 }, new[] { 0, 0, 0 });
var arr = Array.CreateInstance(typeof(string), new[] { 1, 2 }, new[] { 3, 4 });
arr.SetValue("hello", new[] { 3, 5 });
yield return arr;
// Various globalization types
yield return CultureInfo.CurrentCulture;
yield return CultureInfo.InvariantCulture;
// Internal specialized equality comparers
yield return EqualityComparer<byte>.Default;
yield return EqualityComparer<int>.Default;
yield return EqualityComparer<string>.Default;
yield return EqualityComparer<int?>.Default;
yield return EqualityComparer<double?>.Default;
yield return EqualityComparer<object>.Default;
yield return EqualityComparer<Int32Enum>.Default;
// Custom object
var sealedObjectWithIntStringFields = new SealedObjectWithIntStringFields();
yield return sealedObjectWithIntStringFields;
yield return new SealedObjectWithIntStringFields() { Member1 = 42, Member2 = null, Member3 = "84" };
// Custom object with fields pointing to the same object
yield return new ObjectWithIntStringUShortUIntULongAndCustomObjectFields
{
Member1 = 10,
Member2 = "hello",
_member3 = "hello",
Member4 = sealedObjectWithIntStringFields,
Member4shared = sealedObjectWithIntStringFields,
Member5 = new SealedObjectWithIntStringFields(),
Member6 = "Hello World",
str1 = "hello < world",
str2 = "<",
str3 = "< world",
str4 = "hello < world",
u16 = ushort.MaxValue,
u32 = uint.MaxValue,
u64 = ulong.MaxValue,
};
// Simple type without a default ctor
var point = new Point(1, 2);
yield return point;
// Graph without cycles
yield return new Tree<int>(42, null, null);
yield return new Tree<int>(1, new Tree<int>(2, new Tree<int>(3, null, null), null), null);
yield return new Tree<Colors>(Colors.Red, null, new Tree<Colors>(Colors.Blue, null, new Tree<Colors>(Colors.Green, null, null)));
yield return new Tree<int>(1, new Tree<int>(2, new Tree<int>(3, null, null), new Tree<int>(4, null, null)), new Tree<int>(5, null, null));
// Graph with cycles
Graph<int> a = new Graph<int> { Value = 1 };
yield return a;
Graph<int> b = new Graph<int> { Value = 2, Links = new[] { a } };
yield return b;
Graph<int> c = new Graph<int> { Value = 3, Links = new[] { a, b } };
yield return c;
Graph<int> d = new Graph<int> { Value = 3, Links = new[] { a, b, c } };
yield return d;
a.Links = new[] { b, c, d }; // complete the cycle
yield return a;
// Structs
yield return new EmptyStruct();
yield return new StructWithIntField { X = 42 };
yield return new StructWithStringFields { String1 = "hello", String2 = "world" };
yield return new StructContainingOtherStructs { Nested1 = new StructWithStringFields { String1 = "a", String2 = "b" }, Nested2 = new StructWithStringFields { String1 = "3", String2 = "4" } };
yield return new StructContainingArraysOfOtherStructs();
yield return new StructContainingArraysOfOtherStructs { Nested = new StructContainingOtherStructs[0] };
var s = new StructContainingArraysOfOtherStructs
{
Nested = new[]
{
new StructContainingOtherStructs { Nested1 = new StructWithStringFields { String1 = "a", String2 = "b" }, Nested2 = new StructWithStringFields { String1 = "3", String2 = "4" } },
new StructContainingOtherStructs { Nested1 = new StructWithStringFields { String1 = "e", String2 = "f" }, Nested2 = new StructWithStringFields { String1 = "7", String2 = "8" } },
}
};
yield return s;
yield return new object[] { s, new StructContainingArraysOfOtherStructs?(s) };
// ISerializable
yield return new BasicISerializableObject(1, "2");
yield return new DerivedISerializableWithNonPublicDeserializationCtor(1, "2");
// Various other special cases
yield return new TypeWithoutNamespace();
}
public static IEnumerable<object> NonSerializableObjects()
{
yield return new NonSerializableStruct();
yield return new NonSerializableClass();
yield return new SerializableClassWithBadField();
yield return new object[] { 1, 2, 3, new NonSerializableClass() };
}
public static IEnumerable<object[]> ValidateBasicObjectsRoundtrip_MemberData()
{
foreach (object obj in SerializableObjects())
{
foreach (FormatterAssemblyStyle assemblyFormat in new[] { FormatterAssemblyStyle.Full, FormatterAssemblyStyle.Simple })
{
foreach (TypeFilterLevel filterLevel in new[] { TypeFilterLevel.Full, TypeFilterLevel.Low })
{
foreach (FormatterTypeStyle typeFormat in new[] { FormatterTypeStyle.TypesAlways, FormatterTypeStyle.TypesWhenNeeded, FormatterTypeStyle.XsdString })
{
yield return new object[] { obj, assemblyFormat, filterLevel, typeFormat};
}
}
}
}
}
[Theory]
[MemberData(nameof(ValidateBasicObjectsRoundtrip_MemberData))]
public void ValidateBasicObjectsRoundtrip(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat)
{
object result = FormatterClone(obj, null, assemblyFormat, filterLevel, typeFormat);
if (!ReferenceEquals(obj, string.Empty)) // "" is interned and will roundtrip as the same object
{
Assert.NotSame(obj, result);
}
Assert.Equal(obj, result);
}
[Fact]
public void RoundtripManyObjectsInOneStream()
{
object[] objects = SerializableObjects().ToArray();
var s = new MemoryStream();
var f = new BinaryFormatter();
foreach (object obj in objects)
{
f.Serialize(s, obj);
}
s.Position = 0;
foreach (object obj in objects)
{
object result = f.Deserialize(s);
Assert.Equal(obj, result);
}
}
[Fact]
public void SameObjectRepeatedInArray()
{
object o = new object();
object[] arr = new[] { o, o, o, o, o };
object[] result = FormatterClone(arr);
Assert.Equal(arr.Length, result.Length);
Assert.NotSame(arr, result);
Assert.NotSame(arr[0], result[0]);
for (int i = 1; i < result.Length; i++)
{
Assert.Same(result[0], result[i]);
}
}
public static IEnumerable<object[]> SerializableExceptions()
{
yield return new object[] { new AbandonedMutexException() };
yield return new object[] { new AggregateException(new FieldAccessException(), new MemberAccessException()) };
yield return new object[] { new AmbiguousMatchException() };
yield return new object[] { new ArgumentException("message", "paramName") };
yield return new object[] { new ArgumentNullException("paramName") };
yield return new object[] { new ArgumentOutOfRangeException("paramName", 42, "message") };
yield return new object[] { new ArithmeticException() };
yield return new object[] { new ArrayTypeMismatchException("message") };
yield return new object[] { new BadImageFormatException("message", "filename") };
yield return new object[] { new COMException() };
yield return new object[] { new CultureNotFoundException() };
yield return new object[] { new DataMisalignedException("message") };
yield return new object[] { new DecoderFallbackException() };
yield return new object[] { new DirectoryNotFoundException() };
yield return new object[] { new DivideByZeroException() };
yield return new object[] { new DllNotFoundException() };
yield return new object[] { new EncoderFallbackException() };
yield return new object[] { new EndOfStreamException() };
yield return new object[] { new EventSourceException() };
yield return new object[] { new Exception("message") };
yield return new object[] { new FieldAccessException("message", new FieldAccessException()) };
yield return new object[] { new FileLoadException() };
yield return new object[] { new FileNotFoundException() };
yield return new object[] { new FormatException("message") };
yield return new object[] { new IndexOutOfRangeException() };
yield return new object[] { new InsufficientExecutionStackException() };
yield return new object[] { new InvalidCastException() };
yield return new object[] { new InvalidComObjectException() };
yield return new object[] { new InvalidOleVariantTypeException() };
yield return new object[] { new InvalidOperationException() };
yield return new object[] { new InvalidProgramException() };
yield return new object[] { new InvalidTimeZoneException() };
yield return new object[] { new IOException() };
yield return new object[] { new KeyNotFoundException() };
yield return new object[] { new LockRecursionException() };
yield return new object[] { new MarshalDirectiveException() };
yield return new object[] { new MemberAccessException() };
yield return new object[] { new MethodAccessException() };
yield return new object[] { new MissingFieldException() };
yield return new object[] { new MissingMemberException() };
yield return new object[] { new NotImplementedException() };
yield return new object[] { new NotSupportedException() };
yield return new object[] { new NullReferenceException() };
yield return new object[] { new ObjectDisposedException("objectName") };
yield return new object[] { new OperationCanceledException(new CancellationTokenSource().Token) };
yield return new object[] { new OutOfMemoryException() };
yield return new object[] { new OverflowException() };
yield return new object[] { new PathTooLongException() };
yield return new object[] { new PlatformNotSupportedException() };
yield return new object[] { new RankException() };
yield return new object[] { new SafeArrayRankMismatchException() };
yield return new object[] { new SafeArrayTypeMismatchException() };
yield return new object[] { new SecurityException() };
yield return new object[] { new SEHException() };
yield return new object[] { new SemaphoreFullException() };
yield return new object[] { new SerializationException() };
yield return new object[] { new SynchronizationLockException() };
yield return new object[] { new TargetInvocationException("message", new Exception()) };
yield return new object[] { new TargetParameterCountException() };
yield return new object[] { new TaskCanceledException(Task.CompletedTask) };
yield return new object[] { new TaskSchedulerException() };
yield return new object[] { new TimeoutException() };
yield return new object[] { new TypeAccessException() };
yield return new object[] { new TypeInitializationException(typeof(string).FullName, new Exception()) };
yield return new object[] { new TypeLoadException() };
yield return new object[] { new UnauthorizedAccessException("message", new ArgumentNullException()) };
yield return new object[] { new VerificationException() };
yield return new object[] { new WaitHandleCannotBeOpenedException() };
}
[Theory]
[MemberData(nameof(SerializableExceptions))]
public void Roundtrip_Exceptions(Exception expected)
{
BinaryFormatterHelpers.AssertRoundtrips(expected);
}
private static int Identity(int i) => i;
[Fact]
public void Roundtrip_Delegates_NoTarget()
{
Func<int, int> expected = Identity;
Assert.Null(expected.Target);
Func<int, int> actual = FormatterClone(expected);
Assert.NotSame(expected, actual);
Assert.Same(expected.GetMethodInfo(), actual.GetMethodInfo());
Assert.Equal(expected(42), actual(42));
}
[Fact]
public void Roundtrip_Delegates_Target()
{
var owsam = new ObjectWithStateAndMethod { State = 42 };
Func<int> expected = owsam.GetState;
Assert.Same(owsam, expected.Target);
Func<int> actual = FormatterClone(expected);
Assert.NotSame(expected, actual);
Assert.NotSame(expected.Target, actual.Target);
Assert.Equal(expected(), actual());
}
public static IEnumerable<object[]> SerializableObjectsWithFuncOfObjectToCompare()
{
object target = 42;
yield return new object[] { new Random(), new Func<object, object>(o => ((Random)o).Next()) };
}
[Theory]
[MemberData(nameof(SerializableObjectsWithFuncOfObjectToCompare))]
public void Roundtrip_ObjectsWithComparers(object obj, Func<object, object> getResult)
{
object actual = FormatterClone(obj);
Assert.Equal(getResult(obj), getResult(actual));
}
public static IEnumerable<object[]> ValidateNonSerializableTypes_MemberData()
{
foreach (object obj in NonSerializableObjects())
{
foreach (FormatterAssemblyStyle assemblyFormat in new[] { FormatterAssemblyStyle.Full, FormatterAssemblyStyle.Simple })
{
foreach (TypeFilterLevel filterLevel in new[] { TypeFilterLevel.Full, TypeFilterLevel.Low })
{
foreach (FormatterTypeStyle typeFormat in new[] { FormatterTypeStyle.TypesAlways, FormatterTypeStyle.TypesWhenNeeded, FormatterTypeStyle.XsdString })
{
yield return new object[] { obj, assemblyFormat, filterLevel, typeFormat };
}
}
}
}
}
[Theory]
[MemberData(nameof(ValidateNonSerializableTypes_MemberData))]
public void ValidateNonSerializableTypes(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat)
{
var f = new BinaryFormatter()
{
AssemblyFormat = assemblyFormat,
FilterLevel = filterLevel,
TypeFormat = typeFormat
};
using (var s = new MemoryStream())
{
Assert.Throws<SerializationException>(() => f.Serialize(s, obj));
}
}
[Fact]
public void SerializeNonSerializableTypeWithSurrogate()
{
var p = new NonSerializablePair<int, string>() { Value1 = 1, Value2 = "2" };
Assert.False(p.GetType().IsSerializable);
Assert.Throws<SerializationException>(() => FormatterClone(p));
NonSerializablePair<int, string> result = FormatterClone(p, new NonSerializablePairSurrogate());
Assert.NotSame(p, result);
Assert.Equal(p.Value1, result.Value1);
Assert.Equal(p.Value2, result.Value2);
}
[Fact]
public void SerializationEvents_FireAsExpected()
{
var f = new BinaryFormatter();
var obj = new IncrementCountsDuringRoundtrip(null);
Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
using (var s = new MemoryStream())
{
f.Serialize(s, obj);
s.Position = 0;
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
var result = (IncrementCountsDuringRoundtrip)f.Deserialize(s);
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.IncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod);
}
}
[Fact]
public void SerializationEvents_DerivedTypeWithEvents_FireAsExpected()
{
var f = new BinaryFormatter();
var obj = new DerivedIncrementCountsDuringRoundtrip(null);
Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
using (var s = new MemoryStream())
{
f.Serialize(s, obj);
s.Position = 0;
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
var result = (DerivedIncrementCountsDuringRoundtrip)f.Deserialize(s);
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.IncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializedMethod);
}
}
[Fact]
public void Properties_Roundtrip()
{
var f = new BinaryFormatter();
Assert.Null(f.Binder);
var binder = new DelegateBinder();
f.Binder = binder;
Assert.Same(binder, f.Binder);
Assert.NotNull(f.Context);
Assert.Null(f.Context.Context);
Assert.Equal(StreamingContextStates.All, f.Context.State);
var context = new StreamingContext(StreamingContextStates.Clone);
f.Context = context;
Assert.Equal(StreamingContextStates.Clone, f.Context.State);
Assert.Null(f.SurrogateSelector);
var selector = new SurrogateSelector();
f.SurrogateSelector = selector;
Assert.Same(selector, f.SurrogateSelector);
Assert.Equal(FormatterAssemblyStyle.Simple, f.AssemblyFormat);
f.AssemblyFormat = FormatterAssemblyStyle.Full;
Assert.Equal(FormatterAssemblyStyle.Full, f.AssemblyFormat);
Assert.Equal(TypeFilterLevel.Full, f.FilterLevel);
f.FilterLevel = TypeFilterLevel.Low;
Assert.Equal(TypeFilterLevel.Low, f.FilterLevel);
Assert.Equal(FormatterTypeStyle.TypesAlways, f.TypeFormat);
f.TypeFormat = FormatterTypeStyle.XsdString;
Assert.Equal(FormatterTypeStyle.XsdString, f.TypeFormat);
}
[Fact]
public void SerializeDeserialize_InvalidArguments_ThrowsException()
{
var f = new BinaryFormatter();
AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Serialize(null, new object()));
AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Deserialize(null));
Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream())); // seekable, 0-length
}
[Theory]
[InlineData(FormatterAssemblyStyle.Simple, false)]
[InlineData(FormatterAssemblyStyle.Full, true)]
public void MissingField_FailsWithAppropriateStyle(FormatterAssemblyStyle style, bool exceptionExpected)
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, new Version1ClassWithoutField());
s.Position = 0;
f = new BinaryFormatter() { AssemblyFormat = style };
f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithoutOptionalField) };
if (exceptionExpected)
{
Assert.Throws<SerializationException>(() => f.Deserialize(s));
}
else
{
var result = (Version2ClassWithoutOptionalField)f.Deserialize(s);
Assert.NotNull(result);
Assert.Equal(null, result.Value);
}
}
[Theory]
[InlineData(FormatterAssemblyStyle.Simple)]
[InlineData(FormatterAssemblyStyle.Full)]
public void OptionalField_Missing_Success(FormatterAssemblyStyle style)
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, new Version1ClassWithoutField());
s.Position = 0;
f = new BinaryFormatter() { AssemblyFormat = style };
f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithOptionalField) };
var result = (Version2ClassWithOptionalField)f.Deserialize(s);
Assert.NotNull(result);
Assert.Equal(null, result.Value);
}
[Fact]
public void ObjectReference_RealObjectSerialized()
{
var obj = new ObjRefReturnsObj { Real = 42 };
object real = FormatterClone<object>(obj);
Assert.Equal(42, real);
}
public static IEnumerable<object[]> Deserialize_FuzzInput_MemberData()
{
var rand = new Random(42);
foreach (object obj in SerializableObjects())
{
const int FuzzingsPerObject = 3;
for (int i = 0; i < FuzzingsPerObject; i++)
{
yield return new object[] { obj, rand, i };
}
}
}
[OuterLoop]
[Theory]
[MemberData(nameof(Deserialize_FuzzInput_MemberData))]
public void Deserialize_FuzzInput(object obj, Random rand, int fuzzTrial)
{
// Get the serialized data for the object
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, obj);
// Make some "random" changes to it
byte[] data = s.ToArray();
for (int i = 1; i < rand.Next(1, 100); i++)
{
data[rand.Next(data.Length)] = (byte)rand.Next(256);
}
// Try to deserialize that.
try
{
f.Deserialize(new MemoryStream(data));
// Since there's no checksum, it's possible we changed data that didn't corrupt the instance
}
catch (ArgumentOutOfRangeException) { }
catch (ArrayTypeMismatchException) { }
catch (DecoderFallbackException) { }
catch (FormatException) { }
catch (IndexOutOfRangeException) { }
catch (InvalidCastException) { }
catch (OutOfMemoryException) { }
catch (OverflowException) { }
catch (NullReferenceException) { }
catch (SerializationException) { }
catch (TargetInvocationException) { }
}
[Fact]
public void Deserialize_EndOfStream_ThrowsException()
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, 1024);
for (long i = s.Length - 1; i >= 0; i--)
{
s.Position = 0;
var data = new byte[i];
Assert.Equal(data.Length, s.Read(data, 0, data.Length));
Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream(data)));
}
}
public static IEnumerable<object[]> Roundtrip_CrossProcess_MemberData()
{
// Just a few objects to verify we can roundtrip out of process memory
yield return new object[] { "test" };
yield return new object[] { new List<int> { 1, 2, 3, 4, 5 } };
yield return new object[] { new Tree<int>(1, new Tree<int>(2, new Tree<int>(3, null, null), new Tree<int>(4, null, null)), new Tree<int>(5, null, null)) };
}
[Theory]
[MemberData(nameof(Roundtrip_CrossProcess_MemberData))]
public void Roundtrip_CrossProcess(object obj)
{
string outputPath = GetTestFilePath();
string inputPath = GetTestFilePath();
// Serialize out to a file
using (FileStream fs = File.OpenWrite(outputPath))
{
new BinaryFormatter().Serialize(fs, obj);
}
// In another process, deserialize from that file and serialize to another
RemoteInvoke((remoteInput, remoteOutput) =>
{
Assert.False(File.Exists(remoteOutput));
using (FileStream input = File.OpenRead(remoteInput))
using (FileStream output = File.OpenWrite(remoteOutput))
{
var b = new BinaryFormatter();
b.Serialize(output, b.Deserialize(input));
return SuccessExitCode;
}
}, $"\"{outputPath}\"", $"\"{inputPath}\"").Dispose();
// Deserialize what the other process serialized and compare it to the original
using (FileStream fs = File.OpenRead(inputPath))
{
object deserialized = new BinaryFormatter().Deserialize(fs);
Assert.Equal(obj, deserialized);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework fails when serializing arrays with non-zero lower bounds")]
public void Roundtrip_ArrayContainingArrayAtNonZeroLowerBound()
{
FormatterClone(Array.CreateInstance(typeof(uint[]), new[] { 5 }, new[] { 1 }));
}
private class DelegateBinder : SerializationBinder
{
public Func<string, string, Type> BindToTypeDelegate = null;
public override Type BindToType(string assemblyName, string typeName) => BindToTypeDelegate?.Invoke(assemblyName, typeName);
}
private static T FormatterClone<T>(
T obj,
ISerializationSurrogate surrogate = null,
FormatterAssemblyStyle assemblyFormat = FormatterAssemblyStyle.Full,
TypeFilterLevel filterLevel = TypeFilterLevel.Full,
FormatterTypeStyle typeFormat = FormatterTypeStyle.TypesAlways)
{
BinaryFormatter f;
if (surrogate == null)
{
f = new BinaryFormatter();
}
else
{
var c = new StreamingContext();
var s = new SurrogateSelector();
s.AddSurrogate(obj.GetType(), c, surrogate);
f = new BinaryFormatter(s, c);
}
f.AssemblyFormat = assemblyFormat;
f.FilterLevel = filterLevel;
f.TypeFormat = typeFormat;
using (var s = new MemoryStream())
{
f.Serialize(s, obj);
Assert.NotEqual(0, s.Position);
s.Position = 0;
return (T)(f.Deserialize(s));
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.DeviceModels.Chipset.LPC3180.Drivers
{
using System;
using System.Runtime.CompilerServices;
using RT = Microsoft.Zelig.Runtime;
public abstract class RealTimeClock
{
public delegate void Callback( Timer timer, ulong currentTime );
public class Timer
{
//
// State
//
private RealTimeClock m_owner;
private RT.KernelNode< Timer > m_node;
private ulong m_timeout;
private Callback m_callback;
//
// Constructor Methods
//
internal Timer( RealTimeClock owner ,
Callback callback )
{
m_owner = owner;
m_node = new RT.KernelNode< Timer >( this );
m_callback = callback;
}
//
// Helper Methods
//
public void Cancel()
{
m_owner.Deregister( this );
}
internal void Invoke( ulong currentTime )
{
m_callback( this, currentTime );
}
//
// Access Methods
//
internal RT.KernelNode< Timer > Node
{
get
{
return m_node;
}
}
public ulong Timeout
{
get
{
return m_timeout;
}
set
{
m_timeout = value;
m_owner.Register( this );
}
}
public ulong RelativeTimeout
{
get
{
return m_timeout - RealTimeClock.Instance.CurrentTime;
}
set
{
m_timeout = value + RealTimeClock.Instance.CurrentTime;
m_owner.Register( this );
}
}
}
//
// State
//
const uint c_QuarterCycle = 0x40000000u;
const uint c_OverflowFlag = 0x80000000u;
private uint m_lastCount;
private uint m_highPart;
private InterruptController.Handler m_interrupt;
private RT.KernelList< Timer > m_timers;
//
// Helper Methods
//
public void Initialize()
{
m_timers = new RT.KernelList< Timer >();
m_interrupt = InterruptController.Handler.Create( LPC3180.INTC.IRQ_INDEX_MSTIMER_INT, InterruptSettings.ActiveHigh, ProcessTimeout );
//--//
LPC3180.MilliSecondTimer timer = LPC3180.MilliSecondTimer.Instance;
timer.MSTIM_COUNTER = 0;
//
// No interrupts for now.
//
{
var val = new MilliSecondTimer.MSTIM_MCTRL_bitfield();
val.MR0_INT = false;
val.MR1_INT = false;
timer.MSTIM_MCTRL = val;
}
{
var val = new MilliSecondTimer.MSTIM_CTRL_bitfield();
val.COUNT_ENAB = true;
val.PAUSE_EN = true; // Allow hardware debugging to stop the counter.
timer.MSTIM_CTRL = val;
}
InterruptController.Instance.RegisterAndEnable( m_interrupt );
Refresh();
}
public Timer CreateTimer( Callback callback )
{
return new Timer( this, callback );
}
//--//
private void Register( Timer timer )
{
RT.KernelNode< Timer > node = timer.Node;
node.RemoveFromList();
ulong timeout = timer.Timeout;
RT.KernelNode< Timer > node2 = m_timers.StartOfForwardWalk;
while(node2.IsValidForForwardMove)
{
if(node2.Target.Timeout > timeout)
{
break;
}
node2 = node2.Next;
}
node.InsertBefore( node2 );
Refresh();
}
private void Deregister( Timer timer )
{
var node = timer.Node;
if(node.IsLinked)
{
node.RemoveFromList();
Refresh();
}
}
//--//
private void ProcessTimeout( InterruptController.Handler handler )
{
ulong currentTime = this.CurrentTime;
while(true)
{
RT.KernelNode< Timer > node = m_timers.StartOfForwardWalk;
if(node.IsValidForForwardMove == false)
{
break;
}
if(node.Target.Timeout > currentTime)
{
break;
}
node.RemoveFromList();
node.Target.Invoke( currentTime );
}
Refresh();
}
void Refresh()
{
Timer target = m_timers.FirstTarget();
ulong timeout;
if(target != null)
{
timeout = target.Timeout;
}
else
{
timeout = ulong.MaxValue;
}
//--//
ulong now = this.CurrentTime;
//
// Timeout in the past? Trigger the match now.
//
if(now > timeout)
{
timeout = now;
}
//
// Timeout too far in the future? Generate match closer in time, so we handle wrap arounds.
//
if(now + c_QuarterCycle < timeout)
{
timeout = now + c_QuarterCycle;
}
uint timeoutLow = (uint)timeout;
LPC3180.MilliSecondTimer timer = LPC3180.MilliSecondTimer.Instance;
//
// Create two matches, to protect against race conditions (at least one will fire).
//
timer.MSTIM_MATCH0 = timeoutLow;
timer.MSTIM_MATCH1 = timeoutLow + 1;
//
// Configure interrupts.
//
{
var val = new MilliSecondTimer.MSTIM_MCTRL_bitfield();
val.MR0_INT = true;
val.MR1_INT = true;
timer.MSTIM_MCTRL = val;
}
//
// Clear previous interrupts.
//
{
var val = new MilliSecondTimer.MSTIM_INT_bitfield();
val.MATCH0_INT = true;
val.MATCH1_INT = true;
timer.MSTIM_INT = val;
}
//
// Configure the Start Controller.
//
var ctrl = LPC3180.SystemControl.Instance;
ctrl.START_ER_INT |= LPC3180.SystemControl.START_INT.MSTIMER_INT;
ctrl.START_APR_INT |= LPC3180.SystemControl.START_INT.MSTIMER_INT;
}
//
// Access Methods
//
public static extern RealTimeClock Instance
{
[RT.SingletonFactory()]
[MethodImpl( MethodImplOptions.InternalCall )]
get;
}
public ulong CurrentTime
{
get
{
using(RT.SmartHandles.InterruptState.Disable())
{
uint value = LPC3180.MilliSecondTimer.Instance.MSTIM_COUNTER;
uint highPart = m_highPart;
//
// Wrap around? Update high part.
//
if(((value ^ m_lastCount) & c_OverflowFlag) != 0)
{
highPart++;
m_lastCount = value;
m_highPart = highPart;
}
return (ulong)highPart << 32 | value;
}
}
}
}
}
| |
#if !WINRT || UNITY_EDITOR
using System;
using System.Net;
using System.Net.Sockets;
namespace LiteNetLib
{
public sealed class NetEndPoint
{
public string Host { get { return EndPoint.Address.ToString(); } }
public int Port { get { return EndPoint.Port; } }
internal readonly IPEndPoint EndPoint;
internal NetEndPoint(IPEndPoint ipEndPoint)
{
EndPoint = ipEndPoint;
}
public override bool Equals(object obj)
{
if (!(obj is NetEndPoint))
{
return false;
}
return EndPoint.Equals(((NetEndPoint)obj).EndPoint);
}
public override string ToString()
{
return EndPoint.ToString();
}
public override int GetHashCode()
{
return EndPoint.GetHashCode();
}
public NetEndPoint(string hostStr, int port)
{
IPAddress ipAddress;
if (!IPAddress.TryParse(hostStr, out ipAddress))
{
if (Socket.OSSupportsIPv6)
{
if (hostStr == "localhost")
{
ipAddress = IPAddress.IPv6Loopback;
}
else
{
ipAddress = ResolveAddress(hostStr, AddressFamily.InterNetworkV6);
}
}
if (ipAddress == null)
{
ipAddress = ResolveAddress(hostStr, AddressFamily.InterNetwork);
}
}
if (ipAddress == null)
{
throw new Exception("Invalid address: " + hostStr);
}
EndPoint = new IPEndPoint(ipAddress, port);
}
private IPAddress ResolveAddress(string hostStr, AddressFamily addressFamily)
{
#if NETCORE
var hostTask = Dns.GetHostEntryAsync(hostStr);
hostTask.Wait();
var host = hostTask.Result;
#else
var host = Dns.GetHostEntry(hostStr);
#endif
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == addressFamily)
{
return ip;
}
}
return null;
}
internal long GetId()
{
byte[] addr = EndPoint.Address.GetAddressBytes();
long id = 0;
if (addr.Length == 4) //IPv4
{
id = addr[0];
id |= (long)addr[1] << 8;
id |= (long)addr[2] << 16;
id |= (long)addr[3] << 24;
id |= (long)EndPoint.Port << 32;
}
else if (addr.Length == 16) //IPv6
{
id = addr[0] ^ addr[8];
id |= (long)(addr[1] ^ addr[9]) << 8;
id |= (long)(addr[2] ^ addr[10]) << 16;
id |= (long)(addr[3] ^ addr[11]) << 24;
id |= (long)(addr[4] ^ addr[12]) << 32;
id |= (long)(addr[5] ^ addr[13]) << 40;
id |= (long)(addr[6] ^ addr[14]) << 48;
id |= (long)(Port ^ addr[7] ^ addr[15]) << 56;
}
return id;
}
}
}
#else
using System;
using Windows.Networking;
using Windows.Networking.Sockets;
namespace LiteNetLib
{
public sealed class NetEndPoint
{
public string Host { get { return HostName.DisplayName; } }
public int Port { get; private set; }
internal readonly HostName HostName;
internal readonly string PortStr;
internal NetEndPoint(int port)
{
HostName = null;
PortStr = port.ToString();
Port = port;
}
public override bool Equals(object obj)
{
if (!(obj is NetEndPoint))
{
return false;
}
NetEndPoint other = (NetEndPoint) obj;
return HostName.IsEqual(other.HostName) && PortStr.Equals(other.PortStr);
}
public override int GetHashCode()
{
return HostName.CanonicalName.GetHashCode() ^ PortStr.GetHashCode();
}
internal long GetId()
{
//Check locals
if (HostName == null)
{
return ParseIpToId("0.0.0.0");
}
if (HostName.DisplayName == "localhost")
{
return ParseIpToId("127.0.0.1");
}
//Check remote
string hostIp = string.Empty;
var task = DatagramSocket.GetEndpointPairsAsync(HostName, "0").AsTask();
task.Wait();
//IPv4
foreach (var endpointPair in task.Result)
{
hostIp = endpointPair.RemoteHostName.CanonicalName;
if (endpointPair.RemoteHostName.Type == HostNameType.Ipv4)
{
return ParseIpToId(hostIp);
}
}
//Else
return hostIp.GetHashCode() ^ Port;
}
private long ParseIpToId(string hostIp)
{
long id = 0;
string[] ip = hostIp.Split('.');
id |= long.Parse(ip[0]);
id |= long.Parse(ip[1]) << 8;
id |= long.Parse(ip[2]) << 16;
id |= long.Parse(ip[3]) << 24;
id |= (long)Port << 32;
return id;
}
public override string ToString()
{
return HostName.CanonicalName + ":" + PortStr;
}
public NetEndPoint(string hostName, int port)
{
var task = DatagramSocket.GetEndpointPairsAsync(new HostName(hostName), port.ToString()).AsTask();
task.Wait();
HostName = task.Result[0].RemoteHostName;
Port = port;
PortStr = port.ToString();
}
internal NetEndPoint(HostName hostName, string port)
{
HostName = hostName;
Port = int.Parse(port);
PortStr = port;
}
}
}
#endif
| |
/* VRPhysicsConstraintFixed
* MiddleVR
* (c) MiddleVR
*/
using UnityEngine;
using System;
using System.Collections;
using MiddleVR_Unity3D;
[AddComponentMenu("MiddleVR/Physics/Constraints/Fixed")]
[RequireComponent(typeof(VRPhysicsBody))]
public class VRPhysicsConstraintFixed : MonoBehaviour {
#region Member Variables
[SerializeField]
private GameObject m_ConnectedBody = null;
private vrPhysicsConstraintFixed m_PhysicsConstraint = null;
private string m_PhysicsConstraintName = "";
private bool m_AttemptedToAddConstraint = false;
private vrEventListener m_MVREventListener = null;
#endregion
#region Member Properties
public vrPhysicsConstraintFixed PhysicsConstraint
{
get
{
return m_PhysicsConstraint;
}
}
public string PhysicsConstraintName
{
get
{
return m_PhysicsConstraintName;
}
}
public GameObject ConnectedBody
{
get
{
return m_ConnectedBody;
}
set
{
m_ConnectedBody = value;
}
}
#endregion
#region MonoBehaviour Member Functions
protected void Start()
{
if (MiddleVR.VRClusterMgr.IsCluster() && !MiddleVR.VRClusterMgr.IsServer())
{
enabled = false;
return;
}
if (MiddleVR.VRPhysicsMgr == null)
{
MiddleVRTools.Log(0, "No PhysicsManager found when creating a fixed constraint.");
return;
}
vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine();
if (physicsEngine == null)
{
return;
}
if (m_PhysicsConstraint == null)
{
m_PhysicsConstraint = physicsEngine.CreateConstraintFixedWithUniqueName(name);
if (m_PhysicsConstraint == null)
{
MiddleVRTools.Log(0, "[X] Could not create a fixed physics constraint for '"
+ name + "'.");
}
else
{
GC.SuppressFinalize(m_PhysicsConstraint);
m_MVREventListener = new vrEventListener(OnMVRNodeDestroy);
m_PhysicsConstraint.AddEventListener(m_MVREventListener);
m_PhysicsConstraintName = m_PhysicsConstraint.GetName();
}
}
}
protected void OnDestroy()
{
if (m_PhysicsConstraint == null)
{
return;
}
if (MiddleVR.VRPhysicsMgr == null)
{
return;
}
vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine();
if (physicsEngine == null)
{
return;
}
physicsEngine.DestroyConstraint(m_PhysicsConstraintName);
m_PhysicsConstraint = null;
m_PhysicsConstraintName = "";
}
protected void Update()
{
if (!m_AttemptedToAddConstraint)
{
AddConstraint();
m_AttemptedToAddConstraint = true;
}
}
#endregion
#region VRPhysicsConstraintFixed Functions
protected bool AddConstraint()
{
vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine();
if (physicsEngine == null)
{
return false;
}
if (m_PhysicsConstraint == null)
{
return false;
}
bool addedToSimulation = false;
// Cannot fail since we require this component.
VRPhysicsBody body0 = GetComponent<VRPhysicsBody>();
VRPhysicsBody body1 = null;
if (m_ConnectedBody != null)
{
body1 = m_ConnectedBody.GetComponent<VRPhysicsBody>();
}
if (body0.PhysicsBody != null)
{
m_PhysicsConstraint.SetBody(0, body0.PhysicsBody);
m_PhysicsConstraint.SetBody(1, body1 != null ? body1.PhysicsBody : null);
addedToSimulation = physicsEngine.AddConstraint(m_PhysicsConstraint);
if (addedToSimulation)
{
MiddleVRTools.Log(3, "[ ] The constraint '" + m_PhysicsConstraintName +
"' was added to the physics simulation.");
}
else
{
MiddleVRTools.Log(3, "[X] Failed to add the constraint '" +
m_PhysicsConstraintName + "' to the physics simulation.");
}
}
else
{
MiddleVRTools.Log(0, "[X] The PhysicsBody of '" + name +
"' for the fixed physics constraint '" + m_PhysicsConstraintName +
"' is null.");
}
return addedToSimulation;
}
private bool OnMVRNodeDestroy(vrEvent iBaseEvt)
{
vrObjectEvent e = vrObjectEvent.Cast(iBaseEvt);
if (e != null)
{
if (e.ComesFrom(m_PhysicsConstraint))
{
if (e.eventType == (int)VRObjectEventEnum.VRObjectEvent_Destroy)
{
// Killed in MiddleVR so delete it in C#.
m_PhysicsConstraint.Dispose();
}
}
}
return true;
}
#endregion
}
| |
/*
* HaoRan ImageFilter Classes v0.1
* Copyright (C) 2012 Zhenjun Dai
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation.
*/
using System;
using System.Collections.Generic;
using Windows.UI;
namespace Shagu.ImageFilter
{
public class Palette
{
public byte[] Blue;
public byte[] Green;
public int Length;
public byte[] Red;
public Palette(int length)
{
this.Length = length;
this.Red = new byte[length];
this.Green = new byte[length];
this.Blue = new byte[length];
}
}
public class TintColors
{
public static Color LightCyan()
{
return Color.FromArgb(255, 0xeb, 0xf5, 0xe1);
}
public static Color Sepia()
{
return Color.FromArgb(255, 230, 179, 179);
}
}
public class Gradient
{
public List<Color> MapColors;
public Gradient()
{
List<Color> list = new List<Color>();
list.Add(Colors.Black);
list.Add(Colors.White);
this.MapColors = list;
}
public Gradient(List<Color> colors)
{
this.MapColors = colors;
}
private Palette CreateGradient(List<Color> colors, int length)
{
if (colors == null || colors.Count < 2)
{
return null;
}
Palette palette = new Palette(length);
byte[] red = palette.Red;
byte[] green = palette.Green;
byte[] blue = palette.Blue;
int num = length / (colors.Count - 1);
float num1 = 1f / ((float)num);
int index = 0;
Color rgb = colors[0];
int colorR = rgb.R;
int colorG = rgb.G;
int colorB = rgb.B;
for (int i = 1; i < colors.Count; i++)
{
int r = colors[i].R;
int g = colors[i].G;
int b = colors[i].B;
for (int j = 0; j < num; j++)
{
float num2 = j * num1;
int rr = colorR + ((int)((r - colorR) * num2));
int gg = colorG + ((int)((g - colorG) * num2));
int bb = colorB + ((int)((b - colorB) * num2));
red[index] = (byte)(rr > 0xff ? 0xff : ((rr < 0) ? 0 : rr));
green[index] = (byte)(gg > 0xff ? 0xff : ((gg < 0) ? 0 : gg));
blue[index] = (byte)(bb > 0xff ? 0xff : ((bb < 0) ? 0 : bb));
index++;
}
colorR = r;
colorG = g;
colorB = b;
}
if (index < length)
{
red[index] = red[index - 1];
green[index] = green[index - 1];
blue[index] = blue[index - 1];
}
return palette;
}
public Palette CreatePalette(int length)
{
return CreateGradient(this.MapColors, length);
}
public static Gradient BlackSepia()
{
List<Color> colors = new List<Color>();
colors.Add(Colors.Black);
colors.Add(TintColors.Sepia());
return new Gradient(colors);
}
public static Gradient WhiteSepia()
{
List<Color> colors = new List<Color>();
colors.Add(Colors.White);
colors.Add(TintColors.Sepia());
return new Gradient(colors);
}
public static Gradient RainBow()
{
List<Color> colors = new List<Color>();
colors.Add(Colors.Red);
colors.Add(Colors.Magenta);
colors.Add(Colors.Blue);
colors.Add(Colors.Cyan);
colors.Add(Colors.Green);
colors.Add(Colors.Yellow);
colors.Add(Colors.Red);
return new Gradient(colors);
}
public static Gradient Inverse()
{
List<Color> colors = new List<Color>();
colors.Add(Colors.White);
colors.Add(Colors.Black);
return new Gradient(colors);
}
public static Gradient Fade()
{
List<Color> colors = new List<Color>();
colors.Add(Colors.Black);
colors.Add(Color.FromArgb(255, 0xEE, 0xE8, 0xCD));//Cornsilk2 , reference http://www.wescn.com/tool/color_3.html
colors.Add(Colors.Black);
return new Gradient(colors);
}
public static Gradient Scene()
{
List<Color> colors = new List<Color>();
colors.Add(Color.FromArgb(255, 0xFF, 0xD7, 0x00));//Gold , reference http://www.wescn.com/tool/color_3.html
colors.Add(Colors.White);
colors.Add(Color.FromArgb(255, 0xFF, 0xD7, 0x00));//Gold
return new Gradient(colors);
}
public static Gradient Scene1()
{
List<Color> colors = new List<Color>();
colors.Add(Color.FromArgb(255, 0x64, 0x95, 0xED));//CornflowerBlue , reference http://www.wescn.com/tool/color_3.html
colors.Add(Colors.White);
colors.Add(Color.FromArgb(255, 0x64, 0x95, 0xED));//CornflowerBlue
return new Gradient(colors);
}
public static Gradient Scene2()
{
List<Color> colors = new List<Color>();
colors.Add(Color.FromArgb(255, 0x00, 0xBF, 0xFF));//DeepSkyBlue , reference http://www.wescn.com/tool/color_3.html
colors.Add(Color.FromArgb(255, 0xDC, 0xDC, 0xDC));//Gainsboro
colors.Add(Color.FromArgb(255, 0x00, 0xBF, 0xFF));//DeepSkyBlue
return new Gradient(colors);
}
public static Gradient Scene3()
{
List<Color> colors = new List<Color>();
colors.Add(Colors.Orange);// , reference http://www.wescn.com/tool/color_3.html
colors.Add(Colors.White);
colors.Add(Colors.Orange);//
return new Gradient(colors);
}
}
public class GradientFilter : IImageFilter
{
private Palette palette = null;
public Gradient Gradientf;
public float OriginAngleDegree;
// Methods
public GradientFilter()
{
this.OriginAngleDegree = 0f;
this.Gradientf = new Gradient();
}
public void ClearCache()
{
this.palette = null;
}
//@Override
public Image process(Image imageIn)
{
int width = imageIn.getWidth();
int height = imageIn.getHeight();
double d = this.OriginAngleDegree * 0.0174532925;
float cos = (float)System.Math.Cos(d);
float sin = (float)System.Math.Sin(d);
float radio = (cos * width) + (sin * height);
float dcos = cos * radio;
float dsin = sin * radio;
int dist = (int)System.Math.Sqrt((double)((dcos * dcos) + (dsin * dsin)));
dist = System.Math.Max(System.Math.Max(dist, width), height);
if ((this.palette == null) || (dist != this.palette.Length))
{
this.palette = this.Gradientf.CreatePalette(dist);
}
byte[] red = this.palette.Red;
byte[] green = this.palette.Green;
byte[] blue = this.palette.Blue;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
radio = (cos * j) + (sin * i);
dcos = cos * radio;
dsin = sin * radio;
dist = (int)System.Math.Sqrt((double)((dcos * dcos) + (dsin * dsin)));
imageIn.setPixelColor(j, i, red[dist], green[dist], blue[dist]);
}
}
return imageIn;
}
}
}
| |
// Copyright (c) 2007-2014 SIL International
// Licensed under the MIT license: opensource.org/licenses/MIT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using SolidGui.Engine;
namespace SolidGui.Engine
{
public class SfmRecordReader : IDisposable
{
enum StateParse
{
Header,
GotLx,
BuildValue,
BuildKey,
}
StateParse _stateParse = StateParse.Header;
TextReader _r;
private SfmRecord _record;
private string _headerLinux = "";
string _startKey = "lx"; // TODO! use global setting! -JMC
private readonly List<char> _enders = new List<char> {' ', '\t', '\r', '\n', '\\', '\0'}; // All chars that end an SFM marker (SFM key)
private static Regex ReggieLeading = new Regex(
@"^[ \t]+\\", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static Regex ReggieTab = new Regex(
@"\t", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static Regex ReggieLx = new Regex(
@"^[ \t]*\\" + SolidSettings.NewLine + @"\b", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private long _size = 0;
private int _recordStartLine;
private int _recordEndLine;
private int _recordID = -1;
// Reading state
private int _line = 1;
private int _col = 1;
private string _separator = " ";
private Encoding _encoding = SolidSettings.LegacyEncoding; //was: Encoding.GetEncoding("iso-8859-1");
#region Properties
private bool _allowLeadingWhiteSpace;
public bool AllowLeadingWhiteSpace
{
get { return _allowLeadingWhiteSpace; }
set { _allowLeadingWhiteSpace = value; }
}
/// <summary>
/// Time estimate is based on this file size estimate (units of returned size are arbitrary)
/// The number returned is usually in the int range; otherwise it'll just be the max int).
/// </summary>
public int SizeEstimate
{
get
{
long num = _size/1200 + 1; // not sure if returning 0 prematurely is ok
int ret = (num > int.MaxValue) ? int.MaxValue : (int)(num); // max of int32 is 2,147,483,647
return ret;
}
}
public int RecordID
{
get { return _recordID; }
}
public int RecordStartLine
{
get { return _recordStartLine; }
}
public int RecordEndLine
{
get { return _recordEndLine; }
}
#endregion
#region Constructors
private SfmRecordReader(TextReader stream)
{ // the location of the file
_r = stream;
_size = 1024; // a wild guess -JMC
_record = new SfmRecord();
}
private SfmRecordReader(string filePath)
{ // the location of the file
_r = new StreamReader(filePath, _encoding, false);
var fi = new FileInfo(filePath);
_size = fi.Length;
_record = new SfmRecord();
}
#endregion
public void Close()
{
_r.Close();
}
public static int ReadOneChar(TextReader r)
{
// For now, guarantee that we see all newlines as a single \n
// (That is, replace all \r\n with \n, and then all \r with \n)
// Read a tab as a space.
int c = r.Read();
if (c == -1) return c; //EOF
if (c == '\r')
{
if (r.Peek() == '\n')
{
// skip the \r
c = r.Read();
}
else
{
// convert \r to \n
c = '\n';
}
}
// Simplify tab to space.
return (c == '\t') ? ' ' : c;
}
/// <summary>
/// Goes through the stream copying it into the header until the record marker is encountered.
/// </summary>
/// <returns>left-overs that were read in but aren't header chars; typically @"\lx", or an empty string if entire stream was the header.</returns>
private string ReadHeader()
{
string ret = "";
string stopAt = "\\" + _startKey; // typically @"\lx"
int len = stopAt.Length; // typically 3
var sbMatch = new StringBuilder();
var sbHeader = new StringBuilder();
int tmp; // it's so annoying that we need this
char c;
int L = 0;
while (true)
{
tmp = ReadOneChar(_r); //or two, in the case of \r\n
if (tmp == -1)
{
break; // EOF
}
c = (char) tmp;
// Append what we find; though we'll have to back out the last (len) chars
if (c == '\n')
{
sbMatch.Clear(); // no match; start over
_col = 1;
_line++;
sbHeader.Append(SolidSettings.NewLine);
}
else
{
sbHeader.Append(c);
_col++;
}
L = sbMatch.Length; // the current length of a possible match
if (c == stopAt[L] && _col-1 == L+1)
{
sbMatch.Append(c); // still matches
}
else
{
sbMatch.Length = 0; // no match; start over; equivalent to sbMatch.Clear();
}
if (sbMatch.Length == len)
{
// we've found \lx, but does it end?
tmp = _r.Peek();
if ( tmp == -1 || _enders.Contains((char)tmp) )
{
// yes, end of marker (key)
sbHeader.Remove(sbHeader.Length - len, len);
ret = stopAt;
_stateParse = StateParse.GotLx;
// discard separator for now (usually the space in @"\lx ")
_separator = "" + (char)ReadOneChar(_r);
break;
}
// no match; start over (e.g. @"\lxhaha" isn't a match
sbMatch.Length=0;
}
}
_headerLinux = sbHeader.ToString();
return ret;
}
// Read in ONE record from the text stream (into the Record property), OR returns false if no more records in stream.
// Calling code should also check whether the Header property is non-empty after calling this.
public bool ReadRecord()
{
bool retval = false;
_record.Clear(); // but don't clear the header! (nor the separator)
if (_stateParse == StateParse.Header)
{
ReadHeader();
}
SfmField currentField = new SfmField();
if (_stateParse == StateParse.GotLx)
{
retval = true;
currentField.Marker = _startKey;
_recordID++;
_stateParse = StateParse.BuildValue;
}
else if (_r.Peek() == -1) //EOF
{
return false;
}
else
{
Trace.Assert(_r.Read() == 0, "There is a bug in ReadRecord; please let the developers know.");
return false;
}
StringBuilder sb = new StringBuilder(2048);
int temp = -1;
char curr = '\0';
string stemp = "";
_recordStartLine = _line;
_recordEndLine = -1;
_col = 1;
bool eof = false;
bool initialSlash;
while (true) // look at one char or one \r\n sequence; we'll break upon hitting another lx, or on EOF
{
//temp = _r.Read();
temp = ReadOneChar(_r);
eof = temp == -1;
curr = (char)temp;
if ( (!eof) && (!_enders.Contains(curr)) ) // the typical case
{
sb.Append(curr);
_col++;
continue;
}
// It's a tab, space, newline, slash, or EOF; proceed...
if ( (curr == '\n') ) // || (curr == '\r') )
{
_col = 1;
_line++;
initialSlash = false;
}
else
{
initialSlash = ((_col == 1) && (curr == '\\'));
_col++;
}
if (_stateParse == StateParse.BuildKey)
{
// end of field marker
_separator = "" + curr;
stemp = sb.ToString();
if (stemp == _startKey)
{
_stateParse = StateParse.GotLx;
break;
}
currentField.Marker = stemp;
currentField.SourceLine = (curr == '\n') ? _line - 1 : _line;
sb.Length=0;
_stateParse = StateParse.BuildValue;
if (eof)
{
_record.Add(currentField);
break;
}
if (curr == '\n')
{
if ((char) _r.Peek() == '\\') // no data
{
// end of field value (duplicate code below)
currentField.SetSplitValue(sb.ToString(), _separator);
_record.Add(currentField);
sb.Length=0;
currentField = new SfmField(); // clear
_stateParse = StateParse.BuildKey;
_r.Read(); //toss the upcoming slash
_col = 2;
}
}
}
else if (_stateParse == StateParse.BuildValue)
{
if (curr == '\n')
{
sb.Append(SolidSettings.NewLine);
}
else if (!eof && !initialSlash)
{
sb.Append(curr);
}
if (initialSlash || eof)
{
// end of field value (duplicate code above)
currentField.SetSplitValue(sb.ToString(), _separator);
_record.Add(currentField);
sb.Length=0;
currentField = new SfmField(); // clear
_stateParse = StateParse.BuildKey;
}
}
if (eof) break;
}
// Determine _recordEndLine (usually = _line - 1)
_recordEndLine = (_stateParse == StateParse.GotLx) ? _line - 1 : _line;
_recordEndLine = (curr == '\n') ? _recordEndLine - 1 : _recordEndLine;
// So, there's a max of -2 total, which occurs when a record is followed by "\lx\n"
// The minimum is -0, when a record ends in EOF.
return retval;
}
public int FieldCount
{
get
{
return _record.Count;
}
}
public string this[int i]
{
get
{
return Value(i);
}
}
public string HeaderLinux
{
get
{
return _headerLinux;
}
}
public static string HeaderToWrite(string headerLinux, string newLine)
{
string tmp = headerLinux.Replace("\r\n", "\n");
tmp = tmp.Replace("\r", "\n");
return tmp.Replace("\n", newLine); //TODO: a single regex would be better, replacing (\r|\r?\n) with newLine -JMC
}
public SfmRecord Record
{
get
{
return _record;
}
}
public IEnumerable<SfmField> Fields
{
get { return _record; }
}
public SfmField Field(int i)
{
return _record[i];
}
public string Key(int i)
{
return _record[i].Marker;
}
public string Value(int i)
{
return _record[i].Value;
}
public string Value(string key)
{
SfmField result = _record.Find( (SfmField item) => { return item.Marker == key; });
if (result == null)
{
throw new ArgumentOutOfRangeException("key");
}
return result.Value;
}
public string Trailing(string key)
{
SfmField result = _record.Find( (SfmField item) => { return item.Marker == key; });
if (result == null)
{
throw new ArgumentOutOfRangeException("key");
}
return result.Trailing;
}
// Given a string, read it in as one or more records. -JMC
public static SfmRecordReader CreateFromText(string text)
{
// Start with regex cleanup to remove tabs, and leading spaces -JMC 2013-09
string s = ReggieLeading.Replace(text, "\\");
s = ReggieTab.Replace(s, " ");
var stream = new StringReader(s);
return new SfmRecordReader(stream);
}
public static SfmRecordReader CreateFromFilePath(string filePath)
{
return new SfmRecordReader(filePath);
}
public void Dispose()
{
_r.Dispose();
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System.Collections;
using System;
using System.IO;
using System.Text;
using NPOI.Util;
/**
* Title: COLINFO Record<p/>
* Description: Defines with width and formatting for a range of columns<p/>
* REFERENCE: PG 293 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)<p/>
* @author Andrew C. Oliver (acoliver at apache dot org)
* @version 2.0-pre
*/
internal class ColumnInfoRecord : StandardRecord
{
public const short sid = 0x7d;
private int _first_col;
private int _last_col;
private int _col_width;
private int _xf_index;
private int _options;
private static BitField hidden = BitFieldFactory.GetInstance(0x01);
private static BitField outlevel = BitFieldFactory.GetInstance(0x0700);
private static BitField collapsed = BitFieldFactory.GetInstance(0x1000);
// Excel seems Write values 2, 10, and 260, even though spec says "must be zero"
private int field_6_reserved;
public ColumnInfoRecord()
{
this.ColumnWidth = 2275;
_options = 2;
_xf_index = 0x0f;
field_6_reserved = 2; // seems to be the most common value
}
/**
* Constructs a ColumnInfo record and Sets its fields appropriately
* @param in the RecordInputstream to Read the record from
*/
public ColumnInfoRecord(RecordInputStream in1)
{
_first_col = in1.ReadUShort();
_last_col = in1.ReadUShort();
_col_width = in1.ReadUShort();
_xf_index = in1.ReadUShort();
_options = in1.ReadUShort();
switch (in1.Remaining)
{
case 2: // usual case
field_6_reserved = in1.ReadUShort();
break;
case 1:
// often COLINFO Gets encoded 1 byte short
// shouldn't matter because this field Is Unused
field_6_reserved = in1.ReadByte();
break;
case 0:
// According to bugzilla 48332,
// "SoftArtisans OfficeWriter for Excel" totally skips field 6
// Excel seems to be OK with this, and assumes zero.
field_6_reserved = 0;
break;
default:
throw new Exception("Unusual record size remaining=(" + in1.Remaining + ")");
}
}
/**
* @return true if the format, options and column width match
*/
public bool FormatMatches(ColumnInfoRecord other)
{
if (_xf_index != other._xf_index)
{
return false;
}
if (_options != other._options)
{
return false;
}
if (_col_width != other._col_width)
{
return false;
}
return true;
}
/**
* Get the first column this record defines formatting info for
* @return the first column index (0-based)
*/
public int FirstColumn
{
get{return _first_col;}
set { _first_col = value; }
}
/**
* Get the last column this record defines formatting info for
* @return the last column index (0-based)
*/
public int LastColumn
{
get { return _last_col; }
set { _last_col = value; }
}
/**
* Get the columns' width in 1/256 of a Char width
* @return column width
*/
public int ColumnWidth
{
get
{
return _col_width;
}
set { _col_width = value; }
}
/**
* Get the columns' default format info
* @return the extended format index
* @see org.apache.poi.hssf.record.ExtendedFormatRecord
*/
public int XFIndex
{
get { return _xf_index; }
set { _xf_index = value; }
}
/**
* Get the options bitfield - use the bitSetters instead
* @return the bitfield raw value
*/
public int Options
{
get { return _options; }
set { _options = value; }
}
// start options bitfield
/**
* Get whether or not these cells are hidden
* @return whether the cells are hidden.
* @see #SetOptions(short)
*/
public bool IsHidden
{
get { return hidden.IsSet(_options); }
set { _options = hidden.SetBoolean(_options, value); }
}
/**
* Get the outline level for the cells
* @see #SetOptions(short)
* @return outline level for the cells
*/
public int OutlineLevel
{
get { return outlevel.GetValue(_options); }
set { _options = outlevel.SetValue(_options, value); }
}
/**
* Get whether the cells are collapsed
* @return wether the cells are collapsed
* @see #SetOptions(short)
*/
public bool IsCollapsed
{
get { return collapsed.IsSet(_options); }
set
{
_options = collapsed.SetBoolean(_options,
value);
}
}
public override short Sid
{
get { return sid; }
}
public bool ContainsColumn(int columnIndex)
{
return _first_col <= columnIndex && columnIndex <= _last_col;
}
public bool IsAdjacentBefore(ColumnInfoRecord other)
{
return _last_col == other._first_col - 1;
}
protected override int DataSize
{
get { return 12; }
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(FirstColumn);
out1.WriteShort(LastColumn);
out1.WriteShort(ColumnWidth);
out1.WriteShort(XFIndex);
out1.WriteShort(_options);
out1.WriteShort(field_6_reserved);
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[COLINFO]\n");
buffer.Append("colfirst = ").Append(FirstColumn)
.Append("\n");
buffer.Append("collast = ").Append(LastColumn)
.Append("\n");
buffer.Append("colwidth = ").Append(ColumnWidth)
.Append("\n");
buffer.Append("xFindex = ").Append(XFIndex).Append("\n");
buffer.Append("options = ").Append(Options).Append("\n");
buffer.Append(" hidden = ").Append(IsHidden).Append("\n");
buffer.Append(" olevel = ").Append(OutlineLevel)
.Append("\n");
buffer.Append(" collapsed = ").Append(IsCollapsed)
.Append("\n");
buffer.Append("[/COLINFO]\n");
return buffer.ToString();
}
public override Object Clone()
{
ColumnInfoRecord rec = new ColumnInfoRecord();
rec._first_col = _first_col;
rec._last_col = _last_col;
rec._col_width = _col_width;
rec._xf_index = _xf_index;
rec._options = _options;
rec.field_6_reserved = field_6_reserved;
return rec;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
namespace System
{
/// <summary>
/// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
[NonVersionable]
public readonly ref struct ReadOnlySpan<T>
{
/// <summary>A byref or a native ptr.</summary>
private readonly ByReference<T> _pointer;
/// <summary>The number of elements this ReadOnlySpan contains.</summary>
#if PROJECTN
[Bound]
#endif
private readonly int _length;
/// <summary>
/// Creates a new read-only span over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()));
_length = array.Length;
}
/// <summary>
/// Creates a new read-only span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the read-only span.</param>
/// <param name="length">The number of items in the read-only span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
_length = length;
}
/// <summary>
/// Creates a new read-only span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe ReadOnlySpan(void* pointer, int length)
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer));
_length = length;
}
/// <summary>
/// Create a new read-only span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because neither the
/// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
/// "rawPointer" actually lies within <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length) => new ReadOnlySpan<T>(ref objectData, length);
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlySpan(ref T ptr, int length)
{
Debug.Assert(length >= 0);
_pointer = new ByReference<T>(ref ptr);
_length = length;
}
//Debugger Display = {T[length]}
private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length);
/// <summary>
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[EditorBrowsable(EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference()
{
return ref _pointer.Value;
}
/// <summary>
/// The number of items in the read-only span.
/// </summary>
public int Length
{
[NonVersionable]
get
{
return _length;
}
}
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty
{
[NonVersionable]
get
{
return _length == 0;
}
}
/// <summary>
/// Returns the specified element of the read-only span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public T this[int index]
{
#if PROJECTN
[BoundsChecking]
get
{
return Unsafe.Add(ref _pointer.Value, index);
}
#else
#if CORERT
[Intrinsic]
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[NonVersionable]
get
{
if ((uint)index >= (uint)_length)
ThrowHelper.ThrowIndexOutOfRangeException();
return Unsafe.Add(ref _pointer.Value, index);
}
#endif
}
/// <summary>
/// Copies the contents of this read-only span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
/// </summary>
public void CopyTo(Span<T> destination)
{
if (!TryCopyTo(destination))
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
/// Copies the contents of this read-only span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
/// </summary>
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Span<T> destination)
{
if ((uint)_length > (uint)destination.Length)
return false;
Span.CopyTo<T>(ref destination.DangerousGetPinnableReference(), ref _pointer.Value, _length);
return true;
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value);
}
/// <summary>
/// Returns false if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) => !(left == right);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan);
}
/// <summary>
/// This method is not supported as spans cannot be boxed.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on Span will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan);
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(T[] array) => new ReadOnlySpan<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(ArraySegment<T> arraySegment) => new ReadOnlySpan<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Forms a slice out of the given read-only span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start);
}
/// <summary>
/// Forms a slice out of the given read-only span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), length);
}
/// <summary>
/// Copies the contents of this read-only span into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray()
{
if (_length == 0)
return Array.Empty<T>();
var destination = new T[_length];
Span.CopyTo<T>(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, _length);
return destination;
}
/// <summary>
/// Returns a 0-length read-only span whose base is the null pointer.
/// </summary>
public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>);
}
}
| |
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>
/// Strongly-typed collection for the PnSmiprocesoafiliado class.
/// </summary>
[Serializable]
public partial class PnSmiprocesoafiliadoCollection : ActiveList<PnSmiprocesoafiliado, PnSmiprocesoafiliadoCollection>
{
public PnSmiprocesoafiliadoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnSmiprocesoafiliadoCollection</returns>
public PnSmiprocesoafiliadoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnSmiprocesoafiliado o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_smiprocesoafiliados table.
/// </summary>
[Serializable]
public partial class PnSmiprocesoafiliado : ActiveRecord<PnSmiprocesoafiliado>, IActiveRecord
{
#region .ctors and Default Settings
public PnSmiprocesoafiliado()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnSmiprocesoafiliado(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnSmiprocesoafiliado(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnSmiprocesoafiliado(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_smiprocesoafiliados", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdProcafiliado = new TableSchema.TableColumn(schema);
colvarIdProcafiliado.ColumnName = "id_procafiliado";
colvarIdProcafiliado.DataType = DbType.Int32;
colvarIdProcafiliado.MaxLength = 0;
colvarIdProcafiliado.AutoIncrement = true;
colvarIdProcafiliado.IsNullable = false;
colvarIdProcafiliado.IsPrimaryKey = true;
colvarIdProcafiliado.IsForeignKey = false;
colvarIdProcafiliado.IsReadOnly = false;
colvarIdProcafiliado.DefaultSetting = @"";
colvarIdProcafiliado.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdProcafiliado);
TableSchema.TableColumn colvarPeriodo = new TableSchema.TableColumn(schema);
colvarPeriodo.ColumnName = "periodo";
colvarPeriodo.DataType = DbType.AnsiString;
colvarPeriodo.MaxLength = -1;
colvarPeriodo.AutoIncrement = false;
colvarPeriodo.IsNullable = true;
colvarPeriodo.IsPrimaryKey = false;
colvarPeriodo.IsForeignKey = false;
colvarPeriodo.IsReadOnly = false;
colvarPeriodo.DefaultSetting = @"";
colvarPeriodo.ForeignKeyTableName = "";
schema.Columns.Add(colvarPeriodo);
TableSchema.TableColumn colvarCodigocialtadatos = new TableSchema.TableColumn(schema);
colvarCodigocialtadatos.ColumnName = "codigocialtadatos";
colvarCodigocialtadatos.DataType = DbType.AnsiString;
colvarCodigocialtadatos.MaxLength = -1;
colvarCodigocialtadatos.AutoIncrement = false;
colvarCodigocialtadatos.IsNullable = true;
colvarCodigocialtadatos.IsPrimaryKey = false;
colvarCodigocialtadatos.IsForeignKey = false;
colvarCodigocialtadatos.IsReadOnly = false;
colvarCodigocialtadatos.DefaultSetting = @"";
colvarCodigocialtadatos.ForeignKeyTableName = "";
schema.Columns.Add(colvarCodigocialtadatos);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_smiprocesoafiliados",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdProcafiliado")]
[Bindable(true)]
public int IdProcafiliado
{
get { return GetColumnValue<int>(Columns.IdProcafiliado); }
set { SetColumnValue(Columns.IdProcafiliado, value); }
}
[XmlAttribute("Periodo")]
[Bindable(true)]
public string Periodo
{
get { return GetColumnValue<string>(Columns.Periodo); }
set { SetColumnValue(Columns.Periodo, value); }
}
[XmlAttribute("Codigocialtadatos")]
[Bindable(true)]
public string Codigocialtadatos
{
get { return GetColumnValue<string>(Columns.Codigocialtadatos); }
set { SetColumnValue(Columns.Codigocialtadatos, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varPeriodo,string varCodigocialtadatos)
{
PnSmiprocesoafiliado item = new PnSmiprocesoafiliado();
item.Periodo = varPeriodo;
item.Codigocialtadatos = varCodigocialtadatos;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdProcafiliado,string varPeriodo,string varCodigocialtadatos)
{
PnSmiprocesoafiliado item = new PnSmiprocesoafiliado();
item.IdProcafiliado = varIdProcafiliado;
item.Periodo = varPeriodo;
item.Codigocialtadatos = varCodigocialtadatos;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdProcafiliadoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn PeriodoColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn CodigocialtadatosColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdProcafiliado = @"id_procafiliado";
public static string Periodo = @"periodo";
public static string Codigocialtadatos = @"codigocialtadatos";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#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;
using System.Xml;
using System.Xml.Schema;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Security;
#if NET_NATIVE
using Internal.Runtime.Augments;
#endif
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || NET_NATIVE
public delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces);
public delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract);
public delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract);
public sealed class XmlFormatReaderGenerator
#else
internal delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces);
internal delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract);
internal delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract);
internal sealed class XmlFormatReaderGenerator
#endif
{
private static readonly Func<Type, object> s_getUninitializedObjectDelegate = (Func<Type, object>)
typeof(string)
.GetTypeInfo()
.Assembly
.GetType("System.Runtime.Serialization.FormatterServices")
?.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
?.CreateDelegate(typeof(Func<Type, object>));
private static readonly ConcurrentDictionary<Type, bool> s_typeHasDefaultConstructorMap = new ConcurrentDictionary<Type, bool>();
#if !NET_NATIVE
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that was produced within an assert
/// </SecurityNote>
private CriticalHelper _helper;
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// </SecurityNote>
[SecurityCritical]
public XmlFormatReaderGenerator()
{
_helper = new CriticalHelper();
}
/// <SecurityNote>
/// Critical - accesses SecurityCritical helper class 'CriticalHelper'
/// </SecurityNote>
[SecurityCritical]
public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract)
{
return _helper.GenerateClassReader(classContract);
}
/// <SecurityNote>
/// Critical - accesses SecurityCritical helper class 'CriticalHelper'
/// </SecurityNote>
[SecurityCritical]
public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract)
{
return _helper.GenerateCollectionReader(collectionContract);
}
/// <SecurityNote>
/// Critical - accesses SecurityCritical helper class 'CriticalHelper'
/// </SecurityNote>
[SecurityCritical]
public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract)
{
return _helper.GenerateGetOnlyCollectionReader(collectionContract);
}
/// <SecurityNote>
/// Review - handles all aspects of IL generation including initializing the DynamicMethod.
/// changes to how IL generated could affect how data is deserialized and what gets access to data,
/// therefore we mark it for review so that changes to generation logic are reviewed.
/// </SecurityNote>
private class CriticalHelper
{
private CodeGenerator _ilg;
private LocalBuilder _objectLocal;
private Type _objectType;
private ArgBuilder _xmlReaderArg;
private ArgBuilder _contextArg;
private ArgBuilder _memberNamesArg;
private ArgBuilder _memberNamespacesArg;
private ArgBuilder _collectionContractArg;
public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null);
try
{
_ilg.BeginMethod("Read" + classContract.StableName.Name + "FromXml", Globals.TypeOfXmlFormatClassReaderDelegate, memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForRead(securityException);
}
else
{
throw;
}
}
InitArgs();
CreateObject(classContract);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
InvokeOnDeserializing(classContract);
LocalBuilder objectId = null;
ReadClass(classContract);
InvokeOnDeserialized(classContract);
if (objectId == null)
{
_ilg.Load(_objectLocal);
// Do a conversion back from DateTimeOffsetAdapter to DateTimeOffset after deserialization.
// DateTimeOffsetAdapter is used here for deserialization purposes to bypass the ISerializable implementation
// on DateTimeOffset; which does not work in partial trust.
if (classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter)
{
_ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfDateTimeOffsetAdapter);
_ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetMethod);
_ilg.ConvertValue(Globals.TypeOfDateTimeOffset, _ilg.CurrentMethod.ReturnType);
}
//Copy the KeyValuePairAdapter<K,T> to a KeyValuePair<K,T>.
else if (classContract.IsKeyValuePairAdapter)
{
_ilg.Call(classContract.GetKeyValuePairMethodInfo);
_ilg.ConvertValue(Globals.TypeOfKeyValuePair.MakeGenericType(classContract.KeyValuePairGenericArguments), _ilg.CurrentMethod.ReturnType);
}
else
{
_ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType);
}
}
return (XmlFormatClassReaderDelegate)_ilg.EndMethod();
}
public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract)
{
_ilg = GenerateCollectionReaderHelper(collectionContract, false /*isGetOnlyCollection*/);
ReadCollection(collectionContract);
_ilg.Load(_objectLocal);
_ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType);
return (XmlFormatCollectionReaderDelegate)_ilg.EndMethod();
}
public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract)
{
_ilg = GenerateCollectionReaderHelper(collectionContract, true /*isGetOnlyCollection*/);
ReadGetOnlyCollection(collectionContract);
return (XmlFormatGetOnlyCollectionReaderDelegate)_ilg.EndMethod();
}
private CodeGenerator GenerateCollectionReaderHelper(CollectionDataContract collectionContract, bool isGetOnlyCollection)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = collectionContract.RequiresMemberAccessForRead(null);
try
{
if (isGetOnlyCollection)
{
_ilg.BeginMethod("Read" + collectionContract.StableName.Name + "FromXml" + "IsGetOnly", Globals.TypeOfXmlFormatGetOnlyCollectionReaderDelegate, memberAccessFlag);
}
else
{
_ilg.BeginMethod("Read" + collectionContract.StableName.Name + "FromXml" + string.Empty, Globals.TypeOfXmlFormatCollectionReaderDelegate, memberAccessFlag);
}
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
collectionContract.RequiresMemberAccessForRead(securityException);
}
else
{
throw;
}
}
InitArgs();
_collectionContractArg = _ilg.GetArg(4);
return _ilg;
}
private void InitArgs()
{
_xmlReaderArg = _ilg.GetArg(0);
_contextArg = _ilg.GetArg(1);
_memberNamesArg = _ilg.GetArg(2);
_memberNamespacesArg = _ilg.GetArg(3);
}
private void CreateObject(ClassDataContract classContract)
{
Type type = _objectType = classContract.UnderlyingType;
if (type.GetTypeInfo().IsValueType && !classContract.IsNonAttributedType)
type = Globals.TypeOfValueType;
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
if (classContract.UnderlyingType == Globals.TypeOfDBNull)
{
_ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value"));
_ilg.Stloc(_objectLocal);
}
else if (classContract.IsNonAttributedType)
{
if (type.GetTypeInfo().IsValueType)
{
_ilg.Ldloca(_objectLocal);
_ilg.InitObj(type);
}
else
{
_ilg.New(classContract.GetNonAttributedTypeConstructor());
_ilg.Stloc(_objectLocal);
}
}
else
{
_ilg.Call(null, XmlFormatGeneratorStatics.GetUninitializedObjectMethod, DataContract.GetIdForInitialization(classContract));
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(_objectLocal);
}
}
private void InvokeOnDeserializing(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnDeserializing(classContract.BaseContract);
if (classContract.OnDeserializing != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnDeserializing);
}
}
private void InvokeOnDeserialized(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnDeserialized(classContract.BaseContract);
if (classContract.OnDeserialized != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnDeserialized);
}
}
private void ReadClass(ClassDataContract classContract)
{
ReadMembers(classContract, null /*extensionDataLocal*/);
}
private void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal)
{
int memberCount = classContract.MemberNames.Length;
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount);
LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1);
int firstRequiredMember;
bool[] requiredMembers = GetRequiredMembers(classContract, out firstRequiredMember);
bool hasRequiredMembers = (firstRequiredMember < memberCount);
LocalBuilder requiredIndexLocal = hasRequiredMembers ? _ilg.DeclareLocal(Globals.TypeOfInt, "requiredIndex", firstRequiredMember) : null;
object forReadElements = _ilg.For(null, null, null);
_ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, _xmlReaderArg);
_ilg.IfFalseBreak(forReadElements);
if (hasRequiredMembers)
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetMemberIndexWithRequiredMembersMethod, _xmlReaderArg, _memberNamesArg, _memberNamespacesArg, memberIndexLocal, requiredIndexLocal, extensionDataLocal);
else
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetMemberIndexMethod, _xmlReaderArg, _memberNamesArg, _memberNamespacesArg, memberIndexLocal, extensionDataLocal);
Label[] memberLabels = _ilg.Switch(memberCount);
ReadMembers(classContract, requiredMembers, memberLabels, memberIndexLocal, requiredIndexLocal);
_ilg.EndSwitch();
_ilg.EndFor();
if (hasRequiredMembers)
{
_ilg.If(requiredIndexLocal, Cmp.LessThan, memberCount);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMissingExceptionMethod, _xmlReaderArg, memberIndexLocal, requiredIndexLocal, _memberNamesArg);
_ilg.EndIf();
}
}
private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, Label[] memberLabels, LocalBuilder memberIndexLocal, LocalBuilder requiredIndexLocal)
{
int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, requiredMembers,
memberLabels, memberIndexLocal, requiredIndexLocal);
for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
{
DataMember dataMember = classContract.Members[i];
Type memberType = dataMember.MemberType;
_ilg.Case(memberLabels[memberCount], dataMember.Name);
if (dataMember.IsRequired)
{
int nextRequiredIndex = memberCount + 1;
for (; nextRequiredIndex < requiredMembers.Length; nextRequiredIndex++)
if (requiredMembers[nextRequiredIndex])
break;
_ilg.Set(requiredIndexLocal, nextRequiredIndex);
}
LocalBuilder value = null;
if (dataMember.IsGetOnlyCollection)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(dataMember.MemberInfo);
value = _ilg.DeclareLocal(memberType, dataMember.Name + "Value");
_ilg.Stloc(value);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value);
ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace);
}
else
{
value = ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace);
_ilg.LoadAddress(_objectLocal);
_ilg.ConvertAddress(_objectLocal.LocalType, _objectType);
_ilg.Ldloc(value);
_ilg.StoreMember(dataMember.MemberInfo);
}
#if FEATURE_LEGACYNETCF
// The DataContractSerializer in the full framework doesn't support unordered elements:
// deserialization will fail if the data members in the XML are not sorted alphabetically.
// But the NetCF DataContractSerializer does support unordered element. To maintain compatibility
// with Mango we always search for the member from the beginning of the member list.
// We set memberIndexLocal to -1 because GetMemberIndex always starts from memberIndex+1.
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
ilg.Set(memberIndexLocal, (int)-1);
else
#endif // FEATURE_LEGACYNETCF
_ilg.Set(memberIndexLocal, memberCount);
_ilg.EndCase();
}
return memberCount;
}
private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequiredMember)
{
int memberCount = contract.MemberNames.Length;
bool[] requiredMembers = new bool[memberCount];
GetRequiredMembers(contract, requiredMembers);
for (firstRequiredMember = 0; firstRequiredMember < memberCount; firstRequiredMember++)
if (requiredMembers[firstRequiredMember])
break;
return requiredMembers;
}
private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers)
{
int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers);
List<DataMember> members = contract.Members;
for (int i = 0; i < members.Count; i++, memberCount++)
{
requiredMembers[memberCount] = members[i].IsRequired;
}
return memberCount;
}
private LocalBuilder ReadValue(Type type, string name, string ns)
{
LocalBuilder value = _ilg.DeclareLocal(type, "valueRead");
LocalBuilder nullableValue = null;
int nullables = 0;
while (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable)
{
nullables++;
type = type.GetGenericArguments()[0];
}
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.GetTypeInfo().IsValueType)
{
LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, _xmlReaderArg, type, DataContract.IsTypeSerializable(type));
_ilg.Stloc(objectId);
// Deserialize null
_ilg.If(objectId, Cmp.EqualTo, Globals.NullObjectId);
if (nullables != 0)
{
_ilg.LoadAddress(value);
_ilg.InitObj(value.LocalType);
}
else if (type.GetTypeInfo().IsValueType)
ThrowValidationException(SR.Format(SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type)));
else
{
_ilg.Load(null);
_ilg.Stloc(value);
}
// Deserialize value
// Compare against Globals.NewObjectId, which is set to string.Empty
_ilg.ElseIfIsEmptyString(objectId);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod);
_ilg.Stloc(objectId);
if (type.GetTypeInfo().IsValueType)
{
_ilg.IfNotIsEmptyString(objectId);
ThrowValidationException(SR.Format(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type)));
_ilg.EndIf();
}
if (nullables != 0)
{
nullableValue = value;
value = _ilg.DeclareLocal(type, "innerValueRead");
}
if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject)
{
_ilg.Call(_xmlReaderArg, primitiveContract.XmlFormatReaderMethod);
_ilg.Stloc(value);
if (!type.GetTypeInfo().IsValueType)
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, value);
}
else
{
InternalDeserialize(value, type, name, ns);
}
// Deserialize ref
_ilg.Else();
if (type.GetTypeInfo().IsValueType)
ThrowValidationException(SR.Format(SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type)));
else
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetExistingObjectMethod, objectId, type, name, ns);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(value);
}
_ilg.EndIf();
if (nullableValue != null)
{
_ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId);
WrapNullableObject(value, nullableValue, nullables);
_ilg.EndIf();
value = nullableValue;
}
}
else
{
InternalDeserialize(value, type, name, ns);
}
return value;
}
private void InternalDeserialize(LocalBuilder value, Type type, string name, string ns)
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlReaderArg);
Type declaredType = type;
_ilg.Load(DataContract.GetId(declaredType.TypeHandle));
_ilg.Ldtoken(declaredType);
_ilg.Load(name);
_ilg.Load(ns);
_ilg.Call(XmlFormatGeneratorStatics.InternalDeserializeMethod);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(value);
}
private void WrapNullableObject(LocalBuilder innerValue, LocalBuilder outerValue, int nullables)
{
Type innerType = innerValue.LocalType, outerType = outerValue.LocalType;
_ilg.LoadAddress(outerValue);
_ilg.Load(innerValue);
for (int i = 1; i < nullables; i++)
{
Type type = Globals.TypeOfNullable.MakeGenericType(innerType);
_ilg.New(type.GetConstructor(new Type[] { innerType }));
innerType = type;
}
_ilg.Call(outerType.GetConstructor(new Type[] { innerType }));
}
private void ReadCollection(CollectionDataContract collectionContract)
{
Type type = collectionContract.UnderlyingType;
Type itemType = collectionContract.ItemType;
bool isArray = (collectionContract.Kind == CollectionKind.Array);
ConstructorInfo constructor = collectionContract.Constructor;
if (type.GetTypeInfo().IsInterface)
{
switch (collectionContract.Kind)
{
case CollectionKind.GenericDictionary:
type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments());
constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
break;
case CollectionKind.Dictionary:
type = Globals.TypeOfHashtable;
constructor = XmlFormatGeneratorStatics.HashtableCtor;
break;
case CollectionKind.Collection:
case CollectionKind.GenericCollection:
case CollectionKind.Enumerable:
case CollectionKind.GenericEnumerable:
case CollectionKind.List:
case CollectionKind.GenericList:
type = itemType.MakeArrayType();
isArray = true;
break;
}
}
string itemName = collectionContract.ItemName;
string itemNs = collectionContract.StableName.Namespace;
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
if (!isArray)
{
if (type.GetTypeInfo().IsValueType)
{
_ilg.Ldloca(_objectLocal);
_ilg.InitObj(type);
}
else
{
_ilg.New(constructor);
_ilg.Stloc(_objectLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
}
}
LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetArraySizeMethod);
_ilg.Stloc(size);
LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod);
_ilg.Stloc(objectId);
bool canReadPrimitiveArray = false;
if (isArray && TryReadPrimitiveArray(type, itemType, size))
{
canReadPrimitiveArray = true;
_ilg.IfNot();
}
_ilg.If(size, Cmp.EqualTo, -1);
LocalBuilder growingCollection = null;
if (isArray)
{
growingCollection = _ilg.DeclareLocal(type, "growingCollection");
_ilg.NewArray(itemType, 32);
_ilg.Stloc(growingCollection);
}
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
object forLoop = _ilg.For(i, 0, Int32.MaxValue);
IsStartElement(_memberNamesArg, _memberNamespacesArg);
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs);
if (isArray)
{
MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType);
_ilg.Call(null, ensureArraySizeMethod, growingCollection, i);
_ilg.Stloc(growingCollection);
_ilg.StoreArrayElement(growingCollection, i, value);
}
else
StoreCollectionValue(_objectLocal, value, collectionContract);
_ilg.Else();
IsEndElement();
_ilg.If();
_ilg.Break(forLoop);
_ilg.Else();
HandleUnexpectedItemInCollection(i);
_ilg.EndIf();
_ilg.EndIf();
_ilg.EndFor();
if (isArray)
{
MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType);
_ilg.Call(null, trimArraySizeMethod, growingCollection, i);
_ilg.Stloc(_objectLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal);
}
_ilg.Else();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, size);
if (isArray)
{
_ilg.NewArray(itemType, size);
_ilg.Stloc(_objectLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
}
LocalBuilder j = _ilg.DeclareLocal(Globals.TypeOfInt, "j");
_ilg.For(j, 0, size);
IsStartElement(_memberNamesArg, _memberNamespacesArg);
_ilg.If();
LocalBuilder itemValue = ReadCollectionItem(collectionContract, itemType, itemName, itemNs);
if (isArray)
_ilg.StoreArrayElement(_objectLocal, j, itemValue);
else
StoreCollectionValue(_objectLocal, itemValue, collectionContract);
_ilg.Else();
HandleUnexpectedItemInCollection(j);
_ilg.EndIf();
_ilg.EndFor();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _memberNamespacesArg);
_ilg.EndIf();
if (canReadPrimitiveArray)
{
_ilg.Else();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal);
_ilg.EndIf();
}
}
private void ReadGetOnlyCollection(CollectionDataContract collectionContract)
{
Type type = collectionContract.UnderlyingType;
Type itemType = collectionContract.ItemType;
bool isArray = (collectionContract.Kind == CollectionKind.Array);
string itemName = collectionContract.ItemName;
string itemNs = collectionContract.StableName.Namespace;
_objectLocal = _ilg.DeclareLocal(type, "objectDeserialized");
_ilg.Load(_contextArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.GetCollectionMemberMethod);
_ilg.ConvertValue(Globals.TypeOfObject, type);
_ilg.Stloc(_objectLocal);
//check that items are actually going to be deserialized into the collection
IsStartElement(_memberNamesArg, _memberNamespacesArg);
_ilg.If();
_ilg.If(_objectLocal, Cmp.EqualTo, null);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type);
_ilg.Else();
LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize");
if (isArray)
{
_ilg.Load(_objectLocal);
_ilg.Call(XmlFormatGeneratorStatics.GetArrayLengthMethod);
_ilg.Stloc(size);
}
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal);
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
object forLoop = _ilg.For(i, 0, Int32.MaxValue);
IsStartElement(_memberNamesArg, _memberNamespacesArg);
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs);
if (isArray)
{
_ilg.If(size, Cmp.EqualTo, i);
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowArrayExceededSizeExceptionMethod, size, type);
_ilg.Else();
_ilg.StoreArrayElement(_objectLocal, i, value);
_ilg.EndIf();
}
else
StoreCollectionValue(_objectLocal, value, collectionContract);
_ilg.Else();
IsEndElement();
_ilg.If();
_ilg.Break(forLoop);
_ilg.Else();
HandleUnexpectedItemInCollection(i);
_ilg.EndIf();
_ilg.EndIf();
_ilg.EndFor();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _memberNamespacesArg);
_ilg.EndIf();
_ilg.EndIf();
}
private bool TryReadPrimitiveArray(Type type, Type itemType, LocalBuilder size)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
if (primitiveContract == null)
return false;
string readArrayMethod = null;
switch (itemType.GetTypeCode())
{
case TypeCode.Boolean:
readArrayMethod = "TryReadBooleanArray";
break;
case TypeCode.DateTime:
readArrayMethod = "TryReadDateTimeArray";
break;
case TypeCode.Decimal:
readArrayMethod = "TryReadDecimalArray";
break;
case TypeCode.Int32:
readArrayMethod = "TryReadInt32Array";
break;
case TypeCode.Int64:
readArrayMethod = "TryReadInt64Array";
break;
case TypeCode.Single:
readArrayMethod = "TryReadSingleArray";
break;
case TypeCode.Double:
readArrayMethod = "TryReadDoubleArray";
break;
default:
break;
}
if (readArrayMethod != null)
{
_ilg.Load(_xmlReaderArg);
_ilg.Load(_contextArg);
_ilg.Load(_memberNamesArg);
_ilg.Load(_memberNamespacesArg);
_ilg.Load(size);
_ilg.Ldloca(_objectLocal);
_ilg.Call(typeof(XmlReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers));
return true;
}
return false;
}
private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContract, Type itemType, string itemName, string itemNs)
{
if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary)
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetAttributesMethod);
LocalBuilder value = _ilg.DeclareLocal(itemType, "valueRead");
_ilg.Load(_collectionContractArg);
_ilg.Call(XmlFormatGeneratorStatics.GetItemContractMethod);
_ilg.Load(_xmlReaderArg);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.ReadXmlValueMethod);
_ilg.ConvertValue(Globals.TypeOfObject, itemType);
_ilg.Stloc(value);
return value;
}
else
{
return ReadValue(itemType, itemName, itemNs);
}
}
private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract)
{
if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary)
{
ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract;
if (keyValuePairContract == null)
{
DiagnosticUtility.DebugAssert("Failed to create contract for KeyValuePair type");
}
DataMember keyMember = keyValuePairContract.Members[0];
DataMember valueMember = keyValuePairContract.Members[1];
LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name);
LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name);
_ilg.LoadAddress(value);
_ilg.LoadMember(keyMember.MemberInfo);
_ilg.Stloc(pairKey);
_ilg.LoadAddress(value);
_ilg.LoadMember(valueMember.MemberInfo);
_ilg.Stloc(pairValue);
_ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue);
if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid)
_ilg.Pop();
}
else
{
_ilg.Call(collection, collectionContract.AddMethod, value);
if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid)
_ilg.Pop();
}
}
private void HandleUnexpectedItemInCollection(LocalBuilder iterator)
{
IsStartElement();
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.SkipUnknownElementMethod, _xmlReaderArg);
_ilg.Dec(iterator);
_ilg.Else();
ThrowUnexpectedStateException(XmlNodeType.Element);
_ilg.EndIf();
}
private void IsStartElement(ArgBuilder nameArg, ArgBuilder nsArg)
{
_ilg.Call(_xmlReaderArg, XmlFormatGeneratorStatics.IsStartElementMethod2, nameArg, nsArg);
}
private void IsStartElement()
{
_ilg.Call(_xmlReaderArg, XmlFormatGeneratorStatics.IsStartElementMethod0);
}
private void IsEndElement()
{
_ilg.Load(_xmlReaderArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.NodeTypeProperty);
_ilg.Load(XmlNodeType.EndElement);
_ilg.Ceq();
}
private void ThrowUnexpectedStateException(XmlNodeType expectedState)
{
_ilg.Call(null, XmlFormatGeneratorStatics.CreateUnexpectedStateExceptionMethod, expectedState, _xmlReaderArg);
_ilg.Throw();
}
private void ThrowValidationException(string msg, params object[] values)
{
{
_ilg.Load(msg);
}
ThrowValidationException();
}
private void ThrowValidationException()
{
//SerializationException is internal in SL and so cannot be directly invoked from DynamicMethod
//So use helper function to create SerializationException
_ilg.Call(XmlFormatGeneratorStatics.CreateSerializationExceptionMethod);
_ilg.Throw();
}
}
#endif
[SecuritySafeCritical]
static internal object UnsafeGetUninitializedObject(Type type)
{
#if !NET_NATIVE
if (type.GetTypeInfo().IsValueType)
{
return Activator.CreateInstance(type);
}
const BindingFlags Flags = BindingFlags.Public | BindingFlags.Instance;
bool hasDefaultConstructor = s_typeHasDefaultConstructorMap.GetOrAdd(type, t => t.GetConstructor(Flags, Array.Empty<Type>()) != null);
return hasDefaultConstructor ? Activator.CreateInstance(type) : TryGetUninitializedObjectWithFormatterServices(type) ?? Activator.CreateInstance(type);
#else
return RuntimeAugments.NewObject(type.TypeHandle);
#endif
}
/// <SecurityNote>
/// Critical - Elevates by calling GetUninitializedObject which has a LinkDemand
/// Safe - marked as such so that it's callable from transparent generated IL. Takes id as parameter which
/// is guaranteed to be in internal serialization cache.
/// </SecurityNote>
[SecuritySafeCritical]
#if USE_REFEMIT
public static object UnsafeGetUninitializedObject(int id)
#else
static internal object UnsafeGetUninitializedObject(int id)
#endif
{
var type = DataContract.GetDataContractForInitialization(id).TypeForInitialization;
return UnsafeGetUninitializedObject(type);
}
static internal object TryGetUninitializedObjectWithFormatterServices(Type type) =>
s_getUninitializedObjectDelegate?.Invoke(type);
}
}
| |
// 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 Microsoft.VisualStudio.TestTools.UnitTesting;
using TestRunnerInterop;
using PUIT = ProfilingUITests.ProfilingUITests;
namespace ProfilingUITestsRunner {
[TestClass]
public class ProfilingUITests {
#region UI test boilerplate
public VsTestInvoker _vs => new VsTestInvoker(
VsTestContext.Instance,
// Remote container (DLL) name
"Microsoft.PythonTools.Tests.ProfilingUITests",
// Remote class name
$"ProfilingUITests.{GetType().Name}"
);
public TestContext TestContext { get; set; }
[TestInitialize]
public void TestInitialize() => VsTestContext.Instance.TestInitialize(TestContext.DeploymentDirectory);
[TestCleanup]
public void TestCleanup() => VsTestContext.Instance.TestCleanup();
[ClassCleanup]
public static void ClassCleanup() => VsTestContext.Instance.Dispose();
#endregion
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void DefaultInterpreterSelected() {
_vs.RunTest(nameof(PUIT.DefaultInterpreterSelected));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void StartupProjectSelected() {
_vs.RunTest(nameof(PUIT.StartupProjectSelected));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void NewProfilingSession() {
_vs.RunTest(nameof(PUIT.NewProfilingSession));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void DeleteMultipleSessions() {
_vs.RunTest(nameof(PUIT.DeleteMultipleSessions));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void NewProfilingSessionOpenSolution() {
_vs.RunTest(nameof(PUIT.NewProfilingSessionOpenSolution));
}
[TestMethod, Priority(UITestPriority.P2_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void LaunchPythonProfilingWizard() {
_vs.RunTest(nameof(PUIT.LaunchPythonProfilingWizard));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void LaunchProjectPython27() {
_vs.RunTest(nameof(PUIT.LaunchProjectPython27));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void LaunchProjectPython35() {
_vs.RunTest(nameof(PUIT.LaunchProjectPython35));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void LaunchProjectPython36() {
_vs.RunTest(nameof(PUIT.LaunchProjectPython36));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void LaunchProjectPython37() {
_vs.RunTest(nameof(PUIT.LaunchProjectPython37));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void LaunchProjectPython38() {
_vs.RunTest(nameof(PUIT.LaunchProjectPython38));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void LaunchProjectWithSpaceInFilename() {
_vs.RunTest(nameof(PUIT.LaunchProjectWithSpaceInFilename));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void LaunchProjectWithSolutionFolder() {
_vs.RunTest(nameof(PUIT.LaunchProjectWithSolutionFolder));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void LaunchProjectWithSearchPath() {
_vs.RunTest(nameof(PUIT.LaunchProjectWithSearchPath));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void LaunchProjectWithPythonPathSet() {
_vs.RunTest(nameof(PUIT.LaunchProjectWithPythonPathSet));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void LaunchProjectWithPythonPathClear() {
_vs.RunTest(nameof(PUIT.LaunchProjectWithPythonPathClear));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void LaunchProjectWithEnvironment() {
_vs.RunTest(nameof(PUIT.LaunchProjectWithEnvironment));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void SaveDirtySession() {
_vs.RunTest(nameof(PUIT.SaveDirtySession));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void DeleteReport() {
_vs.RunTest(nameof(PUIT.DeleteReport));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void CompareReports() {
_vs.RunTest(nameof(PUIT.CompareReports));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void RemoveReport() {
_vs.RunTest(nameof(PUIT.RemoveReport));
}
// P2 because the report viewer may crash VS depending on prior state.
// We will restart VS before running this test to ensure it is clean.
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void OpenReport() {
_vs.RunTest(nameof(PUIT.OpenReport));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void OpenReportCtxMenu() {
_vs.RunTest(nameof(PUIT.OpenReportCtxMenu));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void TargetPropertiesForProject() {
_vs.RunTest(nameof(PUIT.TargetPropertiesForProject));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void TargetPropertiesForInterpreter() {
_vs.RunTest(nameof(PUIT.TargetPropertiesForInterpreter));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void TargetPropertiesForExecutable() {
_vs.RunTest(nameof(PUIT.TargetPropertiesForExecutable));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void StopProfiling() {
_vs.RunTest(nameof(PUIT.StopProfiling));
}
[TestMethod, Priority(UITestPriority.P2_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void MultipleTargets() {
_vs.RunTest(nameof(PUIT.MultipleTargets));
}
[TestMethod, Priority(UITestPriority.P2_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void MultipleTargetsWithProjectHome() {
_vs.RunTest(nameof(PUIT.MultipleTargetsWithProjectHome));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void MultipleReports() {
_vs.RunTest(nameof(PUIT.MultipleReports));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void LaunchExecutable() {
_vs.RunTest(nameof(PUIT.LaunchExecutable));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void ClassProfile() {
_vs.RunTest(nameof(PUIT.ClassProfile));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void OldClassProfile() {
_vs.RunTest(nameof(PUIT.OldClassProfile));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void DerivedProfile() {
_vs.RunTest(nameof(PUIT.DerivedProfile));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void Pystone() {
_vs.RunTest(nameof(PUIT.Pystone));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void BuiltinsProfilePython27() {
_vs.RunTest(nameof(PUIT.BuiltinsProfilePython27));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void BuiltinsProfilePython27x64() {
_vs.RunTest(nameof(PUIT.BuiltinsProfilePython27x64));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void BuiltinsProfilePython35() {
_vs.RunTest(nameof(PUIT.BuiltinsProfilePython35));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void BuiltinsProfilePython35x64() {
_vs.RunTest(nameof(PUIT.BuiltinsProfilePython35x64));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void BuiltinsProfilePython36() {
_vs.RunTest(nameof(PUIT.BuiltinsProfilePython36));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void BuiltinsProfilePython36x64() {
_vs.RunTest(nameof(PUIT.BuiltinsProfilePython36x64));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void BuiltinsProfilePython37() {
_vs.RunTest(nameof(PUIT.BuiltinsProfilePython37));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void BuiltinsProfilePython37x64() {
_vs.RunTest(nameof(PUIT.BuiltinsProfilePython37x64));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void BuiltinsProfilePython38() {
_vs.RunTest(nameof(PUIT.BuiltinsProfilePython37));
}
[TestMethod, Priority(UITestPriority.P2)]
[TestCategory("Installed")]
public void BuiltinsProfilePython38x64() {
_vs.RunTest(nameof(PUIT.BuiltinsProfilePython37x64));
}
[TestMethod, Priority(UITestPriority.P0_FAILING_UI_TEST)]
[TestCategory("Installed")]
public void LaunchExecutableUsingInterpreterGuid() {
_vs.RunTest(nameof(PUIT.LaunchExecutableUsingInterpreterGuid));
}
}
}
| |
//
// Mono.Cxxi.Util.IEnumerableTransform.cs: Rule-based transformation for IEnumerable
//
// Author:
// Alexander Corrado (alexander.corrado@gmail.com)
// Andreia Gaita (shana@spoiledcat.net)
//
// Copyright (C) 2010-2011 Alexander Corrado
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace Mono.Cxxi.Util {
public static class IEnumerableTransform {
// Transforms an IEnumerable into another by specific rules.
public static IEnumerable<TOut> Transform<TIn, TOut> (this IEnumerable<TIn> input, params EmitterFunc<TIn, TOut> [] rules)
{
CloneableEnumerator<TIn> enumerator = new CloneableEnumerator<TIn> (input, 0);
while (enumerator.MoveNext ()) {
InputData<TIn> inputData = new InputData<TIn> (input, enumerator);
foreach (var rule in rules) {
TOut output;
if (rule (inputData.NewContext (), out output) == RuleResult.MatchEmit)
yield return output;
}
}
}
public static IRule<TIn> And<TIn> (this IRule<TIn> previousRules, IRule<TIn> parentheticalRules)
{
return new AndRule<TIn> (previousRules, parentheticalRules);
}
public static RuleCompound<TIn> And<TIn> (this IRule<TIn> previousRules)
{
return new RuleCompound<TIn> ((subsequentRules) => {
return And<TIn> (previousRules, subsequentRules);
});
}
public static IRule<TIn> Or<TIn> (this IRule<TIn> previousRules, IRule<TIn> parentheticalRules)
{
return new OrRule<TIn> (previousRules, parentheticalRules);
}
public static RuleCompound<TIn> Or<TIn> (this IRule<TIn> previousRules)
{
return new RuleCompound<TIn> ((subsequentRules) => {
return Or<TIn> (previousRules, subsequentRules);
});
}
public static IRule<TIn> After<TIn> (this IRule<TIn> previousRules, IRule<TIn> parentheticalRules)
{
return new AndRule<TIn> (new AfterRule<TIn> (parentheticalRules), previousRules);
}
public static RuleCompound<TIn> After<TIn> (this IRule<TIn> previousRules)
{
return new RuleCompound<TIn> ((subsequentRules) => {
return After<TIn> (previousRules, subsequentRules);
});
}
public static IRule<TIn> AtEnd<TIn> (this IRule<TIn> previousRules)
{
return new AtEndRule<TIn> (previousRules);
}
public static EmitterFunc<TIn, TOut> Emit<TIn, TOut> (this IRule<TIn> rule, Func<TIn, TOut> result)
{
return delegate (InputData<TIn> input, out TOut output) {
output = default (TOut);
TIn value = input.Value;
RuleResult ruleResult = rule.SatisfiedBy (input);
if (ruleResult != RuleResult.NoMatch) {
input.MatchedRules.Add (rule);
output = result (value);
return ruleResult;
}
return RuleResult.NoMatch;
};
}
public static EmitterFunc<TIn, TOut> Emit<TIn, TOut> (this IRule<TIn> rule, TOut result)
{
return Emit (rule, (input) => result);
}
// helpers:
public static IEnumerable<T> With<T> (this IEnumerable<T> current, T additionalValue)
{
foreach (var output in current)
yield return output;
yield return additionalValue;
}
public static bool StartsWith<T> (this IEnumerable<T> current, IEnumerable<T> beginning)
{
IEnumerator<T> currentEnum = current.GetEnumerator ();
IEnumerator<T> beginEnum = beginning.GetEnumerator ();
while (currentEnum.MoveNext ()) {
if (!beginEnum.MoveNext ())
return true;
if (!currentEnum.Current.Equals (beginEnum.Current))
return false;
}
return !beginEnum.MoveNext ();
}
public static IEnumerable<T> Without<T> (this IEnumerable<T> current, T unwantedValue)
{
foreach (var output in current) {
if (!output.Equals (unwantedValue))
yield return output;
}
}
public static IEnumerable<T> WithoutFirst<T> (this IEnumerable<T> current, T unwantedValue)
{
bool first = true;
foreach (var output in current) {
if (first && output.Equals (unwantedValue))
first = false;
else
yield return output;
}
}
public static int SequenceHashCode<T> (this IEnumerable<T> sequence)
{
int hash = 0;
foreach (var item in sequence)
hash ^= item.GetHashCode ();
return hash;
}
// FIXME: Faster way to do this?
public static void AddFirst<T> (this List<T> list, IEnumerable<T> items)
{
T [] temp = new T [list.Count];
list.CopyTo (temp, 0);
list.Clear ();
list.AddRange (items);
list.AddRange (temp);
}
public static void AddFirst<T> (this List<T> list, T item)
{
list.Insert (0, item);
}
}
public enum RuleResult {
NoMatch,
MatchEmit,
MatchNoEmit
}
public delegate RuleResult EmitterFunc<TIn, TOut> (InputData<TIn> input, out TOut output);
public struct InputData<TIn> {
public IEnumerable<TIn> AllValues;
public CloneableEnumerator<TIn> Enumerator;
public List<IRule<TIn>> MatchedRules;
public InputData (IEnumerable<TIn> input, CloneableEnumerator<TIn> enumerator)
{
this.AllValues = input;
this.Enumerator = enumerator;
this.MatchedRules = new List<IRule<TIn>> ();
}
public InputData<TIn> NewContext ()
{
InputData<TIn> nctx = new InputData<TIn> ();
nctx.AllValues = this.AllValues;
nctx.Enumerator = this.Enumerator.Clone ();
nctx.MatchedRules = this.MatchedRules;
return nctx;
}
public TIn Value {
get { return Enumerator.Current; }
}
}
#region Rules
public interface IRule<TIn> {
RuleResult SatisfiedBy (InputData<TIn> input);
}
// yields all inputs indescriminately
public class AnyRule<TIn> : IRule<TIn> {
public AnyRule ()
{
}
public RuleResult SatisfiedBy (InputData<TIn> input)
{
return RuleResult.MatchEmit;
}
}
// yields all inputs that haven't satisfied
// any other rule
public class UnmatchedRule<TIn> : IRule<TIn> {
public UnmatchedRule ()
{
}
public RuleResult SatisfiedBy (InputData<TIn> input)
{
return !input.MatchedRules.Any ()? RuleResult.MatchEmit : RuleResult.NoMatch;
}
}
// yields input if it hasn't been satisfied before
public class FirstRule<TIn> : IRule<TIn> {
protected bool triggered = false;
public FirstRule ()
{
}
public RuleResult SatisfiedBy (InputData<TIn> input)
{
if (!triggered) {
triggered = true;
return RuleResult.MatchEmit;
}
return RuleResult.NoMatch;
}
}
// yields input if it is the last that would satisfy
// all its matched rules
public class LastRule<TIn> : IRule<TIn> {
public LastRule ()
{
}
public RuleResult SatisfiedBy (InputData<TIn> input)
{
throw new NotImplementedException ();
}
}
// yields input if the specified previous rule has already been satisfied
public class AfterRule<TIn> : IRule<TIn> {
protected IRule<TIn> previousRule;
protected bool satisfied = false;
public AfterRule (IRule<TIn> previousRule)
{
this.previousRule = previousRule;
}
public RuleResult SatisfiedBy (InputData<TIn> input)
{
if (satisfied)
return RuleResult.MatchEmit;
satisfied = previousRule.SatisfiedBy (input) != RuleResult.NoMatch;
return RuleResult.NoMatch;
}
}
// yields all inputs found in the specified set
public class InSetRule<TIn> : IRule<TIn> {
protected IEnumerable<TIn> conditions;
public InSetRule (params TIn [] conditions)
{
this.conditions = conditions;
}
public InSetRule (IEnumerable<TIn> conditions)
{
this.conditions = conditions;
}
public RuleResult SatisfiedBy (InputData<TIn> input)
{
return conditions.Contains (input.Value)? RuleResult.MatchEmit : RuleResult.NoMatch;
}
}
public class PredicateRule<TIn> : IRule<TIn> {
protected Func<TIn, bool> predicate;
public PredicateRule (Func<TIn, bool> predicate)
{
this.predicate = predicate;
}
public RuleResult SatisfiedBy (InputData<TIn> input)
{
return predicate (input.Value)? RuleResult.MatchEmit : RuleResult.NoMatch;
}
}
// is satisfied by any of the specified items as long the
// item appears adjacent with all the other items
public class AnyOrderRule<TIn> : IRule<TIn> {
protected IEnumerable<TIn> conditions;
protected Queue<TIn> verifiedItems = new Queue<TIn> ();
protected bool verified = false;
public AnyOrderRule (params TIn [] conditions)
{
this.conditions = conditions;
}
public AnyOrderRule (IEnumerable<TIn> conditions)
{
this.conditions = conditions;
}
public RuleResult SatisfiedBy (InputData<TIn> inputData)
{
if (verified && verifiedItems.Count > 0) {
verifiedItems.Dequeue ();
return RuleResult.MatchNoEmit;
} else
verified = false;
IEnumerator<TIn> input = inputData.Enumerator;
while (conditions.Contains (input.Current) && !verifiedItems.Contains (input.Current)) {
verifiedItems.Enqueue (input.Current);
if (!input.MoveNext ()) break;
}
if (verifiedItems.Count == conditions.Count ()) {
verified = true;
verifiedItems.Dequeue ();
return RuleResult.MatchEmit;
} else
verifiedItems.Clear ();
return RuleResult.NoMatch;
}
}
public class InOrderRule<TIn> : IRule<TIn> {
protected IEnumerable<TIn> conditions;
protected bool verified = false;
protected int verifiedCount = 0;
public InOrderRule (params TIn [] conditions)
{
this.conditions = conditions;
}
public InOrderRule (IEnumerable<TIn> conditions)
{
this.conditions = conditions;
}
public RuleResult SatisfiedBy (InputData<TIn> inputData)
{
if (verified && verifiedCount > 0) {
verifiedCount--;
return RuleResult.MatchNoEmit;
} else
verified = false;
IEnumerator<TIn> condition = conditions.GetEnumerator ();
IEnumerator<TIn> input = inputData.Enumerator;
while (condition.MoveNext () && condition.Equals (input.Current)) {
verifiedCount++;
if (!input.MoveNext ()) break;
}
if (verifiedCount == conditions.Count ()) {
verified = true;
verifiedCount--;
return RuleResult.MatchEmit;
} else
verifiedCount = 0;
return RuleResult.NoMatch;
}
}
// yields all inputs that match all specified rules
public class AndRule<TIn> : IRule<TIn> {
protected IEnumerable<IRule<TIn>> rules;
public AndRule (IEnumerable<IRule<TIn>> rules)
{
this.rules = rules;
}
public AndRule (params IRule<TIn>[] rules)
{
this.rules = rules;
}
public RuleResult SatisfiedBy (InputData<TIn> input)
{
RuleResult finalResult = RuleResult.NoMatch;
foreach (var rule in rules) {
RuleResult result = rule.SatisfiedBy (input.NewContext ());
if (result == RuleResult.NoMatch)
return RuleResult.NoMatch;
if (finalResult != RuleResult.MatchNoEmit)
finalResult = result;
input.MatchedRules.Add (rule);
}
return finalResult;
}
}
// yields all inputs that match any specified rules
public class OrRule<TIn> : IRule<TIn> {
protected IEnumerable<IRule<TIn>> rules;
public OrRule (IEnumerable<IRule<TIn>> rules)
{
this.rules = rules;
}
public OrRule (params IRule<TIn>[] rules)
{
this.rules = rules;
}
public RuleResult SatisfiedBy (InputData<TIn> input)
{
foreach (var rule in rules) {
RuleResult result = rule.SatisfiedBy (input.NewContext ());
if (result != RuleResult.NoMatch) {
input.MatchedRules.Add (rule);
return result;
}
}
return RuleResult.NoMatch;
}
}
public class AtEndRule<TIn> : IRule<TIn> {
protected IRule<TIn> rule;
public AtEndRule (IRule<TIn> rule)
{
this.rule = rule;
}
public RuleResult SatisfiedBy (InputData<TIn> input)
{
RuleResult rr = rule.SatisfiedBy (input);
if (!input.Enumerator.MoveNext ())
return rr;
return RuleResult.NoMatch;
}
}
#endregion
// the base point for building up rules
// All rules start For...
public static class For {
public static IRule<TIn> AnyInputIn<TIn> (params TIn [] input)
{
return new InSetRule<TIn> (input);
}
public static IRule<TIn> AnyInputIn<TIn> (IEnumerable<TIn> input)
{
return new InSetRule<TIn> (input);
}
public static SequenceQualifier<TIn> AllInputsIn<TIn> (params TIn [] input)
{
return new SequenceQualifier<TIn> (input, null);
}
public static SequenceQualifier<TIn> AllInputsIn<TIn> (IEnumerable<TIn> input)
{
return new SequenceQualifier<TIn> (input, null);
}
public static RuleCompound<TIn> First<TIn> ()
{
return new RuleCompound<TIn> ((subsequentRules) => {
return new AndRule<TIn> (subsequentRules, new FirstRule<TIn> ());
});
}
public static RuleCompound<TIn> Last<TIn> ()
{
return new RuleCompound<TIn> ((subsequentRules) => {
return new AndRule<TIn> (subsequentRules, new LastRule<TIn> ());
});
}
public static IRule<TIn> InputsWhere<TIn> (Func<TIn, bool> predicate)
{
return new PredicateRule<TIn> (predicate);
}
public static IRule<TIn> AnyInput<TIn> ()
{
return new AnyRule<TIn> ();
}
public static IRule<TIn> UnmatchedInput<TIn> ()
{
return new UnmatchedRule<TIn> ();
}
}
public class RuleCompound<TIn> {
protected Func<IRule<TIn>,IRule<TIn>> additionalRuleCallback;
public RuleCompound (Func<IRule<TIn>,IRule<TIn>> additionalRuleCallback)
{
this.additionalRuleCallback = additionalRuleCallback;
}
public SequenceQualifier<TIn> AllInputsIn (params TIn [] input)
{
return new SequenceQualifier<TIn> (input, additionalRuleCallback);
}
public SequenceQualifier<TIn> AllInputsIn (IEnumerable<TIn> input)
{
return new SequenceQualifier<TIn> (input, additionalRuleCallback);
}
public IRule<TIn> AnyInputIn (params TIn[] input)
{
return additionalRuleCallback (new InSetRule<TIn> (input));
}
public IRule<TIn> AnyInputIn (IEnumerable<TIn> input)
{
return additionalRuleCallback (new InSetRule<TIn> (input));
}
public IRule<TIn> InputsWhere (Func<TIn, bool> predicate)
{
return additionalRuleCallback (new PredicateRule<TIn> (predicate));
}
public IRule<TIn> AnyInput ()
{
return additionalRuleCallback (new AnyRule<TIn> ());
}
}
public class SequenceQualifier<TIn> {
protected IEnumerable<TIn> sequence;
protected Func<IRule<TIn>, IRule<TIn>> additionalRuleCallback;
public SequenceQualifier (IEnumerable<TIn> sequence, Func<IRule<TIn>, IRule<TIn>> additionalRuleCallback)
{
this.sequence = sequence;
this.additionalRuleCallback = additionalRuleCallback ?? (rul => rul);
}
public IRule<TIn> InThatOrder ()
{
return additionalRuleCallback (new InOrderRule<TIn> (sequence));
}
public IRule<TIn> InAnyOrder ()
{
return additionalRuleCallback (new AnyOrderRule<TIn> (sequence));
}
}
public static class Choose {
public static EmitterFunc<TIn, TOut> TopOne<TIn, TOut> (params EmitterFunc<TIn, TOut> [] rules)
{
return delegate (InputData<TIn> input, out TOut output) {
output = default (TOut);
foreach (var rule in rules) {
RuleResult result = rule (input.NewContext (), out output);
if (result != RuleResult.NoMatch)
return result;
}
return RuleResult.NoMatch;
};
}
}
public class CloneableEnumerator<T> : IEnumerator<T> {
private IEnumerable<T> wrappedEnumerable;
private IEnumerator<T> wrappedEnumerator;
private int position;
public CloneableEnumerator (IEnumerable<T> enumerable, int position)
{
this.wrappedEnumerable = enumerable;
this.position = position;
this.wrappedEnumerator = wrappedEnumerable.GetEnumerator ();
for (int i = 0; i < position; i++)
wrappedEnumerator.MoveNext ();
}
public CloneableEnumerator<T> Clone () {
return new CloneableEnumerator<T> (this.wrappedEnumerable, this.position);
}
public void Reset ()
{
wrappedEnumerator.Reset ();
}
public bool MoveNext ()
{
position++;
return wrappedEnumerator.MoveNext ();
}
public T Current {
get { return wrappedEnumerator.Current; }
}
object IEnumerator.Current {
get { return this.Current; }
}
public void Dispose ()
{
}
}
}
| |
/*
* 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.Linq;
using System.Numerics;
using Newtonsoft.Json;
using QuantConnect.Configuration;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Util;
namespace QuantConnect
{
/// <summary>
/// Defines a unique identifier for securities
/// </summary>
/// <remarks>
/// The SecurityIdentifier contains information about a specific security.
/// This includes the symbol and other data specific to the SecurityType.
/// The symbol is limited to 12 characters
/// </remarks>
[JsonConverter(typeof(SecurityIdentifierJsonConverter))]
public struct SecurityIdentifier : IEquatable<SecurityIdentifier>
{
#region Empty, DefaultDate Fields
private static readonly string MapFileProviderTypeName = Config.Get("map-file-provider", "LocalDiskMapFileProvider");
private static readonly char[] InvalidCharacters = {'|', ' '};
/// <summary>
/// Gets an instance of <see cref="SecurityIdentifier"/> that is empty, that is, one with no symbol specified
/// </summary>
public static readonly SecurityIdentifier Empty = new SecurityIdentifier(string.Empty, 0);
/// <summary>
/// Gets the date to be used when it does not apply.
/// </summary>
public static readonly DateTime DefaultDate = DateTime.FromOADate(0);
/// <summary>
/// Gets the set of invalids symbol characters
/// </summary>
public static readonly HashSet<char> InvalidSymbolCharacters = new HashSet<char>(InvalidCharacters);
#endregion
#region Scales, Widths and Market Maps
// these values define the structure of the 'otherData'
// the constant width fields are used via modulus, so the width is the number of zeros specified,
// {put/call:1}{oa-date:5}{style:1}{strike:6}{strike-scale:2}{market:3}{security-type:2}
private const ulong SecurityTypeWidth = 100;
private const ulong SecurityTypeOffset = 1;
private const ulong MarketWidth = 1000;
private const ulong MarketOffset = SecurityTypeOffset * SecurityTypeWidth;
private const int StrikeDefaultScale = 4;
private static readonly ulong StrikeDefaultScaleExpanded = Pow(10, StrikeDefaultScale);
private const ulong StrikeScaleWidth = 100;
private const ulong StrikeScaleOffset = MarketOffset * MarketWidth;
private const ulong StrikeWidth = 1000000;
private const ulong StrikeOffset = StrikeScaleOffset * StrikeScaleWidth;
private const ulong OptionStyleWidth = 10;
private const ulong OptionStyleOffset = StrikeOffset * StrikeWidth;
private const ulong DaysWidth = 100000;
private const ulong DaysOffset = OptionStyleOffset * OptionStyleWidth;
private const ulong PutCallOffset = DaysOffset * DaysWidth;
private const ulong PutCallWidth = 10;
#endregion
#region Member variables
private readonly string _symbol;
private readonly ulong _properties;
private readonly SidBox _underlying;
#endregion
#region Properties
/// <summary>
/// Gets whether or not this <see cref="SecurityIdentifier"/> is a derivative,
/// that is, it has a valid <see cref="Underlying"/> property
/// </summary>
public bool HasUnderlying
{
get { return _underlying != null; }
}
/// <summary>
/// Gets the underlying security identifier for this security identifier. When there is
/// no underlying, this property will return a value of <see cref="Empty"/>.
/// </summary>
public SecurityIdentifier Underlying
{
get
{
if (_underlying == null)
{
throw new InvalidOperationException("No underlying specified for this identifier. Check that HasUnderlying is true before accessing the Underlying property.");
}
return _underlying.SecurityIdentifier;
}
}
/// <summary>
/// Gets the date component of this identifier. For equities this
/// is the first date the security traded. Technically speaking,
/// in LEAN, this is the first date mentioned in the map_files.
/// For options this is the expiry date. For futures this is the
/// settlement date. For forex and cfds this property will throw an
/// exception as the field is not specified.
/// </summary>
public DateTime Date
{
get
{
var stype = SecurityType;
switch (stype)
{
case SecurityType.Equity:
case SecurityType.Option:
case SecurityType.Future:
var oadate = ExtractFromProperties(DaysOffset, DaysWidth);
return DateTime.FromOADate(oadate);
default:
throw new InvalidOperationException("Date is only defined for SecurityType.Equity, SecurityType.Option and SecurityType.Future");
}
}
}
/// <summary>
/// Gets the original symbol used to generate this security identifier.
/// For equities, by convention this is the first ticker symbol for which
/// the security traded
/// </summary>
public string Symbol
{
get { return _symbol; }
}
/// <summary>
/// Gets the market component of this security identifier. If located in the
/// internal mappings, the full string is returned. If the value is unknown,
/// the integer value is returned as a string.
/// </summary>
public string Market
{
get
{
var marketCode = ExtractFromProperties(MarketOffset, MarketWidth);
var market = QuantConnect.Market.Decode((int)marketCode);
// if we couldn't find it, send back the numeric representation
return market ?? marketCode.ToString();
}
}
/// <summary>
/// Gets the security type component of this security identifier.
/// </summary>
public SecurityType SecurityType
{
get { return (SecurityType)ExtractFromProperties(SecurityTypeOffset, SecurityTypeWidth); }
}
/// <summary>
/// Gets the option strike price. This only applies to SecurityType.Option
/// and will thrown anexception if accessed otherwse.
/// </summary>
public decimal StrikePrice
{
get
{
if (SecurityType != SecurityType.Option)
{
throw new InvalidOperationException("OptionType is only defined for SecurityType.Option");
}
var scale = ExtractFromProperties(StrikeScaleOffset, StrikeScaleWidth);
var unscaled = ExtractFromProperties(StrikeOffset, StrikeWidth);
var pow = Math.Pow(10, (int)scale - StrikeDefaultScale);
return unscaled * (decimal)pow;
}
}
/// <summary>
/// Gets the option type component of this security identifier. This
/// only applies to SecurityType.Open and will throw an exception if
/// accessed otherwise.
/// </summary>
public OptionRight OptionRight
{
get
{
if (SecurityType != SecurityType.Option)
{
throw new InvalidOperationException("OptionRight is only defined for SecurityType.Option");
}
return (OptionRight)ExtractFromProperties(PutCallOffset, PutCallWidth);
}
}
/// <summary>
/// Gets the option style component of this security identifier. This
/// only applies to SecurityType.Open and will throw an exception if
/// accessed otherwise.
/// </summary>
public OptionStyle OptionStyle
{
get
{
if (SecurityType != SecurityType.Option)
{
throw new InvalidOperationException("OptionStyle is only defined for SecurityType.Option");
}
return (OptionStyle)(ExtractFromProperties(OptionStyleOffset, OptionStyleWidth));
}
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SecurityIdentifier"/> class
/// </summary>
/// <param name="symbol">The base36 string encoded as a long using alpha [0-9A-Z]</param>
/// <param name="properties">Other data defining properties of the symbol including market,
/// security type, listing or expiry date, strike/call/put/style for options, ect...</param>
public SecurityIdentifier(string symbol, ulong properties)
{
if (symbol == null)
{
throw new ArgumentNullException("symbol", "SecurityIdentifier requires a non-null string 'symbol'");
}
if (symbol.IndexOfAny(InvalidCharacters) != -1)
{
throw new ArgumentException("symbol must not contain the characters '|' or ' '.", "symbol");
}
_symbol = symbol;
_properties = properties;
_underlying = null;
}
/// <summary>
/// Initializes a new instance of the <see cref="SecurityIdentifier"/> class
/// </summary>
/// <param name="symbol">The base36 string encoded as a long using alpha [0-9A-Z]</param>
/// <param name="properties">Other data defining properties of the symbol including market,
/// security type, listing or expiry date, strike/call/put/style for options, ect...</param>
/// <param name="underlying">Specifies a <see cref="SecurityIdentifier"/> that represents the underlying security</param>
public SecurityIdentifier(string symbol, ulong properties, SecurityIdentifier underlying)
: this(symbol, properties)
{
if (symbol == null)
{
throw new ArgumentNullException("symbol", "SecurityIdentifier requires a non-null string 'symbol'");
}
_symbol = symbol;
_properties = properties;
if (underlying != Empty)
{
_underlying = new SidBox(underlying);
}
}
#endregion
#region AddMarket, GetMarketCode, and Generate
/// <summary>
/// Generates a new <see cref="SecurityIdentifier"/> for an option
/// </summary>
/// <param name="expiry">The date the option expires</param>
/// <param name="underlying">The underlying security's symbol</param>
/// <param name="market">The market</param>
/// <param name="strike">The strike price</param>
/// <param name="optionRight">The option type, call or put</param>
/// <param name="optionStyle">The option style, American or European</param>
/// <returns>A new <see cref="SecurityIdentifier"/> representing the specified option security</returns>
public static SecurityIdentifier GenerateOption(DateTime expiry,
SecurityIdentifier underlying,
string market,
decimal strike,
OptionRight optionRight,
OptionStyle optionStyle)
{
return Generate(expiry, underlying.Symbol, SecurityType.Option, market, strike, optionRight, optionStyle, underlying);
}
/// <summary>
/// Generates a new <see cref="SecurityIdentifier"/> for a future
/// </summary>
/// <param name="expiry">The date the future expires</param>
/// <param name="symbol">The security's symbol</param>
/// <param name="market">The market</param>
/// <returns>A new <see cref="SecurityIdentifier"/> representing the specified futures security</returns>
public static SecurityIdentifier GenerateFuture(DateTime expiry,
string symbol,
string market)
{
return Generate(expiry, symbol, SecurityType.Future, market);
}
/// <summary>
/// Helper overload that will search the mapfiles to resolve the first date. This implementation
/// uses the configured <see cref="IMapFileProvider"/> via the <see cref="Composer.Instance"/>
/// </summary>
/// <param name="symbol">The symbol as it is known today</param>
/// <param name="market">The market</param>
/// <param name="mapSymbol">Specifies if symbol should be mapped using map file provider</param>
/// <returns>A new <see cref="SecurityIdentifier"/> representing the specified symbol today</returns>
public static SecurityIdentifier GenerateEquity(string symbol, string market, bool mapSymbol = true)
{
if (mapSymbol)
{
var provider = Composer.Instance.GetExportedValueByTypeName<IMapFileProvider>(MapFileProviderTypeName);
var resolver = provider.Get(market);
var mapFile = resolver.ResolveMapFile(symbol, DateTime.Today);
var firstDate = mapFile.FirstDate;
if (mapFile.Any())
{
symbol = mapFile.OrderBy(x => x.Date).First().MappedSymbol;
}
return GenerateEquity(firstDate, symbol, market);
}
else
{
return GenerateEquity(DefaultDate, symbol, market);
}
}
/// <summary>
/// Generates a new <see cref="SecurityIdentifier"/> for an equity
/// </summary>
/// <param name="date">The first date this security traded (in LEAN this is the first date in the map_file</param>
/// <param name="symbol">The ticker symbol this security traded under on the <paramref name="date"/></param>
/// <param name="market">The security's market</param>
/// <returns>A new <see cref="SecurityIdentifier"/> representing the specified equity security</returns>
public static SecurityIdentifier GenerateEquity(DateTime date, string symbol, string market)
{
return Generate(date, symbol, SecurityType.Equity, market);
}
/// <summary>
/// Generates a new <see cref="SecurityIdentifier"/> for a custom security
/// </summary>
/// <param name="symbol">The ticker symbol of this security</param>
/// <param name="market">The security's market</param>
/// <returns>A new <see cref="SecurityIdentifier"/> representing the specified base security</returns>
public static SecurityIdentifier GenerateBase(string symbol, string market)
{
return Generate(DefaultDate, symbol, SecurityType.Base, market);
}
/// <summary>
/// Generates a new <see cref="SecurityIdentifier"/> for a forex pair
/// </summary>
/// <param name="symbol">The currency pair in the format similar to: 'EURUSD'</param>
/// <param name="market">The security's market</param>
/// <returns>A new <see cref="SecurityIdentifier"/> representing the specified forex pair</returns>
public static SecurityIdentifier GenerateForex(string symbol, string market)
{
return Generate(DefaultDate, symbol, SecurityType.Forex, market);
}
/// <summary>
/// Generates a new <see cref="SecurityIdentifier"/> for a CFD security
/// </summary>
/// <param name="symbol">The CFD contract symbol</param>
/// <param name="market">The security's market</param>
/// <returns>A new <see cref="SecurityIdentifier"/> representing the specified CFD security</returns>
public static SecurityIdentifier GenerateCfd(string symbol, string market)
{
return Generate(DefaultDate, symbol, SecurityType.Cfd, market);
}
/// <summary>
/// Generic generate method. This method should be used carefully as some parameters are not required and
/// some parameters mean different things for different security types
/// </summary>
private static SecurityIdentifier Generate(DateTime date,
string symbol,
SecurityType securityType,
string market,
decimal strike = 0,
OptionRight optionRight = 0,
OptionStyle optionStyle = 0,
SecurityIdentifier? underlying = null)
{
if ((ulong)securityType >= SecurityTypeWidth || securityType < 0)
{
throw new ArgumentOutOfRangeException("securityType", "securityType must be between 0 and 99");
}
if ((int)optionRight > 1 || optionRight < 0)
{
throw new ArgumentOutOfRangeException("optionRight", "optionType must be either 0 or 1");
}
// normalize input strings
market = market.ToLower();
symbol = symbol.ToUpper();
var marketIdentifier = QuantConnect.Market.Encode(market);
if (!marketIdentifier.HasValue)
{
throw new ArgumentOutOfRangeException("market", string.Format("The specified market wasn't found in the markets lookup. Requested: {0}. " +
"You can add markets by calling QuantConnect.Market.AddMarket(string,ushort)", market));
}
var days = (ulong)date.ToOADate() * DaysOffset;
var marketCode = (ulong)marketIdentifier * MarketOffset;
ulong strikeScale;
var strk = NormalizeStrike(strike, out strikeScale) * StrikeOffset;
strikeScale *= StrikeScaleOffset;
var style = (ulong)optionStyle * OptionStyleOffset;
var putcall = (ulong)optionRight * PutCallOffset;
var otherData = putcall + days + style + strk + strikeScale + marketCode + (ulong)securityType;
return new SecurityIdentifier(symbol, otherData, underlying ?? Empty);
}
/// <summary>
/// Converts an upper case alpha numeric string into a long
/// </summary>
private static ulong DecodeBase36(string symbol)
{
int pos = 0;
ulong result = 0;
for (int i = symbol.Length - 1; i > -1; i--)
{
var c = symbol[i];
// assumes alpha numeric upper case only strings
var value = (uint)(c <= 57
? c - '0'
: c - 'A' + 10);
result += value * Pow(36, pos++);
}
return result;
}
/// <summary>
/// Converts a long to an uppercase alpha numeric string
/// </summary>
private static string EncodeBase36(ulong data)
{
var stack = new Stack<char>();
while (data != 0)
{
var value = data % 36;
var c = value < 10
? (char)(value + '0')
: (char)(value - 10 + 'A');
stack.Push(c);
data /= 36;
}
return new string(stack.ToArray());
}
/// <summary>
/// The strike is normalized into deci-cents and then a scale factor
/// is also saved to bring it back to un-normalized
/// </summary>
private static ulong NormalizeStrike(decimal strike, out ulong scale)
{
var str = strike;
if (strike == 0)
{
scale = 0;
return 0;
}
// convert strike to default scaling, this keeps the scale always positive
strike *= StrikeDefaultScaleExpanded;
scale = 0;
while (strike % 10 == 0)
{
strike /= 10;
scale++;
}
if (strike >= 1000000)
{
throw new ArgumentException("The specified strike price's precision is too high: " + str);
}
return (ulong)strike;
}
/// <summary>
/// Accurately performs the integer exponentiation
/// </summary>
private static ulong Pow(uint x, int pow)
{
// don't use Math.Pow(double, double) due to precision issues
return (ulong)BigInteger.Pow(x, pow);
}
#endregion
#region Parsing routines
/// <summary>
/// Parses the specified string into a <see cref="SecurityIdentifier"/>
/// The string must be a 40 digit number. The first 20 digits must be parseable
/// to a 64 bit unsigned integer and contain ancillary data about the security.
/// The second 20 digits must also be parseable as a 64 bit unsigned integer and
/// contain the symbol encoded from base36, this provides for 12 alpha numeric case
/// insensitive characters.
/// </summary>
/// <param name="value">The string value to be parsed</param>
/// <returns>A new <see cref="SecurityIdentifier"/> instance if the <paramref name="value"/> is able to be parsed.</returns>
/// <exception cref="FormatException">This exception is thrown if the string's length is not exactly 40 characters, or
/// if the components are unable to be parsed as 64 bit unsigned integers</exception>
public static SecurityIdentifier Parse(string value)
{
Exception exception;
SecurityIdentifier identifier;
if (!TryParse(value, out identifier, out exception))
{
throw exception;
}
return identifier;
}
/// <summary>
/// Attempts to parse the specified <see paramref="value"/> as a <see cref="SecurityIdentifier"/>.
/// </summary>
/// <param name="value">The string value to be parsed</param>
/// <param name="identifier">The result of parsing, when this function returns true, <paramref name="identifier"/>
/// was properly created and reflects the input string, when this function returns false <paramref name="identifier"/>
/// will equal default(SecurityIdentifier)</param>
/// <returns>True on success, otherwise false</returns>
public static bool TryParse(string value, out SecurityIdentifier identifier)
{
Exception exception;
return TryParse(value, out identifier, out exception);
}
/// <summary>
/// Helper method impl to be used by parse and tryparse
/// </summary>
private static bool TryParse(string value, out SecurityIdentifier identifier, out Exception exception)
{
if (!TryParseProperties(value, out exception, out identifier))
{
return false;
}
return true;
}
/// <summary>
/// Parses the string into its component ulong pieces
/// </summary>
private static bool TryParseProperties(string value, out Exception exception, out SecurityIdentifier identifier)
{
exception = null;
identifier = Empty;
if (string.IsNullOrWhiteSpace(value))
{
return true;
}
try
{
var sids = value.Split('|');
for (var i = sids.Length - 1; i > -1; i--)
{
var current = sids[i];
var parts = current.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2)
{
exception = new FormatException("The string must be splittable on space into two parts.");
return false;
}
var symbol = parts[0];
var otherData = parts[1];
var props = DecodeBase36(otherData);
// toss the previous in as the underlying, if Empty, ignored by ctor
identifier = new SecurityIdentifier(symbol, props, identifier);
}
}
catch (Exception error)
{
exception = error;
Log.Error("SecurityIdentifier.TryParseProperties(): Error parsing SecurityIdentifier: '{0}', Exception: {1}", value, exception);
return false;
}
return true;
}
/// <summary>
/// Extracts the embedded value from _otherData
/// </summary>
private ulong ExtractFromProperties(ulong offset, ulong width)
{
return (_properties/offset)%width;
}
#endregion
#region Equality members and ToString
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(SecurityIdentifier other)
{
return _properties == other._properties
&& _symbol == other._symbol
&& _underlying == other._underlying;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// true if the specified object is equal to the current object; otherwise, false.
/// </returns>
/// <param name="obj">The object to compare with the current object. </param><filterpriority>2</filterpriority>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != GetType()) return false;
return Equals((SecurityIdentifier)obj);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
/// <filterpriority>2</filterpriority>
public override int GetHashCode()
{
unchecked { return (_symbol.GetHashCode()*397) ^ _properties.GetHashCode(); }
}
/// <summary>
/// Override equals operator
/// </summary>
public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right)
{
return Equals(left, right);
}
/// <summary>
/// Override not equals operator
/// </summary>
public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right)
{
return !Equals(left, right);
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
var props = EncodeBase36(_properties);
if (HasUnderlying)
{
return _symbol + ' ' + props + '|' + _underlying.SecurityIdentifier;
}
return _symbol + ' ' + props;
}
#endregion
/// <summary>
/// Provides a reference type container for a security identifier instance.
/// This is used to maintain a reference to an underlying
/// </summary>
private sealed class SidBox : IEquatable<SidBox>
{
public readonly SecurityIdentifier SecurityIdentifier;
public SidBox(SecurityIdentifier securityIdentifier)
{
SecurityIdentifier = securityIdentifier;
}
public bool Equals(SidBox other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return SecurityIdentifier.Equals(other.SecurityIdentifier);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj is SidBox && Equals((SidBox)obj);
}
public override int GetHashCode()
{
return SecurityIdentifier.GetHashCode();
}
public static bool operator ==(SidBox left, SidBox right)
{
return Equals(left, right);
}
public static bool operator !=(SidBox left, SidBox right)
{
return !Equals(left, right);
}
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Spinvoice.QuickBooks.Domain;
using Spinvoice.Utils;
namespace Spinvoice.Domain.Accounting
{
public class Invoice : INotifyPropertyChanged
{
private DateTime _date;
private string _companyName;
private string _invoiceNumber;
private decimal _netAmount;
private string _currency;
private decimal _vatAmount;
private string _country;
private decimal _exchangeRate;
private bool _isEuropeanUnion;
private string _vatNumber;
private string _externalCompanyId;
private string _externalId;
private decimal _transportationCosts;
private Side _side;
public event Action CurrencyChanged;
public event Action DateChanged;
public event Action SideChanged;
public Invoice()
{
Positions = new ObservableCollection<Position>();
Side = Side.Vendor;
}
public Side Side
{
get { return _side; }
set
{
if (_side == value) return;
_side = value;
OnPropertyChanged();
SideChanged.Raise();
}
}
public DateTime Date
{
get { return _date; }
set
{
if (_date == value) return;
_date = value;
OnPropertyChanged();
DateChanged.Raise();
}
}
public string CompanyName
{
get { return _companyName; }
set
{
_companyName = value;
OnPropertyChanged();
}
}
public string InvoiceNumber
{
get { return _invoiceNumber; }
set
{
_invoiceNumber = value;
OnPropertyChanged();
}
}
public string Currency
{
get { return _currency; }
set
{
_currency = value;
OnPropertyChanged();
CurrencyChanged.Raise();
}
}
public decimal ExchangeRate
{
get { return _exchangeRate; }
set
{
_exchangeRate = value;
OnPropertyChanged();
OnOtherPropertyChanged(nameof(TotalAmount));
OnOtherPropertyChanged(nameof(TotalAmountInHomeCurrency));
}
}
public string Country
{
get { return _country; }
set
{
_country = value;
OnPropertyChanged();
}
}
public decimal NetAmount
{
get { return _netAmount; }
set
{
_netAmount = value;
OnPropertyChanged();
OnOtherPropertyChanged(nameof(TotalAmount));
OnOtherPropertyChanged(nameof(TotalAmountInHomeCurrency));
}
}
public decimal VatAmount
{
get { return _vatAmount; }
set
{
_vatAmount = value;
OnPropertyChanged();
OnOtherPropertyChanged(nameof(TotalAmount));
OnOtherPropertyChanged(nameof(TotalAmountInHomeCurrency));
}
}
public decimal TransportationCosts
{
get { return _transportationCosts; }
set
{
_transportationCosts = value;
OnPropertyChanged();
OnOtherPropertyChanged(nameof(TotalAmount));
OnOtherPropertyChanged(nameof(TotalAmountInHomeCurrency));
}
}
public decimal TotalAmount => NetAmount + VatAmount + TransportationCosts;
public decimal TotalAmountInHomeCurrency => Round(TotalAmount * _exchangeRate);
private static decimal Round(decimal value)
{
return Math.Round(value, 2, MidpointRounding.AwayFromZero);
}
public bool IsEuropeanUnion
{
get { return _isEuropeanUnion; }
set
{
_isEuropeanUnion = value;
OnPropertyChanged();
}
}
public string VatNumber
{
get { return _vatNumber; }
set
{
_vatNumber = value;
OnPropertyChanged();
}
}
public ObservableCollection<Position> Positions { get; set; }
public string ExternalCompanyId
{
get { return _externalCompanyId; }
set
{
_externalCompanyId = value;
OnPropertyChanged();
}
}
public string ExternalId
{
get { return _externalId; }
set
{
if (_externalId == value) return;
_externalId = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
OnOtherPropertyChanged(propertyName);
}
private void OnOtherPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public void ApplyCompany(Company.Company company)
{
CompanyName = company.Name;
Country = company.Country;
Currency = company.Currency;
VatNumber = company.VatNumber;
IsEuropeanUnion = company.IsEuropeanUnion;
Side = company.Side;
ExternalCompanyId = company.ExternalId;
}
public void Clear()
{
_companyName = null;
_exchangeRate = 0;
_country = null;
_date = new DateTime();
_currency = null;
_invoiceNumber = null;
_netAmount = 0;
_vatAmount = 0;
_vatNumber = null;
_isEuropeanUnion = false;
_externalCompanyId = null;
_side = Side.Vendor;
Positions.Clear();
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(""));
}
}
}
| |
//
// Extensions.cs
//
// Author:
// Jarl Erik Schmidt <github@jarlerik.com>
//
// Copyright (c) 2013 Jarl Erik Schmidt
//
// 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.
namespace Winterday.External.Gengo
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using Winterday.External.Gengo.Payloads;
using Winterday.External.Gengo.Properties;
/// <summary>
/// Contains extension methods used internally to ease working with Json
/// content and enumerations.
/// </summary>
internal static class Extensions
{
internal static decimal ToDecimal(this string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return 0;
}
decimal d;
Decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out d);
return d;
}
const NumberStyles UIntStyle = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite;
internal static long ToLong(this string value)
{
if (string.IsNullOrEmpty(value))
{
return 0;
}
long i;
Int64.TryParse(value, UIntStyle, CultureInfo.InvariantCulture, out i);
return i;
}
internal static string ToQueryString(this Dictionary<string, string> dict)
{
if (dict == null)
{
return string.Empty;
}
var sb = new StringBuilder();
foreach (var pair in dict)
{
if (!string.IsNullOrWhiteSpace(pair.Key))
{
if (sb.Length == 0)
{
sb.Append("?");
}
else
{
sb.Append("&");
}
sb.Append(pair.Key.HexEscape());
sb.Append("=");
sb.Append(pair.Value.HexEscape());
}
}
return sb.ToString();
}
static string HexEscape(this string value)
{
return String.Join(String.Empty, value.ToCharArray().Select(c => c.HexEscape()));
}
static string HexEscape(this char c)
{
if ((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122))
{
return c.ToString();
}
return Uri.HexEscape(c);
}
internal static string ToTypeString(this JobType type)
{
return type.ToString().ToLowerInvariant();
}
internal static EnumT TryParseEnum<EnumT>(this string value, EnumT defaultValue, bool removeSpaces) where EnumT : struct
{
EnumT result = defaultValue;
if (removeSpaces)
{
value = (value ?? String.Empty).Replace(" ", "");
}
if (Enum.TryParse<EnumT>(value, true, out result))
{
return result;
}
return defaultValue;
}
internal static AuthorType ToAuthorType(this string value)
{
return value.TryParseEnum(AuthorType.Unknown, true);
}
internal static string ToAuthorString(this AuthorType type)
{
if (type == AuthorType.SeniorTranslator)
{
return "senior translator";
}
else
{
return type.ToString().ToLowerInvariant();
}
}
internal static JobType ToJobType(this string value)
{
return value.TryParseEnum(JobType.Text, false);
}
internal static string ToReasonString(this RejectionReason reason)
{
return reason.ToString().ToLowerInvariant();
}
internal static string ToTierString(this TranslationTier tier)
{
return tier.ToString().ToLowerInvariant();
}
internal static TranslationTier ToTranslationTier(this string value)
{
return value.TryParseEnum(TranslationTier.Unknown, false);
}
internal static string ToStatusString(this TranslationStatus status)
{
return status.ToString().ToLowerInvariant();
}
internal static TranslationStatus ToTranslationStatus(this string value)
{
return value.TryParseEnum(TranslationStatus.Unknown, false);
}
internal static byte[] ToUTF8Bytes(this string value)
{
return Encoding.UTF8.GetBytes(value);
}
internal static String SHA1Hash(this String privateKey, String value)
{
var keybytes = privateKey.ToUTF8Bytes();
var valuebytes = value.ToUTF8Bytes();
var algo = new HMACSHA1(keybytes);
var hash = algo.ComputeHash(valuebytes);
var sb = new StringBuilder(2 * hash.Length);
foreach (var b in hash)
{
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
static readonly DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
internal static long ToTimeStamp(this DateTime time)
{
return (long)(time - unixEpoch).TotalSeconds;
}
internal static DateTime ToDateFromTimestamp(this long timestamp)
{
return unixEpoch.AddSeconds(timestamp);
}
internal static JArray ToJsonJobsArray(this IEnumerable<Job> jobs)
{
if (jobs == null) throw new ArgumentNullException("jobs");
var arr = new JArray();
foreach (var job in jobs)
{
arr.Add(job.ToJObject());
}
return arr;
}
internal static Tuple<JObject, Dictionary<string, Job>> ToJsonJobsList(this IEnumerable<Job> jobs)
{
if (jobs == null) throw new ArgumentNullException("jobs");
var count = 1;
var jobsObj = new JObject();
var mapping = new Dictionary<string, Job>();
foreach (var item in jobs)
{
if (item is SubmittedJob)
throw new ArgumentException(
Resources.JobIsAlreadySubmitted);
var key = "job_" + count;
mapping[key] = item;
jobsObj[key] = item.ToJObject();
count += 1;
}
return Tuple.Create(jobsObj, mapping);
}
internal static IReadOnlyList<int>
ReadIntArrayAsRoList(this JObject obj, string propName)
{
if (string.IsNullOrWhiteSpace(propName))
throw new ArgumentException(Resources.PropertyNameNotProvided);
var list = new List<int>();
obj.ReadIntArrayIntoList(propName, list);
return list;
}
internal static void ReadIntArrayIntoList(this JObject obj, string propName, IList<int> ints)
{
if (string.IsNullOrWhiteSpace(propName))
throw new ArgumentException(Resources.PropertyNameNotProvided);
if (ints == null)
throw new ArgumentNullException("ints");
if (ints.IsReadOnly)
throw new ArgumentException(Resources.ListIsReadOnly, "ints");
if (obj == null)
return;
var arr = obj.Value<JArray>(propName);
if (arr == null)
return;
foreach (var item in arr)
{
if (item == null) continue;
int i;
if (Int32.TryParse(
item.ToString(),
NumberStyles.Integer,
CultureInfo.InvariantCulture,
out i))
{
ints.Add(i);
}
}
}
internal static bool BoolValueStrict(this JObject json, string propName)
{
return (json.IntValueStrict(propName) == 1);
}
internal static DateTime DateValueStrict(this JObject json, string propName)
{
return (json.LongValueStrict(propName).ToDateFromTimestamp());
}
internal static decimal DecValueStrict(this JObject json, string propName)
{
if (json == null)
throw new ArgumentNullException("json");
if (string.IsNullOrWhiteSpace(propName))
throw new ArgumentException(Resources.PropertyNameNotProvided);
decimal i;
if (Decimal.TryParse(
json.Value<string>(propName),
NumberStyles.Number,
CultureInfo.InvariantCulture,
out i))
{
return i;
}
else
{
var err = string.Format
(Resources.NamedPropertyNotFound,
propName);
throw new ArgumentException(err, "json");
}
}
internal static int IntValueStrict(this JObject json, string propName)
{
if (json == null)
throw new ArgumentNullException("json");
if (string.IsNullOrWhiteSpace(propName))
throw new ArgumentException(Resources.PropertyNameNotProvided);
int i;
if (Int32.TryParse(
json.Value<string>(propName),
NumberStyles.Integer,
CultureInfo.InvariantCulture,
out i))
{
return i;
}
else {
var err = string.Format
(Resources.NamedPropertyNotFound,
propName);
throw new ArgumentException(err, "json");
}
}
internal static long LongValueStrict(this JObject json, string propName)
{
if (json == null)
throw new ArgumentNullException("json");
if (string.IsNullOrWhiteSpace(propName))
throw new ArgumentException(Resources.PropertyNameNotProvided);
long i;
if (Int64.TryParse(
json.Value<string>(propName),
NumberStyles.Number,
CultureInfo.InvariantCulture,
out i))
{
return i;
}
else
{
var err = string.Format
(Resources.NamedPropertyNotFound,
propName);
throw new ArgumentException(err, "json");
}
}
internal static TimeSpan TsValueStrict(this JObject json, string propName)
{
return TimeSpan.FromSeconds(json.IntValueStrict(propName));
}
internal static async Task<JsonT> GetJsonPropertyAsync<JsonT>(
this IGengoClient client, string propName, String uriPart, bool authenticated
) where JsonT : JToken
{
var data = await client.GetJsonAsync<JObject>(uriPart, authenticated);
if (data == null) throw new Exception(
"Remote service did not return object.");
var result = data[propName] as JsonT;
if (result == null) throw new Exception(
"Object returned by remote service did not have property " + propName + " of type " + typeof(JsonT).Name);
return result;
}
internal static IEnumerable<JObject> Objects(this JArray arr)
{
return arr == null ?
Enumerable.Empty<JObject>() :
arr.OfType<JObject>();
}
internal static IEnumerable<T> SelectFromObjects<T>(
this JArray arr, Func<JObject, T> selector)
{
if (selector == null) throw new ArgumentNullException("func");
return arr.Objects().Select(selector);
}
internal static HttpContent GetFormUrlEncodedContent(Dictionary<string, string> data)
{
var builder = new StringBuilder();
foreach (var dataPart in data)
{
builder.Append(dataPart.Key + "=");
builder.Append((string) EncodeLargeData(dataPart.Value));
builder.Append("&");
}
builder.Remove(builder.Length - 1, 1);
var content = new StringContent(builder.ToString(), Encoding.UTF8);
content.Headers.ContentType =
new MediaTypeHeaderValue("application/x-www-form-urlencoded");
return content;
}
private static string EncodeLargeData(string data)
{
const int LARGE_DATA_LIMIT = 2000;
var builder = new StringBuilder();
var loopCount = data.Length/LARGE_DATA_LIMIT;
for (var i = 0; i <= loopCount; i++)
{
if (i < loopCount)
{
builder.Append(Uri.EscapeDataString(data.Substring(LARGE_DATA_LIMIT*i, LARGE_DATA_LIMIT)));
}
else
{
builder.Append(Uri.EscapeDataString(data.Substring(LARGE_DATA_LIMIT * i)));
}
}
return builder.ToString();
}
}
}
| |
// Author: abi
// Project: DungeonQuest
// Path: C:\code\Xna\DungeonQuest\Shaders
// Creation date: 28.03.2007 01:01
// Last modified: 31.07.2007 04:47
#region Using directives
using Microsoft.Xna.Framework.Graphics;
using System;
using DungeonQuest.Graphics;
using DungeonQuest.Helpers;
using DungeonQuest.Game;
#endregion
namespace DungeonQuest.Shaders
{
/// <summary>
/// ShadowMapBlur based on PostScreenBlur to blur the final shadow map
/// output for a more smooth view on the screen.
/// </summary>
public class ShadowMapBlur : ShaderEffect
{
#region Variables
/// <summary>
/// The shader xnaEffect filename for this shader.
/// </summary>
private const string Filename = "PostScreenShadowBlur";
/// <summary>
/// Effect handles for window size and scene map.
/// </summary>
private EffectParameter windowSize,
sceneMap;//,
//blurMap;
/// <summary>
/// Links to the render to texture instances.
/// </summary>
private RenderToTexture sceneMapTexture;//,
//blurMapTexture;
/// <summary>
/// Scene map texture
/// </summary>
/// <returns>Render to texture</returns>
public RenderToTexture SceneMapTexture
{
get
{
return sceneMapTexture;
} // get
} // SceneMapTexture
/*obs
/// <summary>
/// Blur map texture
/// </summary>
/// <returns>Render to texture</returns>
public RenderToTexture BlurMapTexture
{
get
{
return blurMapTexture;
} // get
} // BlurMapTexture
*/
#endregion
#region Create
/// <summary>
/// Create shadow map screen blur shader.
/// obs, using full size again: But only use 1/4 of the screen!
/// </summary>
public ShadowMapBlur()
: base(Filename)
{
// Scene map texture
sceneMapTexture = new RenderToTexture(
//RenderToTexture.SizeType.FullScreen);
//RenderToTexture.SizeType.FullScreenWithZBuffer);
//improve performance:
//RenderToTexture.SizeType.HalfScreen);
//TODO if problems:
RenderToTexture.SizeType.HalfScreenWithZBuffer);
/*obs
blurMapTexture = new RenderToTexture(
RenderToTexture.SizeType.FullScreen);
//RenderToTexture.SizeType.FullScreenWithZBuffer);
//improve performance:
//RenderToTexture.SizeType.HalfScreen);
*/
} // ShadowMapBlur()
#endregion
#region Get parameters
/// <summary>
/// Reload
/// </summary>
protected override void GetParameters()
{
// Can't get parameters if loading failed!
if (xnaEffect == null)
return;
windowSize = xnaEffect.Parameters["windowSize"];
sceneMap = xnaEffect.Parameters["sceneMap"];
//blurMap = xnaEffect.Parameters["blurMap"];
// We need both windowSize and sceneMap.
if (windowSize == null ||
sceneMap == null)
throw new NotSupportedException("windowSize and sceneMap must be " +
"valid in PostScreenShader=" + Filename);
} // GetParameters()
#endregion
#region RenderShadows
/// <summary>
/// Render shadows
/// </summary>
/// <param name="renderCode">Render code</param>
public void RenderShadows(BaseGame.RenderDelegate renderCode)
{
// Render into our scene map texture
sceneMapTexture.SetRenderTarget();
//*TODO
DepthStencilBuffer remBackBufferSurface = null;
if (sceneMapTexture.ZBufferSurface != null)
{
remBackBufferSurface = BaseGame.Device.DepthStencilBuffer;
BaseGame.Device.DepthStencilBuffer =
sceneMapTexture.ZBufferSurface;
} // if (sceneMapTexture.ZBufferSurface)
//*/
// Clear render target
sceneMapTexture.Clear(Color.White);
// Render everything
renderCode();
// Resolve render target
sceneMapTexture.Resolve();
// Restore back buffer as render target
BaseGame.ResetRenderTarget(false);
//*TODO
if (sceneMapTexture.ZBufferSurface != null)
BaseGame.Device.DepthStencilBuffer = remBackBufferSurface;
//*/
} // RenderShadows(renderCode)
#endregion
#region ShowShadows
/// <summary>
/// Show shadows with help of our blur map shader.
/// We got 2 parts to fix the problem on the Xbox360 that we can't have
/// more than one rendertarget in parallel.
/// </summary>
public void ShowShadowsPart1()
{
return;
/*obs
// Only apply post screen blur if texture is valid and xnaEffect are valid
if (sceneMapTexture == null ||
Valid == false ||
// If the shadow scene map is not yet filled, there is no point
// continuing here ...
sceneMapTexture.XnaTexture == null)
return;
try
{
// Don't use or write to the z buffer
BaseGame.Device.RenderState.DepthBufferEnable = false;
BaseGame.Device.RenderState.DepthBufferWriteEnable = false;
// Disable alpha for the first pass
BaseGame.Device.RenderState.AlphaBlendEnable = false;
/*obs
// Make sure we use the default add mode for alpha blend operations,
// don't ask me why, but for some reason this is NOT the default
// on the Xbox360 and it cost me a freaking day to figure this out :(
BaseGame.Device.RenderState.AlphaBlendOperation = BlendFunction.Add;
// Make sure we clamp everything to 0-1
BaseGame.Device.SamplerStates[0].AddressU = TextureAddressMode.Clamp;
BaseGame.Device.SamplerStates[0].AddressV = TextureAddressMode.Clamp;
// Restore back buffer as render target
//not required: BaseGame.ResetRenderTarget(false);
*
if (windowSize != null)
windowSize.SetValue(
new float[] { sceneMapTexture.Width, sceneMapTexture.Height });
if (sceneMap != null)
sceneMap.SetValue(sceneMapTexture.XnaTexture);
xnaEffect.CurrentTechnique = xnaEffect.Techniques[
BaseGame.CanUsePS20 ? "ScreenAdvancedBlur20" : "ScreenAdvancedBlur"];
// We must have exactly 2 passes!
if (xnaEffect.CurrentTechnique.Passes.Count != 2)
throw new Exception("This shader should have exactly 2 passes!");
// Just start pass 0
blurMapTexture.SetRenderTarget();
RenderSinglePassShader(VBScreenHelper.Render);
/*obs
effect.Begin(SaveStateMode.None);
EffectPass effectPass = effect.CurrentTechnique.Passes[0];
effectPass.Begin();
VBScreenHelper.Render();
effectPass.End();
*
blurMapTexture.Resolve();
BaseGame.ResetRenderTarget(false);
/*obs
DepthStencilBuffer remBackBufferSurface = null;
xnaEffect.Begin(SaveStateMode.None);
for (int pass = 0; pass < xnaEffect.CurrentTechnique.Passes.Count; pass++)
{
/*#if XBOX360
// Just use 1 pass and render directly!
// Else Xbox360 will render black rectangles on top of our
// background, I really can't kill those (strange bug).
// Use ZeroSourceBlend alpha mode for the final result
BaseGame.Device.RenderState.AlphaBlendEnable = true;
BaseGame.Device.RenderState.AlphaBlendOperation = BlendFunction.Add;
BaseGame.Device.RenderState.SourceBlend = Blend.Zero;
BaseGame.Device.RenderState.DestinationBlend = Blend.SourceColor;
#else
*
if (pass == 0)
{
blurMapTexture.SetRenderTarget();
if (blurMapTexture.ZBufferSurface != null)
{
remBackBufferSurface = BaseGame.Device.DepthStencilBuffer;
BaseGame.Device.DepthStencilBuffer =
blurMapTexture.ZBufferSurface;
} // if (blurMapTexture.ZBufferSurface)
} // if
else
{
BaseGame.ResetRenderTarget(false);
if (blurMapTexture.ZBufferSurface != null)
BaseGame.Device.DepthStencilBuffer = remBackBufferSurface;
// Use ZeroSourceBlend alpha mode for the final result
BaseGame.Device.RenderState.AlphaBlendEnable = true;
BaseGame.Device.RenderState.AlphaBlendOperation = BlendFunction.Add;
BaseGame.Device.RenderState.SourceBlend = Blend.Zero;
BaseGame.Device.RenderState.DestinationBlend = Blend.SourceColor;
} // else
//#endif
EffectPass effectPass = xnaEffect.CurrentTechnique.Passes[pass];
effectPass.Begin();
VBScreenHelper.Render();
effectPass.End();
/*#if XBOX360
break;
#else
*
if (pass == 0)
{
blurMapTexture.Resolve();
if (blurMap != null)
blurMap.SetValue(blurMapTexture.XnaTexture);
xnaEffect.CommitChanges();
} // if
//#endif
} // for (pass, <, ++)
*
} // try
finally
{
//xnaEffect.End();
// Restore z buffer state
BaseGame.Device.RenderState.DepthBufferEnable = true;
BaseGame.Device.RenderState.DepthBufferWriteEnable = true;
// Set u/v addressing back to wrap
BaseGame.Device.SamplerStates[0].AddressU = TextureAddressMode.Wrap;
BaseGame.Device.SamplerStates[0].AddressV = TextureAddressMode.Wrap;
// Restore normal alpha blending
BaseGame.Device.RenderState.BlendFunction = BlendFunction.Add;
//BaseGame.AlphaMode = BaseGame.AlphaModes.Default;
} // finally
*/
} // ShowShadowsPart1()
/// <summary>
/// Show shadows with help of our blur map shader
/// </summary>
public void ShowShadowsPart2()
{
// Don't use or write to the z buffer
BaseGame.Device.RenderState.DepthBufferEnable = false;
BaseGame.Device.RenderState.DepthBufferWriteEnable = false;
// Make sure we clamp everything to 0-1
BaseGame.Device.SamplerStates[0].AddressU = TextureAddressMode.Clamp;
BaseGame.Device.SamplerStates[0].AddressV = TextureAddressMode.Clamp;
if (windowSize != null)
windowSize.SetValue(
new float[] { sceneMapTexture.Width, sceneMapTexture.Height });
if (sceneMap != null)
sceneMap.SetValue(sceneMapTexture.XnaTexture);
// Just use the simple blur, the advanced blur will cause too much throuble!
xnaEffect.CurrentTechnique = xnaEffect.Techniques["ScreenBlur"];
// Use ZeroSourceBlend alpha mode for the final result
BaseGame.Device.RenderState.AlphaBlendEnable = true;
BaseGame.Device.RenderState.AlphaBlendOperation = BlendFunction.Add;
BaseGame.Device.RenderState.SourceBlend = Blend.Zero;
BaseGame.Device.RenderState.DestinationBlend = Blend.SourceColor;
RenderSinglePassShader(VBScreenHelper.Render);
// Restore z buffer state
BaseGame.Device.RenderState.DepthBufferEnable = true;
BaseGame.Device.RenderState.DepthBufferWriteEnable = true;
// Set u/v addressing back to wrap
BaseGame.Device.SamplerStates[0].AddressU = TextureAddressMode.Wrap;
BaseGame.Device.SamplerStates[0].AddressV = TextureAddressMode.Wrap;
// Restore normal alpha blending
BaseGame.Device.RenderState.BlendFunction = BlendFunction.Add;
// Done!
return;
/*obs
// Only apply post screen blur if texture is valid and effect are valid
if (blurMapTexture == null ||
Valid == false ||
// If the shadow scene map is not yet filled, there is no point
// continuing here ...
blurMapTexture.XnaTexture == null)
return;
try
{
// Don't use or write to the z buffer
BaseGame.Device.RenderState.DepthBufferEnable = false;
BaseGame.Device.RenderState.DepthBufferWriteEnable = false;
// Make sure we clamp everything to 0-1
BaseGame.Device.SamplerStates[0].AddressU = TextureAddressMode.Clamp;
BaseGame.Device.SamplerStates[0].AddressV = TextureAddressMode.Clamp;
// Restore back buffer as render target
//not required: BaseGame.ResetRenderTarget(false);
if (blurMap != null)
blurMap.SetValue(blurMapTexture.XnaTexture);
xnaEffect.CurrentTechnique = xnaEffect.Techniques[
BaseGame.CanUsePS20 ? "ScreenAdvancedBlur20" : "ScreenAdvancedBlur"];
// We must have exactly 2 passes!
if (xnaEffect.CurrentTechnique.Passes.Count != 2)
throw new Exception("This shader should have exactly 2 passes!");
// Render second pass
xnaEffect.Begin(SaveStateMode.None);
// Use ZeroSourceBlend alpha mode for the final result
BaseGame.Device.RenderState.AlphaBlendEnable = true;
BaseGame.Device.RenderState.AlphaBlendOperation = BlendFunction.Add;
BaseGame.Device.RenderState.SourceBlend = Blend.Zero;
BaseGame.Device.RenderState.DestinationBlend = Blend.SourceColor;
EffectPass effectPass = xnaEffect.CurrentTechnique.Passes[1];
effectPass.Begin();
VBScreenHelper.Render();
effectPass.End();
} // try
finally
{
xnaEffect.End();
// Restore z buffer state
BaseGame.Device.RenderState.DepthBufferEnable = true;
BaseGame.Device.RenderState.DepthBufferWriteEnable = true;
// Set u/v addressing back to wrap
BaseGame.Device.SamplerStates[0].AddressU = TextureAddressMode.Wrap;
BaseGame.Device.SamplerStates[0].AddressV = TextureAddressMode.Wrap;
// Restore normal alpha blending
//BaseGame.Device.RenderState.BlendFunction = BlendFunction.Add;
//BaseGame.AlphaMode = BaseGame.AlphaModes.Default;
} // finally
*/
} // ShowShadows()
#endregion
} // class ShadowMapBlur
} // namespace DungeonQuest.Shaders
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using System.Collections;
using System.Collections.Generic;
namespace OpenSim.Region.Framework.Interfaces
{
/// <summary>
/// Interface to an entity's (SceneObjectPart's) inventory
/// </summary>
///
/// This is not a finished 1.0 candidate interface
public interface IEntityInventory
{
/// <summary>
/// Number of items in this inventory.
/// </summary>
int Count { get; }
/// <summary>
/// Add an item to this entity's inventory. If an item with the same name already exists, then an alternative
/// name is chosen.
/// </summary>
/// <param name="item"></param>
void AddInventoryItem(TaskInventoryItem item, bool allowedDrop);
/// <summary>
/// Add an item to this entity's inventory. If an item with the same name already exists, it is replaced.
/// </summary>
/// <param name="item"></param>
void AddInventoryItemExclusive(TaskInventoryItem item, bool allowedDrop);
void ApplyGodPermissions(uint perms);
void ApplyNextOwnerPermissions();
/// <summary>
/// Change every item in this inventory to a new group.
/// </summary>
/// <param name="groupID"></param>
void ChangeInventoryGroup(UUID groupID);
/// <summary>
/// Change every item in this inventory to a new owner.
/// </summary>
/// <param name="ownerId"></param>
void ChangeInventoryOwner(UUID ownerId);
/// <summary>
/// Returns true if this inventory contains any scripts
/// </summary></returns>
bool ContainsScripts();
/// <summary>
/// Start a script which is in this entity's inventory.
/// </summary>
/// <param name="item"></param>
/// <param name="postOnRez"></param>
/// <param name="engine"></param>
/// <param name="stateSource"></param>
/// <returns>
/// true if the script instance was valid for starting, false otherwise. This does not guarantee
/// that the script was actually started, just that the script was valid (i.e. its asset data could be found, etc.)
/// </returns>
bool CreateScriptInstance(
TaskInventoryItem item, int startParam, bool postOnRez, string engine, int stateSource);
/// <summary>
/// Start a script which is in this entity's inventory.
/// </summary>
/// <param name="itemId"></param>
/// <param name="startParam"></param>
/// <param name="postOnRez"></param>
/// <param name="engine"></param>
/// <param name="stateSource"></param>
/// <returns>
/// true if the script instance was valid for starting, false otherwise. This does not guarantee
/// that the script was actually started, just that the script was valid (i.e. its asset data could be found, etc.)
/// </returns>
bool CreateScriptInstance(UUID itemId, int startParam, bool postOnRez, string engine, int stateSource);
/// <summary>
/// Start all the scripts contained in this entity's inventory
/// </summary>
/// <param name="startParam"></param>
/// <param name="postOnRez"></param>
/// <param name="engine"></param>
/// <param name="stateSource"></param>
/// <returns>Number of scripts started.</returns>
int CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource);
/// <summary>
/// Force the task inventory of this prim to persist at the next update sweep
/// </summary>
void ForceInventoryPersistence();
/// <summary>
/// Returns an existing inventory item. Returns the original, so any changes will be live.
/// </summary>
/// <param name="itemID"></param>
/// <returns>null if the item does not exist</returns>
TaskInventoryItem GetInventoryItem(UUID itemId);
/// <summary>
/// Gets an inventory item by name
/// </summary>
/// <remarks>
/// This method returns the first inventory item that matches the given name. In SL this is all you need
/// since each item in a prim inventory must have a unique name.
/// </remarks>
/// <param name='name'></param>
/// <returns>
/// The inventory item. Null if no such item was found.
/// </returns>
TaskInventoryItem GetInventoryItem(string name);
/// <summary>
/// Get all inventory items.
/// </summary>
/// <param name="name"></param>
/// <returns>
/// If there are no inventory items then an empty list is returned.
/// </returns>
List<TaskInventoryItem> GetInventoryItems();
/// <summary>
/// Get inventory items by name.
/// </summary>
/// <param name="name"></param>
/// <returns>
/// A list of inventory items with that name.
/// If no inventory item has that name then an empty list is returned.
/// </returns>
List<TaskInventoryItem> GetInventoryItems(string name);
/// <summary>
/// Get inventory items by type.
/// </summary>
/// <param type="name"></param>
/// <returns>
/// A list of inventory items of that type.
/// If no inventory items of that type then an empty list is returned.
/// </returns>
List<TaskInventoryItem> GetInventoryItems(InventoryType type);
/// <summary>
/// Get the uuids of all items in this inventory
/// </summary>
/// <returns></returns>
List<UUID> GetInventoryList();
/// <summary>
/// Get the scene object(s) referenced by an inventory item.
/// </summary>
///
/// This is returned in a 'rez ready' state. That is, name, description, permissions and other details have
/// been adjusted to reflect the part and item from which it originates.
///
/// <param name="item">Inventory item</param>
/// <param name="objlist">The scene objects</param>
/// <param name="veclist">Relative offsets for each object</param>
/// <returns>true = success, false = the scene object asset couldn't be found</returns>
bool GetRezReadySceneObjects(TaskInventoryItem item, out List<SceneObjectGroup> objlist, out List<Vector3> veclist);
ArrayList GetScriptErrors(UUID itemID);
/// <summary>
/// Get the xml representing the saved states of scripts in this inventory.
/// </summary>
/// <returns>
/// A <see cref="Dictionary`2"/>
/// </returns>
Dictionary<UUID, string> GetScriptStates();
uint MaskEffectivePermissions();
/// <summary>
/// Backup the inventory to the given data store
/// </summary>
/// <param name="datastore"></param>
void ProcessInventoryBackup(ISimulationDataService datastore);
/// <summary>
/// Remove an item from this entity's inventory
/// </summary>
/// <param name="itemID"></param>
/// <returns>Numeric asset type of the item removed. Returns -1 if the item did not exist
/// in this prim's inventory.</returns>
int RemoveInventoryItem(UUID itemID);
/// <summary>
/// Stop and remove a script which is in this prim's inventory from the scene.
/// </summary>
/// <param name="itemId"></param>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if these scripts are being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
void RemoveScriptInstance(UUID itemId, bool sceneObjectBeingDeleted);
/// <summary>
/// Stop and remove all the scripts in this entity from the scene.
/// </summary>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if these scripts are being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
void RemoveScriptInstances(bool sceneObjectBeingDeleted);
/// <summary>
/// Serialize all the metadata for the items in this prim's inventory ready for sending to the client
/// </summary>
/// <param name="xferManager"></param>
void RequestInventoryFile(IClientAPI client, IXfer xferManager);
/// <summary>
/// Reset UUIDs for all the items in the prim's inventory.
/// </summary>
///
/// This involves either generating
/// new ones or setting existing UUIDs to the correct parent UUIDs.
///
/// If this method is called and there are inventory items, then we regard the inventory as having changed.
///
/// <param name="linkNum">Link number for the part</param>
void ResetInventoryIDs();
/// <summary>
/// Reset parent object UUID for all the items in the prim's inventory.
/// </summary>
///
/// If this method is called and there are inventory items, then we regard the inventory as having changed.
///
/// <param name="linkNum">Link number for the part</param>
void ResetObjectID();
/// <summary>
/// Restore a whole collection of items to the entity's inventory at once.
/// We assume that the items already have all their fields correctly filled out.
/// The items are not flagged for persistence to the database, since they are being restored
/// from persistence rather than being newly added.
/// </summary>
/// <param name="items"></param>
void RestoreInventoryItems(ICollection<TaskInventoryItem> items);
void ResumeScripts();
/// <summary>
/// Number of running scripts in this inventory.
/// </summary></returns>
int RunningScriptCount();
/// <summary>
/// Number of scripts in this inventory.
/// </summary>
/// <remarks>
/// Includes both running and non running scripts.
/// </remarks>
int ScriptCount();
/// <summary>
/// Stop a script which is in this prim's inventory.
/// </summary>
/// <param name="itemId"></param>
void StopScriptInstance(UUID itemId);
/// <summary>
/// Stop all the scripts in this entity.
/// </summary>
void StopScriptInstances();
/// <summary>
/// Try to get the script running status.
/// </summary>
/// <returns>
/// Returns true if a script for the item was found in one of the simulator's script engines. In this case,
/// the running parameter will reflect the running status.
/// Returns false if the item could not be found, if the item is not a script or if a script instance for the
/// item was not found in any of the script engines. In this case, running status is irrelevant.
/// </returns>
/// <param name='itemId'></param>
/// <param name='running'></param>
bool TryGetScriptInstanceRunning(UUID itemId, out bool running);
/// <summary>
/// Update an existing inventory item.
/// </summary>
/// <param name="item">The updated item. An item with the same id must already exist
/// in this prim's inventory.</param>
/// <returns>false if the item did not exist, true if the update occurred successfully</returns>
bool UpdateInventoryItem(TaskInventoryItem item);
bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents);
bool UpdateInventoryItem(TaskInventoryItem item, bool fireScriptEvents, bool considerChanged);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace iTalk.API.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/pricing/override_price_schedule.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Booking.Pricing {
/// <summary>Holder for reflection information generated from booking/pricing/override_price_schedule.proto</summary>
public static partial class OverridePriceScheduleReflection {
#region Descriptor
/// <summary>File descriptor for booking/pricing/override_price_schedule.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static OverridePriceScheduleReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ci1ib29raW5nL3ByaWNpbmcvb3ZlcnJpZGVfcHJpY2Vfc2NoZWR1bGUucHJv",
"dG8SG2hvbG1zLnR5cGVzLmJvb2tpbmcucHJpY2luZxouYm9va2luZy9pbmRp",
"Y2F0b3JzL3Jlc2VydmF0aW9uX2luZGljYXRvci5wcm90bxohYm9va2luZy9w",
"cmljaW5nL3ByaWNlX25pZ2h0LnByb3RvGh1wcmltaXRpdmUvcGJfbG9jYWxf",
"ZGF0ZS5wcm90byK0AgoVT3ZlcnJpZGVQcmljZVNjaGVkdWxlEkkKC3Jlc2Vy",
"dmF0aW9uGAEgASgLMjQuaG9sbXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3Jz",
"LlJlc2VydmF0aW9uSW5kaWNhdG9yEkYKFXByaWNlc193aXRoX292ZXJyaWRl",
"cxgCIAMoCzInLmhvbG1zLnR5cGVzLmJvb2tpbmcucHJpY2luZy5QcmljZU5p",
"Z2h0EkkKGHByaWNlc193aXRob3V0X292ZXJyaWRlcxgDIAMoCzInLmhvbG1z",
"LnR5cGVzLmJvb2tpbmcucHJpY2luZy5QcmljZU5pZ2h0Ej0KEW92ZXJyaWRk",
"ZW5fbmlnaHRzGAQgAygLMiIuaG9sbXMudHlwZXMucHJpbWl0aXZlLlBiTG9j",
"YWxEYXRlQi9aD2Jvb2tpbmcvcHJpY2luZ6oCG0hPTE1TLlR5cGVzLkJvb2tp",
"bmcuUHJpY2luZ2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Pricing.PriceNightReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Pricing.OverridePriceSchedule), global::HOLMS.Types.Booking.Pricing.OverridePriceSchedule.Parser, new[]{ "Reservation", "PricesWithOverrides", "PricesWithoutOverrides", "OverriddenNights" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class OverridePriceSchedule : pb::IMessage<OverridePriceSchedule> {
private static readonly pb::MessageParser<OverridePriceSchedule> _parser = new pb::MessageParser<OverridePriceSchedule>(() => new OverridePriceSchedule());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<OverridePriceSchedule> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.Pricing.OverridePriceScheduleReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OverridePriceSchedule() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OverridePriceSchedule(OverridePriceSchedule other) : this() {
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
pricesWithOverrides_ = other.pricesWithOverrides_.Clone();
pricesWithoutOverrides_ = other.pricesWithoutOverrides_.Clone();
overriddenNights_ = other.overriddenNights_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public OverridePriceSchedule Clone() {
return new OverridePriceSchedule(this);
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 1;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "prices_with_overrides" field.</summary>
public const int PricesWithOverridesFieldNumber = 2;
private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.Pricing.PriceNight> _repeated_pricesWithOverrides_codec
= pb::FieldCodec.ForMessage(18, global::HOLMS.Types.Booking.Pricing.PriceNight.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.Pricing.PriceNight> pricesWithOverrides_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.Pricing.PriceNight>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Booking.Pricing.PriceNight> PricesWithOverrides {
get { return pricesWithOverrides_; }
}
/// <summary>Field number for the "prices_without_overrides" field.</summary>
public const int PricesWithoutOverridesFieldNumber = 3;
private static readonly pb::FieldCodec<global::HOLMS.Types.Booking.Pricing.PriceNight> _repeated_pricesWithoutOverrides_codec
= pb::FieldCodec.ForMessage(26, global::HOLMS.Types.Booking.Pricing.PriceNight.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Booking.Pricing.PriceNight> pricesWithoutOverrides_ = new pbc::RepeatedField<global::HOLMS.Types.Booking.Pricing.PriceNight>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Booking.Pricing.PriceNight> PricesWithoutOverrides {
get { return pricesWithoutOverrides_; }
}
/// <summary>Field number for the "overridden_nights" field.</summary>
public const int OverriddenNightsFieldNumber = 4;
private static readonly pb::FieldCodec<global::HOLMS.Types.Primitive.PbLocalDate> _repeated_overriddenNights_codec
= pb::FieldCodec.ForMessage(34, global::HOLMS.Types.Primitive.PbLocalDate.Parser);
private readonly pbc::RepeatedField<global::HOLMS.Types.Primitive.PbLocalDate> overriddenNights_ = new pbc::RepeatedField<global::HOLMS.Types.Primitive.PbLocalDate>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::HOLMS.Types.Primitive.PbLocalDate> OverriddenNights {
get { return overriddenNights_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as OverridePriceSchedule);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(OverridePriceSchedule other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Reservation, other.Reservation)) return false;
if(!pricesWithOverrides_.Equals(other.pricesWithOverrides_)) return false;
if(!pricesWithoutOverrides_.Equals(other.pricesWithoutOverrides_)) return false;
if(!overriddenNights_.Equals(other.overriddenNights_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (reservation_ != null) hash ^= Reservation.GetHashCode();
hash ^= pricesWithOverrides_.GetHashCode();
hash ^= pricesWithoutOverrides_.GetHashCode();
hash ^= overriddenNights_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (reservation_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Reservation);
}
pricesWithOverrides_.WriteTo(output, _repeated_pricesWithOverrides_codec);
pricesWithoutOverrides_.WriteTo(output, _repeated_pricesWithoutOverrides_codec);
overriddenNights_.WriteTo(output, _repeated_overriddenNights_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
size += pricesWithOverrides_.CalculateSize(_repeated_pricesWithOverrides_codec);
size += pricesWithoutOverrides_.CalculateSize(_repeated_pricesWithoutOverrides_codec);
size += overriddenNights_.CalculateSize(_repeated_overriddenNights_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(OverridePriceSchedule other) {
if (other == null) {
return;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
pricesWithOverrides_.Add(other.pricesWithOverrides_);
pricesWithoutOverrides_.Add(other.pricesWithoutOverrides_);
overriddenNights_.Add(other.overriddenNights_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 18: {
pricesWithOverrides_.AddEntriesFrom(input, _repeated_pricesWithOverrides_codec);
break;
}
case 26: {
pricesWithoutOverrides_.AddEntriesFrom(input, _repeated_pricesWithoutOverrides_codec);
break;
}
case 34: {
overriddenNights_.AddEntriesFrom(input, _repeated_overriddenNights_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Aurora.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace Aurora.Modules.OnDemand
{
/// <summary>
/// Some notes on this module, this module just modifies when/where the startup code is executed
/// This module has a few different settings for the region to startup with,
/// Soft, Medium, and Normal (no change)
///
/// -- Soft --
/// Disables the heartbeats (not scripts, as its instance-wide)
/// Only loads land and parcels, no prims
///
/// -- Medium --
/// Same as Soft, except it loads prims (same as normal, but no threads)
///
/// -- Normal --
/// Same as always
/// </summary>
public class OnDemandRegionModule : INonSharedRegionModule
{
#region Declares
private readonly List<UUID> m_zombieAgents = new List<UUID>();
private bool m_isRunning;
private bool m_isShuttingDown;
private bool m_isStartingUp;
private IScene m_scene;
private int m_waitTime=0;
#endregion
#region INonSharedRegionModule Members
public void Initialise(IConfigSource source)
{
}
public void AddRegion(IScene scene)
{
if (scene.RegionInfo.Startup != StartupType.Normal)
{
m_scene = scene;
//Disable the heartbeat for this region
scene.ShouldRunHeartbeat = false;
scene.EventManager.OnRemovePresence += OnRemovePresence;
scene.AuroraEventManager.RegisterEventHandler("NewUserConnection", OnGenericEvent);
scene.AuroraEventManager.RegisterEventHandler("AgentIsAZombie", OnGenericEvent);
}
}
public void RegionLoaded(IScene scene)
{
}
public void RemoveRegion(IScene scene)
{
}
public void Close()
{
}
public string Name
{
get { return "OnDemandRegionModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
#region Private Events
private object OnGenericEvent(string FunctionName, object parameters)
{
if (FunctionName == "NewUserConnection")
{
if (!m_isRunning)
{
m_isRunning = true;
object[] obj = (object[]) parameters;
OSDMap responseMap = (OSDMap) obj[0];
//Tell the caller that we will have to wait a bit possibly
responseMap["WaitTime"] = m_waitTime;
if (m_scene.RegionInfo.Startup == StartupType.Medium)
{
m_scene.AuroraEventManager.FireGenericEventHandler("MediumStartup", m_scene);
MediumStartup();
}
}
}
else if (FunctionName == "AgentIsAZombie")
m_zombieAgents.Add((UUID) parameters);
return null;
}
private void OnRemovePresence(IScenePresence presence)
{
if (m_scene.GetScenePresences().Count == 1) //This presence hasn't been removed yet, so we check against one
{
if (m_zombieAgents.Contains(presence.UUID))
{
m_zombieAgents.Remove(presence.UUID);
return; //It'll be readding an agent, don't kill the sim immediately
}
//If all clients are out of the region, we can close it again
if (m_scene.RegionInfo.Startup == StartupType.Medium)
{
m_scene.AuroraEventManager.FireGenericEventHandler("MediumShutdown", m_scene);
MediumShutdown();
}
m_isRunning = false;
}
}
#endregion
#region Private Shutdown Methods
private void MediumShutdown()
{
//Only shut down one at a time
if (m_isShuttingDown)
return;
m_isShuttingDown = true;
GenericShutdown();
m_isShuttingDown = false;
}
/// <summary>
/// This shuts down the heartbeats so that everything is dead again
/// </summary>
private void GenericShutdown()
{
//After the next iteration, the threads will kill themselves
m_scene.ShouldRunHeartbeat = false;
}
#endregion
#region Private Startup Methods
/// <summary>
/// We've already loaded prims/parcels/land earlier,
/// we don't have anything else to load,
/// so we just need to get the heartbeats back on track
/// </summary>
private void MediumStartup()
{
//Only start up one at a time
if (m_isStartingUp)
return;
m_isStartingUp = true;
GenericStartup();
m_isStartingUp = false;
}
/// <summary>
/// This sets up the heartbeats so that they are running again, which is needed
/// </summary>
private void GenericStartup()
{
m_scene.ShouldRunHeartbeat = true;
m_scene.StartHeartbeat();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Runtime.ConsistentRing;
using Orleans.Runtime.Counters;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.LogConsistency;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.MultiClusterNetwork;
using Orleans.Runtime.Providers;
using Orleans.Runtime.ReminderService;
using Orleans.Runtime.Scheduler;
using Orleans.Services;
using Orleans.Streams;
using Orleans.Transactions;
using Orleans.Runtime.Versions;
using Orleans.Versions;
using Orleans.ApplicationParts;
using Orleans.Configuration;
using Orleans.Serialization;
namespace Orleans.Runtime
{
/// <summary>
/// Orleans silo.
/// </summary>
public class Silo
{
/// <summary> Standard name for Primary silo. </summary>
public const string PrimarySiloName = "Primary";
/// <summary> Silo Types. </summary>
public enum SiloType
{
/// <summary> No silo type specified. </summary>
None = 0,
/// <summary> Primary silo. </summary>
Primary,
/// <summary> Secondary silo. </summary>
Secondary,
}
private readonly ILocalSiloDetails siloDetails;
private readonly ClusterOptions clusterOptions;
private readonly ISiloMessageCenter messageCenter;
private readonly OrleansTaskScheduler scheduler;
private readonly LocalGrainDirectory localGrainDirectory;
private readonly ActivationDirectory activationDirectory;
private readonly IncomingMessageAgent incomingAgent;
private readonly IncomingMessageAgent incomingSystemAgent;
private readonly IncomingMessageAgent incomingPingAgent;
private readonly ILogger logger;
private TypeManager typeManager;
private readonly TaskCompletionSource<int> siloTerminatedTask =
new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly SiloStatisticsManager siloStatistics;
private readonly InsideRuntimeClient runtimeClient;
private IReminderService reminderService;
private SystemTarget fallbackScheduler;
private readonly IMembershipOracle membershipOracle;
private readonly IMultiClusterOracle multiClusterOracle;
private readonly ExecutorService executorService;
private Watchdog platformWatchdog;
private readonly TimeSpan initTimeout;
private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1);
private readonly Catalog catalog;
private readonly List<IHealthCheckParticipant> healthCheckParticipants = new List<IHealthCheckParticipant>();
private readonly object lockable = new object();
private readonly GrainFactory grainFactory;
private readonly ISiloLifecycleSubject siloLifecycle;
private List<GrainService> grainServices = new List<GrainService>();
private readonly ILoggerFactory loggerFactory;
/// <summary>
/// Gets the type of this
/// </summary>
internal string Name => this.siloDetails.Name;
internal OrleansTaskScheduler LocalScheduler { get { return scheduler; } }
internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } }
internal IMultiClusterOracle LocalMultiClusterOracle { get { return multiClusterOracle; } }
internal IConsistentRingProvider RingProvider { get; private set; }
internal ICatalog Catalog => catalog;
internal SystemStatus SystemStatus { get; set; }
internal IServiceProvider Services { get; }
/// <summary> SiloAddress for this silo. </summary>
public SiloAddress SiloAddress => this.siloDetails.SiloAddress;
/// <summary>
/// Silo termination event used to signal shutdown of this silo.
/// </summary>
public WaitHandle SiloTerminatedEvent // one event for all types of termination (shutdown, stop and fast kill).
=> ((IAsyncResult)this.siloTerminatedTask.Task).AsyncWaitHandle;
public Task SiloTerminated { get { return this.siloTerminatedTask.Task; } } // one event for all types of termination (shutdown, stop and fast kill).
private SchedulingContext membershipOracleContext;
private SchedulingContext multiClusterOracleContext;
private SchedulingContext reminderServiceContext;
private LifecycleSchedulingSystemTarget lifecycleSchedulingSystemTarget;
/// <summary>
/// Initializes a new instance of the <see cref="Silo"/> class.
/// </summary>
/// <param name="siloDetails">The silo initialization parameters</param>
/// <param name="services">Dependency Injection container</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")]
public Silo(ILocalSiloDetails siloDetails, IServiceProvider services)
{
string name = siloDetails.Name;
// Temporarily still require this. Hopefuly gone when 2.0 is released.
this.siloDetails = siloDetails;
this.SystemStatus = SystemStatus.Creating;
AsynchAgent.IsStarting = true;
var startTime = DateTime.UtcNow;
IOptions<SiloStatisticsOptions> statisticsOptions = services.GetRequiredService<IOptions<SiloStatisticsOptions>>();
StatisticsCollector.Initialize(statisticsOptions.Value.CollectionLevel);
IOptions<ClusterMembershipOptions> clusterMembershipOptions = services.GetRequiredService<IOptions<ClusterMembershipOptions>>();
initTimeout = clusterMembershipOptions.Value.MaxJoinAttemptTime;
if (Debugger.IsAttached)
{
initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), clusterMembershipOptions.Value.MaxJoinAttemptTime);
stopTimeout = initTimeout;
}
var localEndpoint = this.siloDetails.SiloAddress.Endpoint;
services.GetService<SerializationManager>().RegisterSerializers(services.GetService<IApplicationPartManager>());
this.Services = services;
this.Services.InitializeSiloUnobservedExceptionsHandler();
//set PropagateActivityId flag from node config
IOptions<SiloMessagingOptions> messagingOptions = services.GetRequiredService<IOptions<SiloMessagingOptions>>();
RequestContext.PropagateActivityId = messagingOptions.Value.PropagateActivityId;
this.loggerFactory = this.Services.GetRequiredService<ILoggerFactory>();
logger = this.loggerFactory.CreateLogger<Silo>();
logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode));
if (!GCSettings.IsServerGC)
{
logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\">");
logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines).");
}
logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing silo on host {0} MachineName {1} at {2}, gen {3} --------------",
this.siloDetails.DnsHostName, Environment.MachineName, localEndpoint, this.siloDetails.SiloAddress.Generation);
logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0}", name);
var siloMessagingOptions = this.Services.GetRequiredService<IOptions<SiloMessagingOptions>>();
BufferPool.InitGlobalBufferPool(siloMessagingOptions.Value);
try
{
grainFactory = Services.GetRequiredService<GrainFactory>();
}
catch (InvalidOperationException exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc);
throw;
}
// Performance metrics
siloStatistics = Services.GetRequiredService<SiloStatisticsManager>();
// The scheduler
scheduler = Services.GetRequiredService<OrleansTaskScheduler>();
healthCheckParticipants.Add(scheduler);
runtimeClient = Services.GetRequiredService<InsideRuntimeClient>();
// Initialize the message center
messageCenter = Services.GetRequiredService<MessageCenter>();
var dispatcher = this.Services.GetRequiredService<Dispatcher>();
messageCenter.RerouteHandler = dispatcher.RerouteMessage;
messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage;
// Now the router/directory service
// This has to come after the message center //; note that it then gets injected back into the message center.;
localGrainDirectory = Services.GetRequiredService<LocalGrainDirectory>();
// Now the activation directory.
activationDirectory = Services.GetRequiredService<ActivationDirectory>();
// Now the consistent ring provider
RingProvider = Services.GetRequiredService<IConsistentRingProvider>();
catalog = Services.GetRequiredService<Catalog>();
executorService = Services.GetRequiredService<ExecutorService>();
// Now the incoming message agents
var messageFactory = this.Services.GetRequiredService<MessageFactory>();
incomingSystemAgent = new IncomingMessageAgent(Message.Categories.System, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory);
incomingPingAgent = new IncomingMessageAgent(Message.Categories.Ping, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory);
incomingAgent = new IncomingMessageAgent(Message.Categories.Application, messageCenter, activationDirectory, scheduler, catalog.Dispatcher, messageFactory, executorService, this.loggerFactory);
membershipOracle = Services.GetRequiredService<IMembershipOracle>();
this.clusterOptions = Services.GetRequiredService<IOptions<ClusterOptions>>().Value;
var multiClusterOptions = Services.GetRequiredService<IOptions<MultiClusterOptions>>().Value;
if (!multiClusterOptions.HasMultiClusterNetwork)
{
logger.Info("Skip multicluster oracle creation (no multicluster network configured)");
}
else
{
multiClusterOracle = Services.GetRequiredService<IMultiClusterOracle>();
}
this.SystemStatus = SystemStatus.Created;
AsynchAgent.IsStarting = false;
StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME,
() => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs.
this.siloLifecycle = this.Services.GetRequiredService<ISiloLifecycleSubject>();
// register all lifecycle participants
IEnumerable<ILifecycleParticipant<ISiloLifecycle>> lifecycleParticipants = this.Services.GetServices<ILifecycleParticipant<ISiloLifecycle>>();
foreach(ILifecycleParticipant<ISiloLifecycle> participant in lifecycleParticipants)
{
participant?.Participate(this.siloLifecycle);
}
// register all named lifecycle participants
IKeyedServiceCollection<string, ILifecycleParticipant<ISiloLifecycle>> namedLifecycleParticipantCollection = this.Services.GetService<IKeyedServiceCollection<string,ILifecycleParticipant<ISiloLifecycle>>>();
foreach (ILifecycleParticipant<ISiloLifecycle> participant in namedLifecycleParticipantCollection
?.GetServices(this.Services)
?.Select(s => s.GetService(this.Services)))
{
participant?.Participate(this.siloLifecycle);
}
// add self to lifecycle
this.Participate(this.siloLifecycle);
logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode());
}
public void Start()
{
StartAsync(CancellationToken.None).GetAwaiter().GetResult();
}
public async Task StartAsync(CancellationToken cancellationToken)
{
StartTaskWithPerfAnalysis("Start Scheduler", scheduler.Start, new Stopwatch());
// SystemTarget for provider init calls
this.lifecycleSchedulingSystemTarget = Services.GetRequiredService<LifecycleSchedulingSystemTarget>();
this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>();
RegisterSystemTarget(lifecycleSchedulingSystemTarget);
try
{
await this.scheduler.QueueTask(() => this.siloLifecycle.OnStart(cancellationToken), this.lifecycleSchedulingSystemTarget.SchedulingContext);
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc);
throw;
}
}
private void CreateSystemTargets()
{
logger.Debug("Creating System Targets for this silo.");
logger.Debug("Creating {0} System Target", "SiloControl");
var siloControl = ActivatorUtilities.CreateInstance<SiloControl>(Services);
RegisterSystemTarget(siloControl);
logger.Debug("Creating {0} System Target", "ProtocolGateway");
RegisterSystemTarget(new ProtocolGateway(this.SiloAddress, this.loggerFactory));
logger.Debug("Creating {0} System Target", "DeploymentLoadPublisher");
RegisterSystemTarget(Services.GetRequiredService<DeploymentLoadPublisher>());
logger.Debug("Creating {0} System Target", "RemoteGrainDirectory + CacheValidator");
RegisterSystemTarget(LocalGrainDirectory.RemoteGrainDirectory);
RegisterSystemTarget(LocalGrainDirectory.CacheValidator);
logger.Debug("Creating {0} System Target", "RemoteClusterGrainDirectory");
RegisterSystemTarget(LocalGrainDirectory.RemoteClusterGrainDirectory);
logger.Debug("Creating {0} System Target", "ClientObserverRegistrar + TypeManager");
this.RegisterSystemTarget(this.Services.GetRequiredService<ClientObserverRegistrar>());
var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>();
var versionDirectorManager = this.Services.GetRequiredService<CachedVersionSelectorManager>();
var grainTypeManager = this.Services.GetRequiredService<GrainTypeManager>();
IOptions<TypeManagementOptions> typeManagementOptions = this.Services.GetRequiredService<IOptions<TypeManagementOptions>>();
typeManager = new TypeManager(SiloAddress, grainTypeManager, membershipOracle, LocalScheduler, typeManagementOptions.Value.TypeMapRefreshInterval, implicitStreamSubscriberTable, this.grainFactory, versionDirectorManager,
this.loggerFactory);
this.RegisterSystemTarget(typeManager);
logger.Debug("Creating {0} System Target", "MembershipOracle");
if (this.membershipOracle is SystemTarget)
{
RegisterSystemTarget((SystemTarget)membershipOracle);
}
if (multiClusterOracle != null && multiClusterOracle is SystemTarget)
{
logger.Debug("Creating {0} System Target", "MultiClusterOracle");
RegisterSystemTarget((SystemTarget)multiClusterOracle);
}
var transactionAgent = this.Services.GetRequiredService<ITransactionAgent>() as SystemTarget;
if (transactionAgent != null)
{
logger.Debug("Creating {0} System Target", "TransactionAgent");
RegisterSystemTarget(transactionAgent);
}
logger.Debug("Finished creating System Targets for this silo.");
}
private async Task InjectDependencies()
{
healthCheckParticipants.Add(membershipOracle);
catalog.SiloStatusOracle = this.membershipOracle;
this.membershipOracle.SubscribeToSiloStatusEvents(localGrainDirectory);
messageCenter.SiloDeadOracle = this.membershipOracle.IsDeadSilo;
// consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here
this.membershipOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider);
this.membershipOracle.SubscribeToSiloStatusEvents(typeManager);
this.membershipOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<DeploymentLoadPublisher>());
this.membershipOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<ClientObserverRegistrar>());
var reminderTable = Services.GetService<IReminderTable>();
if (reminderTable != null)
{
logger.Info($"Creating reminder grain service for type={reminderTable.GetType()}");
// Start the reminder service system target
reminderService = new LocalReminderService(this, reminderTable, this.initTimeout, this.loggerFactory); ;
RegisterSystemTarget((SystemTarget)reminderService);
}
RegisterSystemTarget(catalog);
await scheduler.QueueAction(catalog.Start, catalog.SchedulingContext)
.WithTimeout(initTimeout, $"Starting Catalog failed due to timeout {initTimeout}");
// SystemTarget for provider init calls
this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>();
RegisterSystemTarget(fallbackScheduler);
}
private Task OnRuntimeInitializeStart(CancellationToken ct)
{
lock (lockable)
{
if (!this.SystemStatus.Equals(SystemStatus.Created))
throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", this.SystemStatus));
this.SystemStatus = SystemStatus.Starting;
}
logger.Info(ErrorCode.SiloStarting, "Silo Start()");
var processExitHandlingOptions = this.Services.GetService<IOptions<ProcessExitHandlingOptions>>().Value;
if(processExitHandlingOptions.FastKillOnProcessExit)
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
//TODO: setup thead pool directly to lifecycle
StartTaskWithPerfAnalysis("ConfigureThreadPoolAndServicePointSettings",
this.ConfigureThreadPoolAndServicePointSettings, Stopwatch.StartNew());
return Task.CompletedTask;
}
private void StartTaskWithPerfAnalysis(string taskName, Action task, Stopwatch stopWatch)
{
stopWatch.Restart();
task.Invoke();
stopWatch.Stop();
this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish");
}
private async Task StartAsyncTaskWithPerfAnalysis(string taskName, Func<Task> task, Stopwatch stopWatch)
{
stopWatch.Restart();
await task.Invoke();
stopWatch.Stop();
this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish");
}
private async Task OnRuntimeServicesStart(CancellationToken ct)
{
//TODO: Setup all (or as many as possible) of the class started in this call to work directly with lifecyce
var stopWatch = Stopwatch.StartNew();
// The order of these 4 is pretty much arbitrary.
StartTaskWithPerfAnalysis("Start Message center",messageCenter.Start,stopWatch);
StartTaskWithPerfAnalysis("Start Incoming message agents", IncomingMessageAgentsStart, stopWatch);
void IncomingMessageAgentsStart()
{
incomingPingAgent.Start();
incomingSystemAgent.Start();
incomingAgent.Start();
}
StartTaskWithPerfAnalysis("Start local grain directory", LocalGrainDirectory.Start,stopWatch);
// Set up an execution context for this thread so that the target creation steps can use asynch values.
RuntimeContext.InitializeMainThread();
StartTaskWithPerfAnalysis("Init implicit stream subscribe table", InitImplicitStreamSubscribeTable, stopWatch);
void InitImplicitStreamSubscribeTable()
{
// Initialize the implicit stream subscribers table.
var implicitStreamSubscriberTable = Services.GetRequiredService<ImplicitStreamSubscriberTable>();
var grainTypeManager = Services.GetRequiredService<GrainTypeManager>();
implicitStreamSubscriberTable.InitImplicitStreamSubscribers(grainTypeManager.GrainClassTypeData.Select(t => t.Value.Type).ToArray());
}
this.runtimeClient.CurrentStreamProviderRuntime = this.Services.GetRequiredService<SiloProviderRuntime>();
// This has to follow the above steps that start the runtime components
await StartAsyncTaskWithPerfAnalysis("Create system targets and inject dependencies", () =>
{
CreateSystemTargets();
return InjectDependencies();
}, stopWatch);
// Validate the configuration.
// TODO - refactor validation - jbragg
//GlobalConfig.Application.ValidateConfiguration(logger);
}
private async Task OnRuntimeGrainServicesStart(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
await StartAsyncTaskWithPerfAnalysis("Init transaction agent", InitTransactionAgent, stopWatch);
async Task InitTransactionAgent()
{
ITransactionAgent transactionAgent = this.Services.GetRequiredService<ITransactionAgent>();
ISchedulingContext transactionAgentContext = (transactionAgent as SystemTarget)?.SchedulingContext;
await scheduler.QueueTask(transactionAgent.Start, transactionAgentContext)
.WithTimeout(initTimeout, $"Starting TransactionAgent failed due to timeout {initTimeout}");
}
// Load and init grain services before silo becomes active.
await StartAsyncTaskWithPerfAnalysis("Init grain services",
() => CreateGrainServices(), stopWatch);
this.membershipOracleContext = (this.membershipOracle as SystemTarget)?.SchedulingContext ??
this.fallbackScheduler.SchedulingContext;
await StartAsyncTaskWithPerfAnalysis("Starting local silo status oracle", StartMembershipOracle, stopWatch);
async Task StartMembershipOracle()
{
await scheduler.QueueTask(() => this.membershipOracle.Start(), this.membershipOracleContext)
.WithTimeout(initTimeout, $"Starting MembershipOracle failed due to timeout {initTimeout}");
logger.Debug("Local silo status oracle created successfully.");
}
var versionStore = Services.GetService<IVersionStore>();
await StartAsyncTaskWithPerfAnalysis("Init type manager", () => scheduler
.QueueTask(() => this.typeManager.Initialize(versionStore), this.typeManager.SchedulingContext)
.WithTimeout(this.initTimeout, $"TypeManager Initializing failed due to timeout {initTimeout}"), stopWatch);
//if running in multi cluster scenario, start the MultiClusterNetwork Oracle
if (this.multiClusterOracle != null)
{
await StartAsyncTaskWithPerfAnalysis("Start multicluster oracle", StartMultiClusterOracle, stopWatch);
async Task StartMultiClusterOracle()
{
logger.Info("Starting multicluster oracle with my ServiceId={0} and ClusterId={1}.",
this.clusterOptions.ServiceId, this.clusterOptions.ClusterId);
this.multiClusterOracleContext = (multiClusterOracle as SystemTarget)?.SchedulingContext ??
this.fallbackScheduler.SchedulingContext;
await scheduler.QueueTask(() => multiClusterOracle.Start(), multiClusterOracleContext)
.WithTimeout(initTimeout, $"Starting MultiClusterOracle failed due to timeout {initTimeout}");
logger.Debug("multicluster oracle created successfully.");
}
}
try
{
SiloStatisticsOptions statisticsOptions = Services.GetRequiredService<IOptions<SiloStatisticsOptions>>().Value;
StartTaskWithPerfAnalysis("Start silo statistics", () => this.siloStatistics.Start(statisticsOptions), stopWatch);
logger.Debug("Silo statistics manager started successfully.");
// Finally, initialize the deployment load collector, for grains with load-based placement
await StartAsyncTaskWithPerfAnalysis("Start deployment load collector", StartDeploymentLoadCollector, stopWatch);
async Task StartDeploymentLoadCollector()
{
var deploymentLoadPublisher = Services.GetRequiredService<DeploymentLoadPublisher>();
await this.scheduler.QueueTask(deploymentLoadPublisher.Start, deploymentLoadPublisher.SchedulingContext)
.WithTimeout(this.initTimeout, $"Starting DeploymentLoadPublisher failed due to timeout {initTimeout}");
logger.Debug("Silo deployment load publisher started successfully.");
}
// Start background timer tick to watch for platform execution stalls, such as when GC kicks in
this.platformWatchdog = new Watchdog(statisticsOptions.LogWriteInterval, this.healthCheckParticipants, this.executorService, this.loggerFactory);
this.platformWatchdog.Start();
if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo platform watchdog started successfully."); }
}
catch (Exception exc)
{
this.SafeExecute(() => this.logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", this.SiloAddress), exc));
throw;
}
if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo.Start complete: System status = {0}", this.SystemStatus); }
}
private async Task OnBecomeActiveStart(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
StartTaskWithPerfAnalysis("Start gateway", StartGateway, stopWatch);
void StartGateway()
{
// Now that we're active, we can start the gateway
var mc = this.messageCenter as MessageCenter;
mc?.StartGateway(this.Services.GetRequiredService<ClientObserverRegistrar>());
logger.Debug("Message gateway service started successfully.");
}
await StartAsyncTaskWithPerfAnalysis("Starting local silo status oracle", BecomeActive, stopWatch);
async Task BecomeActive()
{
await scheduler.QueueTask(this.membershipOracle.BecomeActive, this.membershipOracleContext)
.WithTimeout(initTimeout, $"MembershipOracle activating failed due to timeout {initTimeout}");
logger.Debug("Local silo status oracle became active successfully.");
}
this.SystemStatus = SystemStatus.Running;
}
private async Task OnActiveStart(CancellationToken ct)
{
var stopWatch = Stopwatch.StartNew();
if (this.reminderService != null)
{
await StartAsyncTaskWithPerfAnalysis("Start reminder service", StartReminderService, stopWatch);
async Task StartReminderService()
{
// so, we have the view of the membership in the consistentRingProvider. We can start the reminder service
this.reminderServiceContext = (this.reminderService as SystemTarget)?.SchedulingContext ??
this.fallbackScheduler.SchedulingContext;
await this.scheduler.QueueTask(this.reminderService.Start, this.reminderServiceContext)
.WithTimeout(this.initTimeout, $"Starting ReminderService failed due to timeout {initTimeout}");
this.logger.Debug("Reminder service started successfully.");
}
}
foreach (var grainService in grainServices)
{
await StartGrainService(grainService);
}
}
private async Task CreateGrainServices()
{
var grainServices = this.Services.GetServices<IGrainService>();
foreach (var grainService in grainServices)
{
await RegisterGrainService(grainService);
}
}
private async Task RegisterGrainService(IGrainService service)
{
var grainService = (GrainService)service;
RegisterSystemTarget(grainService);
grainServices.Add(grainService);
await this.scheduler.QueueTask(() => grainService.Init(Services), grainService.SchedulingContext).WithTimeout(this.initTimeout, $"GrainService Initializing failed due to timeout {initTimeout}");
logger.Info($"Grain Service {service.GetType().FullName} registered successfully.");
}
private async Task StartGrainService(IGrainService service)
{
var grainService = (GrainService)service;
await this.scheduler.QueueTask(grainService.Start, grainService.SchedulingContext).WithTimeout(this.initTimeout, $"Starting GrainService failed due to timeout {initTimeout}");
logger.Info($"Grain Service {service.GetType().FullName} started successfully.");
}
private void ConfigureThreadPoolAndServicePointSettings()
{
PerformanceTuningOptions performanceTuningOptions = Services.GetRequiredService<IOptions<PerformanceTuningOptions>>().Value;
if (performanceTuningOptions.MinDotNetThreadPoolSize > 0)
{
int workerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
if (performanceTuningOptions.MinDotNetThreadPoolSize > workerThreads ||
performanceTuningOptions.MinDotNetThreadPoolSize > completionPortThreads)
{
// if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value.
int newWorkerThreads = Math.Max(performanceTuningOptions.MinDotNetThreadPoolSize, workerThreads);
int newCompletionPortThreads = Math.Max(performanceTuningOptions.MinDotNetThreadPoolSize, completionPortThreads);
bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads);
if (ok)
{
logger.Info(ErrorCode.SiloConfiguredThreadPool,
"Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
else
{
logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool,
"Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.",
newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads);
}
}
}
// Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage
// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx
logger.Info(ErrorCode.SiloConfiguredServicePointManager,
"Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.",
performanceTuningOptions.Expect100Continue, performanceTuningOptions.DefaultConnectionLimit, performanceTuningOptions.UseNagleAlgorithm);
ServicePointManager.Expect100Continue = performanceTuningOptions.Expect100Continue;
ServicePointManager.DefaultConnectionLimit = performanceTuningOptions.DefaultConnectionLimit;
ServicePointManager.UseNagleAlgorithm = performanceTuningOptions.UseNagleAlgorithm;
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// Grains are not deactivated.
/// </summary>
public void Stop()
{
var cancellationSource = new CancellationTokenSource();
cancellationSource.Cancel();
StopAsync(cancellationSource.Token).GetAwaiter().GetResult();
}
/// <summary>
/// Gracefully stop the run time system and the application.
/// All grains will be properly deactivated.
/// All in-flight applications requests would be awaited and finished gracefully.
/// </summary>
public void Shutdown()
{
StopAsync(CancellationToken.None).GetAwaiter().GetResult();
}
/// <summary>
/// Gracefully stop the run time system only, but not the application.
/// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible.
/// </summary>
public async Task StopAsync(CancellationToken cancellationToken)
{
bool gracefully = !cancellationToken.IsCancellationRequested;
string operation = gracefully ? "Shutdown()" : "Stop()";
bool stopAlreadyInProgress = false;
lock (lockable)
{
if (this.SystemStatus.Equals(SystemStatus.Stopping) ||
this.SystemStatus.Equals(SystemStatus.ShuttingDown) ||
this.SystemStatus.Equals(SystemStatus.Terminated))
{
stopAlreadyInProgress = true;
// Drop through to wait below
}
else if (!this.SystemStatus.Equals(SystemStatus.Running))
{
throw new InvalidOperationException(String.Format("Calling Silo.{0} on a silo which is not in the Running state. This silo is in the {1} state.", operation, this.SystemStatus));
}
else
{
if (gracefully)
this.SystemStatus = SystemStatus.ShuttingDown;
else
this.SystemStatus = SystemStatus.Stopping;
}
}
if (stopAlreadyInProgress)
{
logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish");
var pause = TimeSpan.FromSeconds(1);
while (!this.SystemStatus.Equals(SystemStatus.Terminated))
{
logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause);
Thread.Sleep(pause);
}
await this.siloTerminatedTask.Task;
return;
}
try
{
await this.scheduler.QueueTask(() => this.siloLifecycle.OnStop(cancellationToken), this.lifecycleSchedulingSystemTarget.SchedulingContext);
} finally
{
SafeExecute(scheduler.Stop);
SafeExecute(scheduler.PrintStatistics);
}
}
private Task OnRuntimeServicesStop(CancellationToken cancellationToken)
{
// Start rejecting all silo to silo application messages
SafeExecute(messageCenter.BlockApplicationMessages);
// Stop scheduling/executing application turns
SafeExecute(scheduler.StopApplicationTurns);
// Directory: Speed up directory handoff
// will be started automatically when directory receives SiloStatusChangeNotification(Stopping)
SafeExecute(() => LocalGrainDirectory.StopPreparationCompletion.WaitWithThrow(stopTimeout));
return Task.CompletedTask;
}
private Task OnRuntimeInitializeStop(CancellationToken ct)
{
// 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ...
logger.Info(ErrorCode.SiloStopped, "Silo is Stopped()");
SafeExecute(() => scheduler.QueueTask( this.membershipOracle.KillMyself, this.membershipOracleContext)
.WaitWithThrow(stopTimeout));
// incoming messages
SafeExecute(incomingSystemAgent.Stop);
SafeExecute(incomingPingAgent.Stop);
SafeExecute(incomingAgent.Stop);
// timers
if (platformWatchdog != null)
SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up
SafeExecute(activationDirectory.PrintActivationDirectory);
SafeExecute(messageCenter.Stop);
SafeExecute(siloStatistics.Stop);
SafeExecute(() => this.SystemStatus = SystemStatus.Terminated);
SafeExecute(() => (this.Services as IDisposable)?.Dispose());
// Setting the event should be the last thing we do.
// Do nothing after that!
this.siloTerminatedTask.SetResult(0);
return Task.CompletedTask;
}
private async Task OnBecomeActiveStop(CancellationToken ct)
{
bool gracefully = !ct.IsCancellationRequested;
string operation = gracefully ? "Shutdown()" : "Stop()";
try
{
if (gracefully)
{
logger.Info(ErrorCode.SiloShuttingDown, "Silo starting to Shutdown()");
// Write "ShutDown" state in the table + broadcast gossip msgs to re-read the table to everyone
await scheduler.QueueTask(this.membershipOracle.ShutDown, this.membershipOracleContext)
.WithTimeout(stopTimeout, $"MembershipOracle Shutting down failed due to timeout {stopTimeout}");
// Deactivate all grains
SafeExecute(() => catalog.DeactivateAllActivations().WaitWithThrow(stopTimeout));
}
else
{
logger.Info(ErrorCode.SiloStopping, "Silo starting to Stop()");
// Write "Stopping" state in the table + broadcast gossip msgs to re-read the table to everyone
await scheduler.QueueTask(this.membershipOracle.Stop, this.membershipOracleContext)
.WithTimeout(stopTimeout, $"Stopping MembershipOracle faield due to timeout {stopTimeout}");
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.SiloFailedToStopMembership, String.Format("Failed to {0} membership oracle. About to FastKill this silo.", operation), exc);
return; // will go to finally
}
// Stop the gateway
SafeExecute(messageCenter.StopAcceptingClientMessages);
}
private async Task OnActiveStop(CancellationToken ct)
{
if (reminderService != null)
{
// 2: Stop reminder service
await scheduler.QueueTask(reminderService.Stop, this.reminderServiceContext)
.WithTimeout(stopTimeout, $"Stopping ReminderService failed due to timeout {stopTimeout}");
}
foreach (var grainService in grainServices)
{
await this.scheduler.QueueTask(grainService.Stop, grainService.SchedulingContext).WithTimeout(this.stopTimeout, $"Stopping GrainService failed due to timeout {initTimeout}");
if (this.logger.IsEnabled(LogLevel.Debug))
{
logger.Debug(String.Format("{0} Grain Service with Id {1} stopped successfully.", grainService.GetType().FullName, grainService.GetPrimaryKeyLong(out string ignored)));
}
}
}
private void SafeExecute(Action action)
{
Utils.SafeExecute(action, logger, "Silo.Stop");
}
private void HandleProcessExit(object sender, EventArgs e)
{
// NOTE: We need to minimize the amount of processing occurring on this code path -- we only have under approx 2-3 seconds before process exit will occur
this.logger.Warn(ErrorCode.Runtime_Error_100220, "Process is exiting");
this.Stop();
}
internal void RegisterSystemTarget(SystemTarget target)
{
var providerRuntime = this.Services.GetRequiredService<SiloProviderRuntime>();
providerRuntime.RegisterSystemTarget(target);
}
/// <summary> Return dump of diagnostic data from this silo. </summary>
/// <param name="all"></param>
/// <returns>Debug data for this silo.</returns>
public string GetDebugDump(bool all = true)
{
var sb = new StringBuilder();
foreach (var systemTarget in activationDirectory.AllSystemTargets())
sb.AppendFormat("System target {0}:", ((ISystemTargetBase)systemTarget).GrainId.ToString()).AppendLine();
var enumerator = activationDirectory.GetEnumerator();
while(enumerator.MoveNext())
{
Utils.SafeExecute(() =>
{
var activationData = enumerator.Current.Value;
var workItemGroup = scheduler.GetWorkItemGroup(activationData.SchedulingContext);
if (workItemGroup == null)
{
sb.AppendFormat("Activation with no work item group!! Grain {0}, activation {1}.",
activationData.Grain,
activationData.ActivationId);
sb.AppendLine();
return;
}
if (all || activationData.State.Equals(ActivationState.Valid))
{
sb.AppendLine(workItemGroup.DumpStatus());
sb.AppendLine(activationData.DumpStatus());
}
});
}
logger.Info(ErrorCode.SiloDebugDump, sb.ToString());
return sb.ToString();
}
/// <summary> Object.ToString override -- summary info for this silo. </summary>
public override string ToString()
{
return localGrainDirectory.ToString();
}
private void Participate(ISiloLifecycle lifecycle)
{
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeInitialize, (ct) => Task.Run(() => OnRuntimeInitializeStart(ct)), (ct) => Task.Run(() => OnRuntimeInitializeStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeServices, (ct) => Task.Run(() => OnRuntimeServicesStart(ct)), (ct) => Task.Run(() => OnRuntimeServicesStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeGrainServices, (ct) => Task.Run(() => OnRuntimeGrainServicesStart(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.BecomeActive, (ct) => Task.Run(() => OnBecomeActiveStart(ct)), (ct) => Task.Run(() => OnBecomeActiveStop(ct)));
lifecycle.Subscribe<Silo>(ServiceLifecycleStage.Active, (ct) => Task.Run(() => OnActiveStart(ct)), (ct) => Task.Run(() => OnActiveStop(ct)));
}
}
// A dummy system target for fallback scheduler
internal class FallbackSystemTarget : SystemTarget
{
public FallbackSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory)
: base(Constants.FallbackSystemTargetId, localSiloDetails.SiloAddress, loggerFactory)
{
}
}
// A dummy system target for fallback scheduler
internal class LifecycleSchedulingSystemTarget : SystemTarget
{
public LifecycleSchedulingSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory)
: base(Constants.LifecycleSchedulingSystemTargetId, localSiloDetails.SiloAddress, loggerFactory)
{
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Provisioning.SiteModifierWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Newtonsoft.Json.Linq;
using NuGet.Client.Installation;
using NuGet.Client.Resolution;
using NuGet.Versioning;
using NuGet.VisualStudio;
using NuGetConsole;
using Resx = NuGet.Client.VisualStudio.UI.Resources;
namespace NuGet.Client.VisualStudio.UI
{
/// <summary>
/// Interaction logic for PackageManagerControl.xaml
/// </summary>
public partial class PackageManagerControl : UserControl
{
private const int PageSize = 10;
// Copied from file Constants.cs in NuGet.Core:
// This is temporary until we fix the gallery to have proper first class support for this.
// The magic unpublished date is 1900-01-01T00:00:00
public static readonly DateTimeOffset Unpublished = new DateTimeOffset(1900, 1, 1, 0, 0, 0, TimeSpan.FromHours(-8));
private bool _initialized;
// used to prevent starting new search when we update the package sources
// list in response to PackageSourcesChanged event.
private bool _dontStartNewSearch;
private int _busyCount;
public PackageManagerModel Model { get; private set; }
public SourceRepositoryManager Sources
{
get
{
return Model.Sources;
}
}
public InstallationTarget Target
{
get
{
return Model.Target;
}
}
private IConsole _outputConsole;
internal IUserInterfaceService UI { get; private set; }
private PackageRestoreBar _restoreBar;
private IPackageRestoreManager _packageRestoreManager;
public PackageManagerControl(PackageManagerModel model, IUserInterfaceService ui)
{
UI = ui;
Model = model;
InitializeComponent();
_searchControl.Text = model.SearchText;
_filter.Items.Add(Resx.Resources.Filter_All);
_filter.Items.Add(Resx.Resources.Filter_Installed);
_filter.Items.Add(Resx.Resources.Filter_UpdateAvailable);
// TODO: Relocate to v3 API.
_packageRestoreManager = ServiceLocator.GetInstance<IPackageRestoreManager>();
AddRestoreBar();
_packageDetail.Visibility = System.Windows.Visibility.Collapsed;
_packageDetail.Control = this;
_packageSolutionDetail.Visibility = System.Windows.Visibility.Collapsed;
_packageSolutionDetail.Control = this;
_busyCount = 0;
if (Target.IsSolution)
{
_packageSolutionDetail.Visibility = System.Windows.Visibility.Visible;
}
else
{
_packageDetail.Visibility = System.Windows.Visibility.Visible;
}
var outputConsoleProvider = ServiceLocator.GetInstance<IOutputConsoleProvider>();
_outputConsole = outputConsoleProvider.CreateOutputConsole(requirePowerShellHost: false);
InitSourceRepoList();
this.Unloaded += PackageManagerControl_Unloaded;
_initialized = true;
Model.Sources.PackageSourcesChanged += Sources_PackageSourcesChanged;
}
// Set the PackageStatus property of the given package.
private static void SetPackageStatus(
UiSearchResultPackage package,
InstallationTarget target)
{
var latestStableVersion = package.AllVersions
.Where(p => !p.Version.IsPrerelease)
.Max(p => p.Version);
// Get the minimum version installed in any target project/solution
var minimumInstalledPackage = target.GetAllTargetsRecursively()
.Select(t => t.InstalledPackages.GetInstalledPackage(package.Id))
.Where(p => p != null)
.OrderBy(r => r.Identity.Version)
.FirstOrDefault();
PackageStatus status;
if (minimumInstalledPackage != null)
{
if (minimumInstalledPackage.Identity.Version < latestStableVersion)
{
status = PackageStatus.UpdateAvailable;
}
else
{
status = PackageStatus.Installed;
}
}
else
{
status = PackageStatus.NotInstalled;
}
package.Status = status;
if (!Target.IsSolution)
{
var installedPackage = Target.InstalledPackages.GetInstalledPackage(selectedPackage.Id);
var installedVersion = installedPackage == null ? null : installedPackage.Identity.Version;
_packageDetail.DataContext = new PackageDetailControlModel(selectedPackage, installedVersion);
}
else
{
_packageSolutionDetail.DataContext = new PackageSolutionDetailControlModel(selectedPackage, (VsSolution)Target);
}
}
private void Sources_PackageSourcesChanged(object sender, EventArgs e)
{
// Set _dontStartNewSearch to true to prevent a new search started in
// _sourceRepoList_SelectionChanged(). This method will start the new
// search when needed by itself.
_dontStartNewSearch = true;
try
{
var oldActiveSource = _sourceRepoList.SelectedItem as PackageSource;
var newSources = new List<PackageSource>(Sources.AvailableSources);
// Update the source repo list with the new value.
_sourceRepoList.Items.Clear();
foreach (var source in newSources)
{
_sourceRepoList.Items.Add(source);
}
if (oldActiveSource != null && newSources.Contains(oldActiveSource))
{
// active source is not changed. Set _dontStartNewSearch to true
// to prevent a new search when _sourceRepoList.SelectedItem is set.
_sourceRepoList.SelectedItem = oldActiveSource;
}
else
{
// active source changed.
_sourceRepoList.SelectedItem =
newSources.Count > 0 ?
newSources[0] :
null;
// start search explicitly.
SearchPackageInActivePackageSource();
}
}
finally
{
_dontStartNewSearch = false;
}
}
private void PackageManagerControl_Unloaded(object sender, RoutedEventArgs e)
{
RemoveRestoreBar();
}
private void AddRestoreBar()
{
_restoreBar = new PackageRestoreBar(_packageRestoreManager);
_root.Children.Add(_restoreBar);
_packageRestoreManager.PackagesMissingStatusChanged += packageRestoreManager_PackagesMissingStatusChanged;
}
private void RemoveRestoreBar()
{
_restoreBar.CleanUp();
_packageRestoreManager.PackagesMissingStatusChanged -= packageRestoreManager_PackagesMissingStatusChanged;
}
private void packageRestoreManager_PackagesMissingStatusChanged(object sender, PackagesMissingStatusEventArgs e)
{
// PackageRestoreManager fires this event even when solution is closed.
// Don't do anything if solution is closed.
if (!Target.IsAvailable)
{
return;
}
if (!e.PackagesMissing)
{
// packages are restored. Update the UI
if (Target.IsSolution)
{
// TODO: update UI here
}
else
{
// TODO: update UI here
}
}
}
private void InitSourceRepoList()
{
_label.Text = string.Format(
CultureInfo.CurrentCulture,
Resx.Resources.Label_PackageManager,
Target.Name);
// init source repo list
_sourceRepoList.Items.Clear();
foreach (var source in Sources.AvailableSources)
{
_sourceRepoList.Items.Add(source);
}
if (Sources.ActiveRepository != null)
{
_sourceRepoList.SelectedItem = Sources.ActiveRepository.Source;
}
}
private void SetBusy(bool busy)
{
if (busy)
{
_busyCount++;
if (_busyCount > 0)
{
_busyControl.Visibility = System.Windows.Visibility.Visible;
this.IsEnabled = false;
}
}
else
{
_busyCount--;
if (_busyCount <= 0)
{
_busyControl.Visibility = System.Windows.Visibility.Collapsed;
this.IsEnabled = true;
}
}
}
private class PackageLoaderOption
{
public bool IncludePrerelease { get; set; }
public bool ShowUpdatesAvailable { get; set; }
}
private class PackageLoader : ILoader
{
// where to get the package list
private Func<int, CancellationToken, Task<IEnumerable<JObject>>> _loader;
private InstallationTarget _target;
private PackageLoaderOption _option;
public PackageLoader(
Func<int, CancellationToken, Task<IEnumerable<JObject>>> loader,
InstallationTarget target,
PackageLoaderOption option,
string searchText)
{
_loader = loader;
_target = target;
_option = option;
LoadingMessage = string.IsNullOrWhiteSpace(searchText) ?
Resx.Resources.Text_Loading :
string.Format(
CultureInfo.CurrentCulture,
Resx.Resources.Text_Searching,
searchText);
}
public string LoadingMessage
{
get;
private set;
}
private Task<List<JObject>> InternalLoadItems(
int startIndex,
CancellationToken ct,
Func<int, CancellationToken, Task<IEnumerable<JObject>>> loader)
{
return Task.Factory.StartNew(() =>
{
var r1 = _loader(startIndex, ct);
return r1.Result.ToList();
});
}
private UiDetailedPackage ToDetailedPackage(UiSearchResultPackage package)
{
var detailedPackage = new UiDetailedPackage();
detailedPackage.Id = package.Id;
detailedPackage.Version = package.Version;
detailedPackage.Summary = package.Summary;
return detailedPackage;
}
public async Task<LoadResult> LoadItems(int startIndex, CancellationToken ct)
{
var results = await InternalLoadItems(startIndex, ct, _loader);
List<UiSearchResultPackage> packages = new List<UiSearchResultPackage>();
foreach (var package in results)
{
ct.ThrowIfCancellationRequested();
// As a debugging aide, I am intentionally NOT using an object initializer -anurse
var searchResultPackage = new UiSearchResultPackage();
searchResultPackage.Id = package.Value<string>(Properties.PackageId);
searchResultPackage.Version = NuGetVersion.Parse(package.Value<string>(Properties.LatestVersion));
if (searchResultPackage.Version.IsPrerelease && !_option.IncludePrerelease)
{
// don't include prerelease version if includePrerelease is false
continue;
}
searchResultPackage.IconUrl = GetUri(package, Properties.IconUrl);
var allVersions = LoadVersions(
package.Value<JArray>(Properties.Packages),
searchResultPackage.Version);
if (!allVersions.Select(v => v.Version).Contains(searchResultPackage.Version))
{
// make sure allVersions contains searchResultPackage itself.
allVersions.Add(ToDetailedPackage(searchResultPackage));
}
searchResultPackage.AllVersions = allVersions;
SetPackageStatus(searchResultPackage, _target);
if (_option.ShowUpdatesAvailable &&
searchResultPackage.Status != PackageStatus.UpdateAvailable)
{
continue;
}
searchResultPackage.Summary = package.Value<string>(Properties.Summary);
if (string.IsNullOrWhiteSpace(searchResultPackage.Summary))
{
// summary is empty. Use its description instead.
var self = searchResultPackage.AllVersions.FirstOrDefault(p => p.Version == searchResultPackage.Version);
if (self != null)
{
searchResultPackage.Summary = self.Description;
}
}
packages.Add(searchResultPackage);
}
ct.ThrowIfCancellationRequested();
return new LoadResult()
{
Items = packages,
HasMoreItems = packages.Count == PageSize
};
}
// Get all versions of the package
private List<UiDetailedPackage> LoadVersions(JArray versions, NuGetVersion searchResultVersion)
{
var retValue = new List<UiDetailedPackage>();
// If repo is AggregateRepository, the package duplicates can be returned by
// FindPackagesById(), so Distinct is needed here to remove the duplicates.
foreach (var token in versions)
{
Debug.Assert(token.Type == JTokenType.Object);
JObject version = (JObject)token;
var detailedPackage = new UiDetailedPackage();
detailedPackage.Id = version.Value<string>(Properties.PackageId);
detailedPackage.Version = NuGetVersion.Parse(version.Value<string>(Properties.Version));
if (detailedPackage.Version.IsPrerelease &&
!_option.IncludePrerelease &&
detailedPackage.Version != searchResultVersion)
{
// don't include prerelease version if includePrerelease is false
continue;
}
string publishedStr = version.Value<string>(Properties.Published);
if (!String.IsNullOrEmpty(publishedStr))
{
detailedPackage.Published = DateTime.Parse(publishedStr);
if (detailedPackage.Published <= Unpublished &&
detailedPackage.Version != searchResultVersion)
{
// don't include unlisted package
continue;
}
}
detailedPackage.Summary = version.Value<string>(Properties.Summary);
detailedPackage.Description = version.Value<string>(Properties.Description);
detailedPackage.Authors = version.Value<string>(Properties.Authors);
detailedPackage.Owners = version.Value<string>(Properties.Owners);
detailedPackage.IconUrl = GetUri(version, Properties.IconUrl);
detailedPackage.LicenseUrl = GetUri(version, Properties.LicenseUrl);
detailedPackage.ProjectUrl = GetUri(version, Properties.ProjectUrl);
detailedPackage.Tags = String.Join(" ", (version.Value<JArray>(Properties.Tags) ?? Enumerable.Empty<JToken>()).Select(t => t.ToString()));
detailedPackage.DownloadCount = version.Value<int>(Properties.DownloadCount);
detailedPackage.DependencySets = (version.Value<JArray>(Properties.DependencyGroups) ?? Enumerable.Empty<JToken>()).Select(obj => LoadDependencySet((JObject)obj));
detailedPackage.HasDependencies = detailedPackage.DependencySets.Any(
set => set.Dependencies != null && set.Dependencies.Count > 0);
retValue.Add(detailedPackage);
}
return retValue;
}
private Uri GetUri(JObject json, string property)
{
if (json[property] == null)
{
return null;
}
string str = json[property].ToString();
if (String.IsNullOrEmpty(str))
{
return null;
}
return new Uri(str);
}
private UiPackageDependencySet LoadDependencySet(JObject set)
{
var fxName = set.Value<string>(Properties.TargetFramework);
return new UiPackageDependencySet(
String.IsNullOrEmpty(fxName) ? null : FrameworkNameHelper.ParsePossiblyShortenedFrameworkName(fxName),
(set.Value<JArray>(Properties.Dependencies) ?? Enumerable.Empty<JToken>()).Select(obj => LoadDependency((JObject)obj)));
}
private UiPackageDependency LoadDependency(JObject dep)
{
var ver = dep.Value<string>(Properties.Range);
return new UiPackageDependency(
dep.Value<string>(Properties.PackageId),
String.IsNullOrEmpty(ver) ? null : VersionRange.Parse(ver));
}
private string StringCollectionToString(JArray v)
{
if (v == null)
{
return null;
}
string retValue = String.Join(", ", v.Select(t => t.ToString()));
if (retValue == String.Empty)
{
return null;
}
return retValue;
}
}
private bool ShowInstalled
{
get
{
return Resx.Resources.Filter_Installed.Equals(_filter.SelectedItem);
}
}
private bool ShowUpdatesAvailable
{
get
{
return Resx.Resources.Filter_UpdateAvailable.Equals(_filter.SelectedItem);
}
}
public bool IncludePrerelease
{
get
{
return _checkboxPrerelease.IsChecked == true;
}
}
internal SourceRepository CreateActiveRepository()
{
var activeSource = _sourceRepoList.SelectedItem as PackageSource;
if (activeSource == null)
{
return null;
}
return Sources.CreateSourceRepository(activeSource);
}
private void SearchPackageInActivePackageSource()
{
var searchText = _searchControl.Text;
var supportedFrameworks = Target.GetSupportedFrameworks();
// search online
var activeSource = _sourceRepoList.SelectedItem as PackageSource;
var sourceRepository = Sources.CreateSourceRepository(activeSource);
PackageLoaderOption option = new PackageLoaderOption()
{
IncludePrerelease = this.IncludePrerelease,
ShowUpdatesAvailable = this.ShowUpdatesAvailable
};
if (ShowInstalled || ShowUpdatesAvailable)
{
// search installed packages
var loader = new PackageLoader(
(startIndex, ct) =>
Target.SearchInstalled(
sourceRepository,
searchText,
startIndex,
PageSize,
ct),
Target,
option,
searchText);
_packageList.Loader = loader;
}
else
{
// search in active package source
if (activeSource == null)
{
var loader = new PackageLoader(
(startIndex, ct) =>
{
return Task.Factory.StartNew(() =>
{
return Enumerable.Empty<JObject>();
});
},
Target,
option,
searchText);
_packageList.Loader = loader;
}
else
{
var loader = new PackageLoader(
(startIndex, ct) =>
sourceRepository.Search(
searchText,
new SearchFilter()
{
SupportedFrameworks = supportedFrameworks,
IncludePrerelease = option.IncludePrerelease
},
startIndex,
PageSize,
ct),
Target,
option,
searchText);
_packageList.Loader = loader;
}
}
}
private void SettingsButtonClick(object sender, RoutedEventArgs e)
{
UI.LaunchNuGetOptionsDialog();
}
private void PackageList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UpdateDetailPane();
}
/// <summary>
/// Updates the detail pane based on the selected package
/// </summary>
private void UpdateDetailPane()
{
var selectedPackage = _packageList.SelectedItem as UiSearchResultPackage;
if (selectedPackage == null)
{
_packageDetail.DataContext = null;
_packageSolutionDetail.DataContext = null;
}
else
{
if (!Target.IsSolution)
{
var installedPackage = Target.InstalledPackages.GetInstalledPackage(selectedPackage.Id);
var installedVersion = installedPackage == null ? null : installedPackage.Identity.Version;
_packageDetail.DataContext = new PackageDetailControlModel(selectedPackage, installedVersion);
}
else
{
_packageSolutionDetail.DataContext = new PackageSolutionDetailControlModel(selectedPackage, (VsSolution)Target);
}
}
}
private void _sourceRepoList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_dontStartNewSearch)
{
return;
}
var newSource = _sourceRepoList.SelectedItem as PackageSource;
if (newSource != null)
{
Sources.ChangeActiveSource(newSource);
}
SearchPackageInActivePackageSource();
}
private void _filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_initialized)
{
SearchPackageInActivePackageSource();
}
}
internal void UpdatePackageStatus()
{
if (ShowInstalled || ShowUpdatesAvailable)
{
// refresh the whole package list
_packageList.Reload();
}
else
{
// in this case, we only need to update PackageStatus of
// existing items in the package list
foreach (var item in _packageList.Items)
{
var package = item as UiSearchResultPackage;
if (package == null)
{
continue;
}
SetPackageStatus(package, Target);
}
}
}
public bool ShowLicenseAgreement(IEnumerable<PackageAction> operations)
{
var licensePackages = operations.Where(op =>
op.ActionType == PackageActionType.Install &&
op.Package.Value<bool>("requireLicenseAcceptance"));
// display license window if necessary
if (licensePackages.Any())
{
// Hacky distinct without writing a custom comparer
var licenseModels = licensePackages
.GroupBy(a => Tuple.Create(a.Package["id"], a.Package["version"]))
.Select(g =>
{
dynamic p = g.First().Package;
string licenseUrl = (string)p.licenseUrl;
string id = (string)p.id;
string authors = (string)p.authors;
return new PackageLicenseInfo(
id,
licenseUrl == null ? null : new Uri(licenseUrl),
authors);
})
.Where(pli => pli.LicenseUrl != null); // Shouldn't get nulls, but just in case
bool accepted = this.UI.PromptForLicenseAcceptance(licenseModels);
if (!accepted)
{
return false;
}
}
return true;
}
private void PreviewActions(IEnumerable<PackageAction> actions)
{
var w = new PreviewWindow();
w.DataContext = new PreviewWindowModel(actions, Target);
w.ShowModal();
}
// preview user selected action
internal async void Preview(IDetailControl detailControl)
{
SetBusy(true);
try
{
_outputConsole.Clear();
var actions = await detailControl.ResolveActionsAsync();
PreviewActions(actions);
}
catch (Exception ex)
{
var errorDialog = new ErrorReportingDialog(
ex.Message,
ex.ToString());
errorDialog.ShowModal();
}
finally
{
SetBusy(false);
}
}
// perform the user selected action
internal async void PerformAction(IDetailControl detailControl)
{
SetBusy(true);
_outputConsole.Clear();
var progressDialog = new ProgressDialog(_outputConsole);
progressDialog.Owner = Window.GetWindow(this);
progressDialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
try
{
var actions = await detailControl.ResolveActionsAsync();
// show license agreeement
bool acceptLicense = ShowLicenseAgreement(actions);
if (!acceptLicense)
{
return;
}
// Create the executor and execute the actions
progressDialog.FileConflictAction = detailControl.FileConflictAction;
progressDialog.Show();
var executor = new ActionExecutor();
await executor.ExecuteActionsAsync(actions, logger: progressDialog, cancelToken: CancellationToken.None);
UpdatePackageStatus();
detailControl.Refresh();
}
catch (Exception ex)
{
var errorDialog = new ErrorReportingDialog(
ex.Message,
ex.ToString());
errorDialog.ShowModal();
}
finally
{
progressDialog.RequestToClose();
SetBusy(false);
}
}
private void _searchControl_SearchStart(object sender, EventArgs e)
{
if (!_initialized)
{
return;
}
SearchPackageInActivePackageSource();
}
private void _checkboxPrerelease_CheckChanged(object sender, RoutedEventArgs e)
{
if (!_initialized)
{
return;
}
SearchPackageInActivePackageSource();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Security;
using System.Threading.Tasks;
namespace System.Xml
{
internal abstract class XmlStreamNodeWriter : XmlNodeWriter
{
private Stream _stream;
private byte[] _buffer;
private int _offset;
private bool _ownsStream;
private const int bufferLength = 512;
private const int maxBytesPerChar = 3;
private Encoding _encoding;
private static UTF8Encoding s_UTF8Encoding = new UTF8Encoding(false, true);
protected XmlStreamNodeWriter()
{
_buffer = new byte[bufferLength];
}
protected void SetOutput(Stream stream, bool ownsStream, Encoding encoding)
{
_stream = stream;
_ownsStream = ownsStream;
_offset = 0;
_encoding = encoding;
}
// Getting/Setting the Stream exists for fragmenting
public Stream Stream
{
get
{
return _stream;
}
set
{
_stream = value;
}
}
// StreamBuffer/BufferOffset exists only for the BinaryWriter to fix up nodes
public byte[] StreamBuffer
{
get
{
return _buffer;
}
}
public int BufferOffset
{
get
{
return _offset;
}
}
public int Position
{
get
{
return (int)_stream.Position + _offset;
}
}
private int GetByteCount(char[] chars)
{
if (_encoding == null)
{
return s_UTF8Encoding.GetByteCount(chars);
}
else
{
return _encoding.GetByteCount(chars);
}
}
protected byte[] GetBuffer(int count, out int offset)
{
DiagnosticUtility.DebugAssert(count >= 0 && count <= bufferLength, "");
int bufferOffset = _offset;
if (bufferOffset + count <= bufferLength)
{
offset = bufferOffset;
}
else
{
FlushBuffer();
offset = 0;
}
#if DEBUG
DiagnosticUtility.DebugAssert(offset + count <= bufferLength, "");
for (int i = 0; i < count; i++)
{
_buffer[offset + i] = (byte)'<';
}
#endif
return _buffer;
}
protected async Task<BytesWithOffset> GetBufferAsync(int count)
{
int offset;
DiagnosticUtility.DebugAssert(count >= 0 && count <= bufferLength, "");
int bufferOffset = _offset;
if (bufferOffset + count <= bufferLength)
{
offset = bufferOffset;
}
else
{
await FlushBufferAsync().ConfigureAwait(false);
offset = 0;
}
#if DEBUG
DiagnosticUtility.DebugAssert(offset + count <= bufferLength, "");
for (int i = 0; i < count; i++)
{
_buffer[offset + i] = (byte)'<';
}
#endif
return new BytesWithOffset(_buffer, offset);
}
protected void Advance(int count)
{
DiagnosticUtility.DebugAssert(_offset + count <= bufferLength, "");
_offset += count;
}
private void EnsureByte()
{
if (_offset >= bufferLength)
{
FlushBuffer();
}
}
protected void WriteByte(byte b)
{
EnsureByte();
_buffer[_offset++] = b;
}
protected Task WriteByteAsync(byte b)
{
if (_offset >= bufferLength)
{
return FlushBufferAndWriteByteAsync(b);
}
else
{
_buffer[_offset++] = b;
return Task.CompletedTask;
}
}
private async Task FlushBufferAndWriteByteAsync(byte b)
{
await FlushBufferAsync().ConfigureAwait(false);
_buffer[_offset++] = b;
}
protected void WriteByte(char ch)
{
DiagnosticUtility.DebugAssert(ch < 0x80, "");
WriteByte((byte)ch);
}
protected Task WriteByteAsync(char ch)
{
DiagnosticUtility.DebugAssert(ch < 0x80, "");
return WriteByteAsync((byte)ch);
}
protected void WriteBytes(byte b1, byte b2)
{
byte[] buffer = _buffer;
int offset = _offset;
if (offset + 1 >= bufferLength)
{
FlushBuffer();
offset = 0;
}
buffer[offset + 0] = b1;
buffer[offset + 1] = b2;
_offset += 2;
}
protected Task WriteBytesAsync(byte b1, byte b2)
{
if (_offset + 1 >= bufferLength)
{
return FlushAndWriteBytesAsync(b1, b2);
}
else
{
_buffer[_offset++] = b1;
_buffer[_offset++] = b2;
return Task.CompletedTask;
}
}
private async Task FlushAndWriteBytesAsync(byte b1, byte b2)
{
await FlushBufferAsync().ConfigureAwait(false);
_buffer[_offset++] = b1;
_buffer[_offset++] = b2;
}
protected void WriteBytes(char ch1, char ch2)
{
DiagnosticUtility.DebugAssert(ch1 < 0x80 && ch2 < 0x80, "");
WriteBytes((byte)ch1, (byte)ch2);
}
protected Task WriteBytesAsync(char ch1, char ch2)
{
DiagnosticUtility.DebugAssert(ch1 < 0x80 && ch2 < 0x80, "");
return WriteBytesAsync((byte)ch1, (byte)ch2);
}
public void WriteBytes(byte[] byteBuffer, int byteOffset, int byteCount)
{
if (byteCount < bufferLength)
{
int offset;
byte[] buffer = GetBuffer(byteCount, out offset);
Buffer.BlockCopy(byteBuffer, byteOffset, buffer, offset, byteCount);
Advance(byteCount);
}
else
{
FlushBuffer();
_stream.Write(byteBuffer, byteOffset, byteCount);
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected void UnsafeWriteBytes(byte* bytes, int byteCount)
{
FlushBuffer();
byte[] buffer = _buffer;
while (byteCount >= bufferLength)
{
for (int i = 0; i < bufferLength; i++)
buffer[i] = bytes[i];
_stream.Write(buffer, 0, bufferLength);
bytes += bufferLength;
byteCount -= bufferLength;
}
{
for (int i = 0; i < byteCount; i++)
buffer[i] = bytes[i];
_stream.Write(buffer, 0, byteCount);
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe protected void WriteUTF8Char(int ch)
{
if (ch < 0x80)
{
WriteByte((byte)ch);
}
else if (ch <= char.MaxValue)
{
char* chars = stackalloc char[1];
chars[0] = (char)ch;
UnsafeWriteUTF8Chars(chars, 1);
}
else
{
SurrogateChar surrogateChar = new SurrogateChar(ch);
char* chars = stackalloc char[2];
chars[0] = surrogateChar.HighChar;
chars[1] = surrogateChar.LowChar;
UnsafeWriteUTF8Chars(chars, 2);
}
}
protected void WriteUTF8Chars(byte[] chars, int charOffset, int charCount)
{
if (charCount < bufferLength)
{
int offset;
byte[] buffer = GetBuffer(charCount, out offset);
Buffer.BlockCopy(chars, charOffset, buffer, offset, charCount);
Advance(charCount);
}
else
{
FlushBuffer();
_stream.Write(chars, charOffset, charCount);
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// Safe - unsafe code is effectively encapsulated, all inputs are validated
/// </SecurityNote>
[SecuritySafeCritical]
unsafe protected void WriteUTF8Chars(string value)
{
int count = value.Length;
if (count > 0)
{
fixed (char* chars = value)
{
UnsafeWriteUTF8Chars(chars, count);
}
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected void UnsafeWriteUTF8Chars(char* chars, int charCount)
{
const int charChunkSize = bufferLength / maxBytesPerChar;
while (charCount > charChunkSize)
{
int offset;
int chunkSize = charChunkSize;
if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate
chunkSize--;
byte[] buffer = GetBuffer(chunkSize * maxBytesPerChar, out offset);
Advance(UnsafeGetUTF8Chars(chars, chunkSize, buffer, offset));
charCount -= chunkSize;
chars += chunkSize;
}
if (charCount > 0)
{
int offset;
byte[] buffer = GetBuffer(charCount * maxBytesPerChar, out offset);
Advance(UnsafeGetUTF8Chars(chars, charCount, buffer, offset));
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected void UnsafeWriteUnicodeChars(char* chars, int charCount)
{
const int charChunkSize = bufferLength / 2;
while (charCount > charChunkSize)
{
int offset;
int chunkSize = charChunkSize;
if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate
chunkSize--;
byte[] buffer = GetBuffer(chunkSize * 2, out offset);
Advance(UnsafeGetUnicodeChars(chars, chunkSize, buffer, offset));
charCount -= chunkSize;
chars += chunkSize;
}
if (charCount > 0)
{
int offset;
byte[] buffer = GetBuffer(charCount * 2, out offset);
Advance(UnsafeGetUnicodeChars(chars, charCount, buffer, offset));
}
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected int UnsafeGetUnicodeChars(char* chars, int charCount, byte[] buffer, int offset)
{
char* charsMax = chars + charCount;
while (chars < charsMax)
{
char value = *chars++;
buffer[offset++] = (byte)value;
value >>= 8;
buffer[offset++] = (byte)value;
}
return charCount * 2;
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected int UnsafeGetUTF8Length(char* chars, int charCount)
{
char* charsMax = chars + charCount;
while (chars < charsMax)
{
if (*chars >= 0x80)
break;
chars++;
}
if (chars == charsMax)
return charCount;
char[] chArray = new char[charsMax - chars];
for (int i = 0; i < chArray.Length; i++)
{
chArray[i] = chars[i];
}
return (int)(chars - (charsMax - charCount)) + GetByteCount(chArray);
}
/// <SecurityNote>
/// Critical - contains unsafe code
/// caller needs to validate arguments
/// </SecurityNote>
[SecurityCritical]
unsafe protected int UnsafeGetUTF8Chars(char* chars, int charCount, byte[] buffer, int offset)
{
if (charCount > 0)
{
fixed (byte* _bytes = &buffer[offset])
{
byte* bytes = _bytes;
byte* bytesMax = &bytes[buffer.Length - offset];
char* charsMax = &chars[charCount];
while (true)
{
while (chars < charsMax)
{
char t = *chars;
if (t >= 0x80)
break;
*bytes = (byte)t;
bytes++;
chars++;
}
if (chars >= charsMax)
break;
char* charsStart = chars;
while (chars < charsMax && *chars >= 0x80)
{
chars++;
}
bytes += (_encoding ?? s_UTF8Encoding).GetBytes(charsStart, (int)(chars - charsStart), bytes, (int)(bytesMax - bytes));
if (chars >= charsMax)
break;
}
return (int)(bytes - _bytes);
}
}
return 0;
}
protected virtual void FlushBuffer()
{
if (_offset != 0)
{
_stream.Write(_buffer, 0, _offset);
_offset = 0;
}
}
protected virtual Task FlushBufferAsync()
{
if (_offset != 0)
{
var task = _stream.WriteAsync(_buffer, 0, _offset);
_offset = 0;
return task;
}
return Task.CompletedTask;
}
public override void Flush()
{
FlushBuffer();
_stream.Flush();
}
public override async Task FlushAsync()
{
await FlushBufferAsync().ConfigureAwait(false);
await _stream.FlushAsync().ConfigureAwait(false);
}
public override void Close()
{
if (_stream != null)
{
if (_ownsStream)
{
_stream.Dispose();
}
_stream = null;
}
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace RestServerSideWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ICSimulator
{
public interface IBufRingBackpressure
{
bool getCredit(Flit f, object sender, int bubble);
}
public class BufRingNetwork_Router : Router
{
BufRingNetwork_NIC[] _nics;
int _nic_count;
public BufRingNetwork_Router(Coord c) : base(c)
{
_nics = new BufRingNetwork_NIC[Config.bufrings_n];
_nic_count = 0;
}
protected override void _doStep()
{
// nothing
}
public override bool canInjectFlit(Flit f)
{
for (int i = 0; i < _nic_count; i++)
if (_nics[i].Inject == null)
return true;
return false;
}
public override void InjectFlit(Flit f)
{
int baseIdx = Simulator.rand.Next(_nic_count);
for (int i = 0; i < _nic_count; i++)
if (_nics[(i+baseIdx)%_nic_count].Inject == null) {
_nics[(i+baseIdx)%_nic_count].Inject = f;
return;
}
throw new Exception("Could not inject flit -- no free slots!");
}
public void statsIJ(Flit f)
{
statsInjectFlit(f);
}
public void acceptFlit(Flit f)
{
statsEjectFlit(f);
if (f.packet.nrOfArrivedFlits + 1 == f.packet.nrOfFlits)
statsEjectPacket(f.packet);
m_n.receiveFlit(f);
}
public void addNIC(BufRingNetwork_NIC nic)
{
_nics[_nic_count++] = nic;
}
}
public class BufRingNetwork_NIC : IBufRingBackpressure
{
BufRingNetwork_Router _router;
int _ring, _id;
IBufRingBackpressure _downstream;
Flit _inject;
Link _in, _out;
Queue<Flit> _buf;
int _credits;
public Flit Inject { get { return _inject; } set { _inject = value; } }
public bool getCredit(Flit f, object sender, int bubble)
{
if (_credits > bubble) {
_credits--;
return true;
}
else
return false;
}
public BufRingNetwork_NIC(int localring, int id)
{
_ring = localring;
_id = id;
_buf = new Queue<Flit>();
_credits = Config.bufrings_localbuf;
_inject = null;
}
public void setRouter(BufRingNetwork_Router router)
{
_router = router;
}
public bool doStep()
{
bool somethingMoved = false;
// handle input from ring
if (_in.Out != null) {
Flit f = _in.Out;
_in.Out = null;
somethingMoved = true;
if (f.packet.dest.ID == _router.coord.ID) {
_credits++;
_router.acceptFlit(f);
}
else {
_buf.Enqueue(f);
Simulator.stats.bufrings_nic_enqueue.Add();
}
}
// handle through traffic
if (_buf.Count > 0) {
Flit f = _buf.Peek();
if (_downstream.getCredit(f, this, 0)) {
_buf.Dequeue();
_credits++;
_out.In = f;
Simulator.stats.bufrings_nic_dequeue.Add();
somethingMoved = true;
}
}
// handle injections
if (_out.In == null && _inject != null) {
if (_downstream.getCredit(_inject, this, 2)) {
_out.In = _inject;
_router.statsIJ(_inject);
_inject = null;
Simulator.stats.bufrings_nic_inject.Add();
somethingMoved = true;
}
}
if (_inject != null)
Simulator.stats.bufrings_nic_starve.Add();
if (_out.In != null)
Simulator.stats.bufrings_link_traverse[1].Add();
Simulator.stats.bufrings_nic_occupancy.Add(_buf.Count);
return somethingMoved;
}
public void setInput(Link l)
{
_in = l;
}
public void setOutput(Link l, IBufRingBackpressure downstream)
{
_out = l;
_downstream = downstream;
}
public static void Map(int ID, out int localring, out int localid)
{
localring = ID/Config.bufrings_branching;
localid = ID%Config.bufrings_branching;
}
public void nuke(Queue<Flit> flits)
{
while (_buf.Count > 0) {
flits.Enqueue(_buf.Dequeue());
}
if (_inject != null)
flits.Enqueue(_inject);
_credits = Config.bufrings_localbuf;
_inject = null;
}
}
public class BufRingNetwork_IRI : IBufRingBackpressure
{
Link _gin, _gout, _lin, _lout;
Queue<Flit> _bufGL, _bufLG, _bufL, _bufG;
int _creditGL, _creditLG, _creditL, _creditG;
int _id;
IBufRingBackpressure _downstreamL, _downstreamG;
public bool getCredit(Flit f, object sender, int bubble)
{
int ring, localid;
BufRingNetwork_NIC.Map(f.packet.dest.ID, out ring, out localid);
if (sender is BufRingNetwork_IRI) { // on global ring
if (ring != _id) {
if (_creditG > bubble) {
_creditG--;
return true;
}
else
return false;
}
else {
if (_creditGL > bubble) {
_creditGL--;
return true;
}
else
return false;
}
}
else if (sender is BufRingNetwork_NIC) { // on local ring
if (ring != _id) {
if (_creditLG > bubble) {
_creditLG--;
return true;
}
else
return false;
}
else {
if (_creditL > bubble) {
_creditL--;
return true;
}
else
return false;
}
}
return false;
}
public BufRingNetwork_IRI(int localring)
{
if (Config.N != Config.bufrings_branching*Config.bufrings_branching)
throw new Exception("Wrong size for 2-level bufrings network! Check that N = (bufrings_branching)^2.");
_id = localring;
_bufGL = new Queue<Flit>();
_bufLG = new Queue<Flit>();
_bufL = new Queue<Flit>();
_bufG = new Queue<Flit>();
_creditGL = Config.bufrings_G2L;
_creditLG = Config.bufrings_L2G;
_creditL = Config.bufrings_localbuf;
_creditG = Config.bufrings_globalbuf;
}
public void setGlobalInput(Link l) { _gin = l; }
public void setGlobalOutput(Link l, IBufRingBackpressure b) { _gout = l; _downstreamG = b; }
public void setLocalInput(Link l) { _lin = l; }
public void setLocalOutput(Link l, IBufRingBackpressure b) { _lout = l; _downstreamL = b; }
public bool doStep()
{
bool somethingMoved = false;
// handle inputs
// global input
if (_gin.Out != null) {
Flit f = _gin.Out;
_gin.Out = null;
somethingMoved = true;
int ring, localid;
BufRingNetwork_NIC.Map(f.packet.dest.ID, out ring, out localid);
if (ring == _id) {
_bufGL.Enqueue(f);
Simulator.stats.bufrings_iri_enqueue_gl[0].Add();
}
else {
_bufG.Enqueue(f);
Simulator.stats.bufrings_iri_enqueue_g[0].Add();
}
}
// local input
if (_lin.Out != null) {
Flit f = _lin.Out;
_lin.Out = null;
somethingMoved = true;
int ring, localid;
BufRingNetwork_NIC.Map(f.packet.dest.ID, out ring, out localid);
if (ring == _id) {
_bufL.Enqueue(f);
Simulator.stats.bufrings_iri_enqueue_l[0].Add();
}
else {
_bufLG.Enqueue(f);
Simulator.stats.bufrings_iri_enqueue_lg[0].Add();
}
}
// handle outputs
// global output (on-ring traffic)
if (_gout.In == null && _bufG.Count > 0) {
Flit f = _bufG.Peek();
if (_downstreamG.getCredit(f, this, 0)) {
_bufG.Dequeue();
Simulator.stats.bufrings_iri_dequeue_g[0].Add();
_creditG++;
_gout.In = f;
somethingMoved = true;
}
}
// global output (transfer traffic)
if (_gout.In == null && _bufLG.Count > 0) {
Flit f = _bufLG.Peek();
if (_downstreamG.getCredit(f, this, 1)) {
_bufLG.Dequeue();
Simulator.stats.bufrings_iri_dequeue_lg[0].Add();
_creditLG++;
_gout.In = f;
somethingMoved = true;
}
}
// local output (on-ring traffic)
if (_lout.In == null && _bufL.Count > 0) {
Flit f = _bufL.Peek();
if (_downstreamL.getCredit(f, this, 0)) {
_bufL.Dequeue();
Simulator.stats.bufrings_iri_dequeue_l[0].Add();
_creditL++;
_lout.In = f;
somethingMoved = true;
}
}
// local output (transfer traffic)
if (_lout.In == null && _bufGL.Count > 0) {
Flit f = _bufGL.Peek();
if (_downstreamL.getCredit(f, this, 1)) {
_bufGL.Dequeue();
Simulator.stats.bufrings_iri_dequeue_gl[0].Add();
_creditGL++;
_lout.In = f;
somethingMoved = true;
}
}
if (_gout.In != null)
Simulator.stats.bufrings_link_traverse[0].Add();
if (_lout.In != null)
Simulator.stats.bufrings_link_traverse[1].Add();
Simulator.stats.bufrings_iri_occupancy_g[0].Add(_bufG.Count);
Simulator.stats.bufrings_iri_occupancy_l[0].Add(_bufL.Count);
Simulator.stats.bufrings_iri_occupancy_gl[0].Add(_bufGL.Count);
Simulator.stats.bufrings_iri_occupancy_lg[0].Add(_bufLG.Count);
return somethingMoved;
}
public void nuke(Queue<Flit> flits)
{
while (_bufGL.Count > 0)
flits.Enqueue(_bufGL.Dequeue());
while (_bufG.Count > 0)
flits.Enqueue(_bufG.Dequeue());
while (_bufL.Count > 0)
flits.Enqueue(_bufL.Dequeue());
while (_bufLG.Count > 0)
flits.Enqueue(_bufLG.Dequeue());
_creditGL = Config.bufrings_G2L;
_creditLG = Config.bufrings_L2G;
_creditL = Config.bufrings_localbuf;
_creditG = Config.bufrings_globalbuf;
}
}
public class BufRingNetwork : Network
{
BufRingNetwork_NIC[] _nics;
BufRingNetwork_IRI[] _iris;
BufRingNetwork_Router[] _routers;
public BufRingNetwork(int dimX, int dimY) : base(dimX, dimY)
{
X = dimX;
Y = dimY;
}
public override void setup()
{
// boilerplate
nodes = new Node[Config.N];
cache = new CmpCache();
ParseFinish(Config.finish);
workload = new Workload(Config.traceFilenames);
mapping = new NodeMapping_AllCPU_SharedCache();
links = new List<Link>();
_routers = new BufRingNetwork_Router[Config.N];
// create routers and nodes
for (int n = 0; n < Config.N; n++)
{
Coord c = new Coord(n);
nodes[n] = new Node(mapping, c);
_routers[n] = new BufRingNetwork_Router(c);
_routers[n].setNode(nodes[n]);
nodes[n].setRouter(_routers[n]);
}
int B = Config.bufrings_branching;
// create the NICs and IRIs
_nics = new BufRingNetwork_NIC[Config.N * Config.bufrings_n];
_iris = new BufRingNetwork_IRI[B * Config.bufrings_n];
// for each copy of the network...
for (int copy = 0; copy < Config.bufrings_n; copy++) {
// for each local ring...
for (int ring = 0; ring < B; ring++) {
// create global ring interface
_iris[copy*B + ring] = new BufRingNetwork_IRI(ring);
// create local NICs (ring stops)
for (int local = 0; local < B; local++)
_nics[copy*Config.N + ring*B + local] = new BufRingNetwork_NIC(ring, local);
// connect with links
for (int local = 1; local < B; local++)
{
Link l = new Link(Config.bufrings_locallat - 1);
links.Add(l);
_nics[copy*Config.N + ring*B + local - 1].setOutput(l,
_nics[copy*Config.N + ring*B + local]);
_nics[copy*Config.N + ring*B + local].setInput(l);
}
Link iriIn = new Link(Config.bufrings_locallat - 1), iriOut = new Link(Config.bufrings_locallat - 1);
links.Add(iriIn);
links.Add(iriOut);
_nics[copy*Config.N + ring*B + B-1].setOutput(iriIn,
_iris[copy*B + ring]);
_nics[copy*Config.N + ring*B + 0].setInput(iriOut);
_iris[copy*B + ring].setLocalInput(iriIn);
_iris[copy*B + ring].setLocalOutput(iriOut,
_nics[copy*Config.N + ring*B + 0]);
}
// connect IRIs with links to make up global ring
for (int ring = 0; ring < B; ring++) {
Link globalLink = new Link(Config.bufrings_globallat - 1);
links.Add(globalLink);
_iris[copy*B + ring].setGlobalOutput(globalLink,
_iris[copy*B + (ring+1)%B]);
_iris[copy*B + (ring+1)%B].setGlobalInput(globalLink);
}
// add the corresponding NIC to each node/router
for (int id = 0; id < Config.N; id++) {
int ring, local;
BufRingNetwork_NIC.Map(id, out ring, out local);
_routers[id].addNIC(_nics[copy * Config.N + ring*B + local]);
_nics[copy * Config.N + ring*B + local].setRouter(_routers[id]);
}
}
}
public override void doStep()
{
bool somethingMoved = false;
doStats();
for (int n = 0; n < Config.N; n++)
nodes[n].doStep();
// step the network sim: first, routers
foreach (BufRingNetwork_NIC nic in _nics)
if (nic.doStep())
somethingMoved = true;
foreach (BufRingNetwork_IRI iri in _iris)
if (iri.doStep())
somethingMoved = true;
bool stalled = false;
foreach (BufRingNetwork_NIC nic in _nics)
if (nic.Inject != null)
stalled = true;
// now, step each link
foreach (Link l in links)
l.doStep();
if (stalled && !somethingMoved)
nuke();
}
void nuke()
{
Console.WriteLine("NUKE! Cycle {0}.", Simulator.CurrentRound);
Simulator.stats.bufrings_nuke.Add();
// first, collect all flits from the network and reset credits, etc
Queue<Flit> flits = new Queue<Flit>();
foreach (BufRingNetwork_NIC nic in _nics)
nic.nuke(flits);
foreach (BufRingNetwork_IRI iri in _iris)
iri.nuke(flits);
foreach (Link l in links)
if (l.Out != null) {
flits.Enqueue(l.Out);
l.Out = null;
}
// now deliver all collected flits
while (flits.Count > 0) {
Flit f = flits.Dequeue();
_routers[f.packet.dest.ID].acceptFlit(f);
}
}
public override void close()
{
}
}
}
| |
// This is always generated file. Do not change anything.
using SoftFX.Lrp;
namespace SoftFX.Extended.Generated
{
internal static class TypesSerializer
{
public static System.ArgumentNullException ReadArgumentNullException(this MemoryBuffer buffer)
{
System.String _message = buffer.ReadAString();
var result = new System.ArgumentNullException(_message);
return result;
}
public static System.ArgumentException ReadArgumentException(this MemoryBuffer buffer)
{
System.String _message = buffer.ReadAString();
var result = new System.ArgumentException(_message);
return result;
}
public static SoftFX.Extended.Errors.InvalidHandleException ReadInvalidHandleException(this MemoryBuffer buffer)
{
System.String _message = buffer.ReadAString();
var result = new SoftFX.Extended.Errors.InvalidHandleException(_message);
return result;
}
public static SoftFX.Extended.Errors.RejectException ReadRejectException(this MemoryBuffer buffer)
{
System.String _message = buffer.ReadAString();
var result = new SoftFX.Extended.Errors.RejectException(_message);
result.Code = buffer.ReadInt32();
return result;
}
public static SoftFX.Extended.Errors.TimeoutException ReadTimeoutException(this MemoryBuffer buffer)
{
System.String _message = buffer.ReadAString();
var result = new SoftFX.Extended.Errors.TimeoutException(_message);
result.WaitingInterval = buffer.ReadInt32();
result.OperationId = buffer.ReadAString();
return result;
}
public static SoftFX.Extended.Errors.SendException ReadSendException(this MemoryBuffer buffer)
{
System.String _message = buffer.ReadAString();
var result = new SoftFX.Extended.Errors.SendException(_message);
return result;
}
public static SoftFX.Extended.Errors.LogoutException ReadLogoutException(this MemoryBuffer buffer)
{
System.String _message = buffer.ReadAString();
var result = new SoftFX.Extended.Errors.LogoutException(_message);
return result;
}
public static SoftFX.Extended.Errors.UnsupportedFeatureException ReadUnsupportedFeatureException(this MemoryBuffer buffer)
{
System.String _message = buffer.ReadAString();
var result = new SoftFX.Extended.Errors.UnsupportedFeatureException(_message);
result.Feature = buffer.ReadAString();
return result;
}
public static SoftFX.Extended.Errors.RuntimeException ReadRuntimeException(this MemoryBuffer buffer)
{
System.String _message = buffer.ReadAString();
var result = new SoftFX.Extended.Errors.RuntimeException(_message);
return result;
}
public static SoftFX.Extended.AccountType ReadAccountType(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.AccountType)buffer.ReadInt32();
return result;
}
public static void WriteAccountType(this MemoryBuffer buffer, SoftFX.Extended.AccountType arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.Severity ReadSeverity(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.Severity)buffer.ReadInt32();
return result;
}
public static void WriteSeverity(this MemoryBuffer buffer, SoftFX.Extended.Severity arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.NotificationType ReadNotificationType(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.NotificationType)buffer.ReadInt32();
return result;
}
public static void WriteNotificationType(this MemoryBuffer buffer, SoftFX.Extended.NotificationType arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.ProfitCalcMode ReadProfitCalcMode(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.ProfitCalcMode)buffer.ReadInt32();
return result;
}
public static void WriteProfitCalcMode(this MemoryBuffer buffer, SoftFX.Extended.ProfitCalcMode arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.MarginCalcMode ReadMarginCalcMode(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.MarginCalcMode)buffer.ReadInt32();
return result;
}
public static void WriteMarginCalcMode(this MemoryBuffer buffer, SoftFX.Extended.MarginCalcMode arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.SessionStatus ReadSessionStatus(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.SessionStatus)buffer.ReadInt32();
return result;
}
public static void WriteSessionStatus(this MemoryBuffer buffer, SoftFX.Extended.SessionStatus arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.TradeRecordSide ReadSide(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.TradeRecordSide)buffer.ReadInt32();
return result;
}
public static void WriteSide(this MemoryBuffer buffer, SoftFX.Extended.TradeRecordSide arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.PriceType ReadPriceType(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.PriceType)buffer.ReadInt32();
return result;
}
public static void WritePriceType(this MemoryBuffer buffer, SoftFX.Extended.PriceType arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.TradeRecordSide ReadTradeRecordSide(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.TradeRecordSide)buffer.ReadInt32();
return result;
}
public static void WriteTradeRecordSide(this MemoryBuffer buffer, SoftFX.Extended.TradeRecordSide arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.TradeRecordType ReadTradeRecordType(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.TradeRecordType)buffer.ReadInt32();
return result;
}
public static void WriteTradeRecordType(this MemoryBuffer buffer, SoftFX.Extended.TradeRecordType arg)
{
buffer.WriteInt32((int)arg);
}
public static System.Int32 ReadFxOrderType(this MemoryBuffer buffer)
{
var result = (System.Int32)buffer.ReadInt32();
return result;
}
public static void WriteFxOrderType(this MemoryBuffer buffer, System.Int32 arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.OrderType ReadOrderType(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.OrderType)buffer.ReadInt32();
return result;
}
public static void WriteOrderType(this MemoryBuffer buffer, SoftFX.Extended.OrderType arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.LogoutReason ReadLogoutReason(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.LogoutReason)buffer.ReadInt32();
return result;
}
public static void WriteLogoutReason(this MemoryBuffer buffer, SoftFX.Extended.LogoutReason arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.TwoFactorReason ReadTwoFactorReason(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.TwoFactorReason)buffer.ReadInt32();
return result;
}
public static void WriteTwoFactorReason(this MemoryBuffer buffer, SoftFX.Extended.TwoFactorReason arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.OrderStatus ReadOrderStatus(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.OrderStatus)buffer.ReadInt32();
return result;
}
public static void WriteOrderStatus(this MemoryBuffer buffer, SoftFX.Extended.OrderStatus arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.ExecutionType ReadExecutionType(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.ExecutionType)buffer.ReadInt32();
return result;
}
public static void WriteExecutionType(this MemoryBuffer buffer, SoftFX.Extended.ExecutionType arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.RejectReason ReadRejectReason(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.RejectReason)buffer.ReadInt32();
return result;
}
public static void WriteRejectReason(this MemoryBuffer buffer, SoftFX.Extended.RejectReason arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.CommissionType ReadCommissionType(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.CommissionType)buffer.ReadInt32();
return result;
}
public static void WriteCommissionType(this MemoryBuffer buffer, SoftFX.Extended.CommissionType arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.CommissionChargeType ReadCommissionChargeType(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.CommissionChargeType)buffer.ReadInt32();
return result;
}
public static void WriteCommissionChargeType(this MemoryBuffer buffer, SoftFX.Extended.CommissionChargeType arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.CommissionChargeMethod ReadCommissionChargeMethod(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.CommissionChargeMethod)buffer.ReadInt32();
return result;
}
public static void WriteCommissionChargeMethod(this MemoryBuffer buffer, SoftFX.Extended.CommissionChargeMethod arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.SwapType ReadSwapType(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.SwapType)buffer.ReadInt32();
return result;
}
public static void WriteSwapType(this MemoryBuffer buffer, SoftFX.Extended.SwapType arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.Data.Notification ReadNotification(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.Data.Notification();
result.Severity = buffer.ReadSeverity();
result.Type = buffer.ReadNotificationType();
result.Text = buffer.ReadAString();
result.Balance = buffer.ReadDouble();
result.TransactionAmount = buffer.ReadDouble();
result.TransactionCurrency = buffer.ReadAString();
return result;
}
public static void WriteNotification(this MemoryBuffer buffer, SoftFX.Extended.Data.Notification arg)
{
buffer.WriteSeverity(arg.Severity);
buffer.WriteNotificationType(arg.Type);
buffer.WriteAString(arg.Text);
buffer.WriteDouble(arg.Balance);
buffer.WriteDouble(arg.TransactionAmount);
buffer.WriteAString(arg.TransactionCurrency);
}
public static SoftFX.Extended.DataHistoryInfo ReadDataHistoryInfo(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.DataHistoryInfo();
result.FromAll = buffer.ReadTime();
result.ToAll = buffer.ReadTime();
result.From = buffer.ReadNullTime();
result.To = buffer.ReadNullTime();
result.LastTickId = buffer.ReadAString();
result.Files = buffer.ReadStringArray();
result.Bars = buffer.ReadBarArray();
return result;
}
public static void WriteDataHistoryInfo(this MemoryBuffer buffer, SoftFX.Extended.DataHistoryInfo arg)
{
buffer.WriteTime(arg.FromAll);
buffer.WriteTime(arg.ToAll);
buffer.WriteNullTime(arg.From);
buffer.WriteNullTime(arg.To);
buffer.WriteAString(arg.LastTickId);
buffer.WriteStringArray(arg.Files);
buffer.WriteBarArray(arg.Bars);
}
public static SoftFX.Extended.SymbolInfo ReadSymbolInfo(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.SymbolInfo();
result.Name = buffer.ReadAString();
result.Currency = buffer.ReadAString();
result.SettlementCurrency = buffer.ReadAString();
result.ContractMultiplier = buffer.ReadDouble();
result.Description = buffer.ReadWString();
result.Precision = buffer.ReadInt32();
result.RoundLot = buffer.ReadDouble();
result.MinTradeVolume = buffer.ReadDouble();
result.MaxTradeVolume = buffer.ReadDouble();
result.TradeVolumeStep = buffer.ReadDouble();
result.ProfitCalcMode = buffer.ReadProfitCalcMode();
result.MarginCalcMode = buffer.ReadMarginCalcMode();
result.MarginHedge = buffer.ReadDouble();
result.MarginFactor = buffer.ReadInt32();
result.MarginFactorFractional = buffer.ReadNullDouble();
result.Color = buffer.ReadInt32();
result.CommissionType = buffer.ReadCommissionType();
result.CommissionChargeType = buffer.ReadCommissionChargeType();
result.CommissionChargeMethod = buffer.ReadCommissionChargeMethod();
result.LimitsCommission = buffer.ReadDouble();
result.Commission = buffer.ReadDouble();
result.MinCommission = buffer.ReadDouble();
result.MinCommissionCurrency = buffer.ReadWString();
result.SwapType = buffer.ReadSwapType();
result.TripleSwapDay = buffer.ReadInt32();
result.SwapSizeShort = buffer.ReadNullDouble();
result.SwapSizeLong = buffer.ReadNullDouble();
result.DefaultSlippage = buffer.ReadNullDouble();
result.IsTradeEnabled = buffer.ReadBoolean();
result.GroupSortOrder = buffer.ReadInt32();
result.SortOrder = buffer.ReadInt32();
result.CurrencySortOrder = buffer.ReadInt32();
result.SettlementCurrencySortOrder = buffer.ReadInt32();
result.CurrencyPrecision = buffer.ReadInt32();
result.SettlementCurrencyPrecision = buffer.ReadInt32();
result.StatusGroupId = buffer.ReadAString();
result.SecurityName = buffer.ReadAString();
result.SecurityDescription = buffer.ReadWString();
result.StopOrderMarginReduction = buffer.ReadNullDouble();
result.HiddenLimitOrderMarginReduction = buffer.ReadNullDouble();
result.IsCloseOnly = buffer.ReadBoolean();
return result;
}
public static void WriteSymbolInfo(this MemoryBuffer buffer, SoftFX.Extended.SymbolInfo arg)
{
buffer.WriteAString(arg.Name);
buffer.WriteAString(arg.Currency);
buffer.WriteAString(arg.SettlementCurrency);
buffer.WriteDouble(arg.ContractMultiplier);
buffer.WriteWString(arg.Description);
buffer.WriteInt32(arg.Precision);
buffer.WriteDouble(arg.RoundLot);
buffer.WriteDouble(arg.MinTradeVolume);
buffer.WriteDouble(arg.MaxTradeVolume);
buffer.WriteDouble(arg.TradeVolumeStep);
buffer.WriteProfitCalcMode(arg.ProfitCalcMode);
buffer.WriteMarginCalcMode(arg.MarginCalcMode);
buffer.WriteDouble(arg.MarginHedge);
buffer.WriteInt32(arg.MarginFactor);
buffer.WriteNullDouble(arg.MarginFactorFractional);
buffer.WriteInt32(arg.Color);
buffer.WriteCommissionType(arg.CommissionType);
buffer.WriteCommissionChargeType(arg.CommissionChargeType);
buffer.WriteCommissionChargeMethod(arg.CommissionChargeMethod);
buffer.WriteDouble(arg.LimitsCommission);
buffer.WriteDouble(arg.Commission);
buffer.WriteDouble(arg.MinCommission);
buffer.WriteWString(arg.MinCommissionCurrency);
buffer.WriteSwapType(arg.SwapType);
buffer.WriteInt32(arg.TripleSwapDay);
buffer.WriteNullDouble(arg.SwapSizeShort);
buffer.WriteNullDouble(arg.SwapSizeLong);
buffer.WriteNullDouble(arg.DefaultSlippage);
buffer.WriteBoolean(arg.IsTradeEnabled);
buffer.WriteInt32(arg.GroupSortOrder);
buffer.WriteInt32(arg.SortOrder);
buffer.WriteInt32(arg.CurrencySortOrder);
buffer.WriteInt32(arg.SettlementCurrencySortOrder);
buffer.WriteInt32(arg.CurrencyPrecision);
buffer.WriteInt32(arg.SettlementCurrencyPrecision);
buffer.WriteAString(arg.StatusGroupId);
buffer.WriteAString(arg.SecurityName);
buffer.WriteWString(arg.SecurityDescription);
buffer.WriteNullDouble(arg.StopOrderMarginReduction);
buffer.WriteNullDouble(arg.HiddenLimitOrderMarginReduction);
buffer.WriteBoolean(arg.IsCloseOnly);
}
public static SoftFX.Extended.TwoFactorAuth ReadTwoFactorAuth(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.TwoFactorAuth();
result.Reason = buffer.ReadTwoFactorReason();
result.Text = buffer.ReadAString();
result.Expire = buffer.ReadTime();
return result;
}
public static void WriteTwoFactorAuth(this MemoryBuffer buffer, SoftFX.Extended.TwoFactorAuth arg)
{
buffer.WriteTwoFactorReason(arg.Reason);
buffer.WriteAString(arg.Text);
buffer.WriteTime(arg.Expire);
}
public static SoftFX.Extended.StatusGroupInfo ReadStatusGroupInfo(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.StatusGroupInfo();
result.StatusGroupId = buffer.ReadAString();
result.Status = buffer.ReadSessionStatus();
result.StartTime = buffer.ReadTime();
result.EndTime = buffer.ReadTime();
result.OpenTime = buffer.ReadTime();
result.CloseTime = buffer.ReadTime();
return result;
}
public static void WriteStatusGroupInfo(this MemoryBuffer buffer, SoftFX.Extended.StatusGroupInfo arg)
{
buffer.WriteAString(arg.StatusGroupId);
buffer.WriteSessionStatus(arg.Status);
buffer.WriteTime(arg.StartTime);
buffer.WriteTime(arg.EndTime);
buffer.WriteTime(arg.OpenTime);
buffer.WriteTime(arg.CloseTime);
}
public static SoftFX.Extended.StatusGroupInfo[] ReadStatusGroupInfoArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new SoftFX.Extended.StatusGroupInfo[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadStatusGroupInfo();
}
return result;
}
public static void WriteStatusGroupInfoArray(this MemoryBuffer buffer, SoftFX.Extended.StatusGroupInfo[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WriteStatusGroupInfo(element);
}
}
public static SoftFX.Extended.SessionInfo ReadSessionInfo(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.SessionInfo();
result.TradingSessionId = buffer.ReadAString();
result.Status = buffer.ReadSessionStatus();
result.ServerTimeZoneOffset = buffer.ReadInt32();
result.StartTime = buffer.ReadTime();
result.OpenTime = buffer.ReadTime();
result.CloseTime = buffer.ReadTime();
result.EndTime = buffer.ReadTime();
result.PlatformName = buffer.ReadWString();
result.PlatformCompany = buffer.ReadWString();
result.StatusGroups = buffer.ReadStatusGroupInfoArray();
return result;
}
public static void WriteSessionInfo(this MemoryBuffer buffer, SoftFX.Extended.SessionInfo arg)
{
buffer.WriteAString(arg.TradingSessionId);
buffer.WriteSessionStatus(arg.Status);
buffer.WriteInt32(arg.ServerTimeZoneOffset);
buffer.WriteTime(arg.StartTime);
buffer.WriteTime(arg.OpenTime);
buffer.WriteTime(arg.CloseTime);
buffer.WriteTime(arg.EndTime);
buffer.WriteWString(arg.PlatformName);
buffer.WriteWString(arg.PlatformCompany);
buffer.WriteStatusGroupInfoArray(arg.StatusGroups);
}
public static SoftFX.Extended.SymbolInfo[] ReadSymbolInfoArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new SoftFX.Extended.SymbolInfo[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadSymbolInfo();
}
return result;
}
public static void WriteSymbolInfoArray(this MemoryBuffer buffer, SoftFX.Extended.SymbolInfo[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WriteSymbolInfo(element);
}
}
public static string[] ReadStringArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new string[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadAString();
}
return result;
}
public static void WriteStringArray(this MemoryBuffer buffer, string[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WriteAString(element);
}
}
public static byte[] ReadByteArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new byte[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadUInt8();
}
return result;
}
public static void WriteByteArray(this MemoryBuffer buffer, byte[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WriteUInt8(element);
}
}
public static SoftFX.Extended.AssetInfo ReadAssetInfo(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.AssetInfo();
result.Currency = buffer.ReadAString();
result.Balance = buffer.ReadDouble();
result.LockedAmount = buffer.ReadDouble();
result.TradeAmount = buffer.ReadDouble();
result.CurrencyToUsdConversionRate = buffer.ReadNullDouble();
result.UsdToCurrencyConversionRate = buffer.ReadNullDouble();
result.CurrencyToReportConversionRate = buffer.ReadNullDouble();
result.ReportToCurrencyConversionRate = buffer.ReadNullDouble();
return result;
}
public static void WriteAssetInfo(this MemoryBuffer buffer, SoftFX.Extended.AssetInfo arg)
{
buffer.WriteAString(arg.Currency);
buffer.WriteDouble(arg.Balance);
buffer.WriteDouble(arg.LockedAmount);
buffer.WriteDouble(arg.TradeAmount);
buffer.WriteNullDouble(arg.CurrencyToUsdConversionRate);
buffer.WriteNullDouble(arg.UsdToCurrencyConversionRate);
buffer.WriteNullDouble(arg.CurrencyToReportConversionRate);
buffer.WriteNullDouble(arg.ReportToCurrencyConversionRate);
}
public static SoftFX.Extended.AssetInfo[] ReadAssetInfoArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new SoftFX.Extended.AssetInfo[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadAssetInfo();
}
return result;
}
public static void WriteAssetInfoArray(this MemoryBuffer buffer, SoftFX.Extended.AssetInfo[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WriteAssetInfo(element);
}
}
public static SoftFX.Extended.TradeServerInfo ReadTradeServerInfo(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.TradeServerInfo();
result.CompanyName = buffer.ReadWString();
result.CompanyFullName = buffer.ReadWString();
result.CompanyDescription = buffer.ReadWString();
result.CompanyAddress = buffer.ReadWString();
result.CompanyEmail = buffer.ReadAString();
result.CompanyPhone = buffer.ReadAString();
result.CompanyWebSite = buffer.ReadAString();
result.ServerName = buffer.ReadWString();
result.ServerFullName = buffer.ReadWString();
result.ServerDescription = buffer.ReadWString();
result.ServerAddress = buffer.ReadAString();
result.ServerFixFeedSslPort = buffer.ReadNullInt32();
result.ServerFixTradeSslPort = buffer.ReadNullInt32();
result.ServerWebSocketFeedPort = buffer.ReadNullInt32();
result.ServerWebSocketTradePort = buffer.ReadNullInt32();
result.ServerRestPort = buffer.ReadNullInt32();
return result;
}
public static void WriteTradeServerInfo(this MemoryBuffer buffer, SoftFX.Extended.TradeServerInfo arg)
{
buffer.WriteWString(arg.CompanyName);
buffer.WriteWString(arg.CompanyFullName);
buffer.WriteWString(arg.CompanyDescription);
buffer.WriteWString(arg.CompanyAddress);
buffer.WriteAString(arg.CompanyEmail);
buffer.WriteAString(arg.CompanyPhone);
buffer.WriteAString(arg.CompanyWebSite);
buffer.WriteWString(arg.ServerName);
buffer.WriteWString(arg.ServerFullName);
buffer.WriteWString(arg.ServerDescription);
buffer.WriteAString(arg.ServerAddress);
buffer.WriteNullInt32(arg.ServerFixFeedSslPort);
buffer.WriteNullInt32(arg.ServerFixTradeSslPort);
buffer.WriteNullInt32(arg.ServerWebSocketFeedPort);
buffer.WriteNullInt32(arg.ServerWebSocketTradePort);
buffer.WriteNullInt32(arg.ServerRestPort);
}
public static SoftFX.Extended.AccountInfo ReadAccountInfo(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.AccountInfo();
result.AccountId = buffer.ReadAString();
result.Type = buffer.ReadAccountType();
result.Name = buffer.ReadWString();
result.Email = buffer.ReadAString();
result.Comment = buffer.ReadWString();
result.Currency = buffer.ReadAString();
result.RegistredDate = buffer.ReadNullTime();
result.ModifiedTime = buffer.ReadNullTime();
result.Leverage = buffer.ReadInt32();
result.Balance = buffer.ReadDouble();
result.Margin = buffer.ReadDouble();
result.Equity = buffer.ReadDouble();
result.MarginCallLevel = buffer.ReadDouble();
result.StopOutLevel = buffer.ReadDouble();
result.IsValid = buffer.ReadBoolean();
result.IsReadOnly = buffer.ReadBoolean();
result.IsBlocked = buffer.ReadBoolean();
result.Assets = buffer.ReadAssetInfoArray();
result.SessionsPerAccount = buffer.ReadInt32();
result.RequestsPerSecond = buffer.ReadInt32();
result.ThrottlingMethods = buffer.ReadThrottlingMethodInfoArray();
result.ReportCurrency = buffer.ReadAString();
result.TokenCommissionCurrency = buffer.ReadAString();
result.TokenCommissionCurrencyDiscount = buffer.ReadNullDouble();
result.IsTokenCommissionEnabled = buffer.ReadBoolean();
return result;
}
public static void WriteAccountInfo(this MemoryBuffer buffer, SoftFX.Extended.AccountInfo arg)
{
buffer.WriteAString(arg.AccountId);
buffer.WriteAccountType(arg.Type);
buffer.WriteWString(arg.Name);
buffer.WriteAString(arg.Email);
buffer.WriteWString(arg.Comment);
buffer.WriteAString(arg.Currency);
buffer.WriteNullTime(arg.RegistredDate);
buffer.WriteNullTime(arg.ModifiedTime);
buffer.WriteInt32(arg.Leverage);
buffer.WriteDouble(arg.Balance);
buffer.WriteDouble(arg.Margin);
buffer.WriteDouble(arg.Equity);
buffer.WriteDouble(arg.MarginCallLevel);
buffer.WriteDouble(arg.StopOutLevel);
buffer.WriteBoolean(arg.IsValid);
buffer.WriteBoolean(arg.IsReadOnly);
buffer.WriteBoolean(arg.IsBlocked);
buffer.WriteAssetInfoArray(arg.Assets);
buffer.WriteInt32(arg.SessionsPerAccount);
buffer.WriteInt32(arg.RequestsPerSecond);
buffer.WriteThrottlingMethodInfoArray(arg.ThrottlingMethods);
buffer.WriteAString(arg.ReportCurrency);
buffer.WriteAString(arg.TokenCommissionCurrency);
buffer.WriteNullDouble(arg.TokenCommissionCurrencyDiscount);
buffer.WriteBoolean(arg.IsTokenCommissionEnabled);
}
public static SoftFX.Extended.FxFileChunk ReadFileChunk(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.FxFileChunk();
result.FileId = buffer.ReadAString();
result.FileName = buffer.ReadAString();
result.FileSize = buffer.ReadInt32();
result.ChunkId = buffer.ReadInt32();
result.TotalChunks = buffer.ReadInt32();
result.Data = buffer.ReadByteArray();
return result;
}
public static void WriteFileChunk(this MemoryBuffer buffer, SoftFX.Extended.FxFileChunk arg)
{
buffer.WriteAString(arg.FileId);
buffer.WriteAString(arg.FileName);
buffer.WriteInt32(arg.FileSize);
buffer.WriteInt32(arg.ChunkId);
buffer.WriteInt32(arg.TotalChunks);
buffer.WriteByteArray(arg.Data);
}
public static SoftFX.Extended.Data.FxOrder ReadFxOrder(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.Data.FxOrder();
result.OrderId = buffer.ReadAString();
result.ClientOrderId = buffer.ReadAString();
result.Symbol = buffer.ReadAString();
result.InitialVolume = buffer.ReadDouble();
result.Volume = buffer.ReadNullDouble();
result.MaxVisibleVolume = buffer.ReadNullDouble();
result.Price = buffer.ReadNullDouble();
result.StopPrice = buffer.ReadNullDouble();
result.TakeProfit = buffer.ReadNullDouble();
result.StopLoss = buffer.ReadNullDouble();
result.Commission = buffer.ReadDouble();
result.AgentCommission = buffer.ReadDouble();
result.Swap = buffer.ReadDouble();
result.Profit = buffer.ReadNullDouble();
result.InitialType = buffer.ReadFxOrderType();
result.Type = buffer.ReadFxOrderType();
result.Side = buffer.ReadTradeRecordSide();
result.Expiration = buffer.ReadNullTime();
result.Created = buffer.ReadNullTime();
result.Modified = buffer.ReadNullTime();
result.Comment = buffer.ReadWString();
result.Tag = buffer.ReadWString();
result.Magic = buffer.ReadNullInt32();
result.IsReducedOpenCommission = buffer.ReadBoolean();
result.IsReducedCloseCommission = buffer.ReadBoolean();
result.ImmediateOrCancel = buffer.ReadBoolean();
result.MarketWithSlippage = buffer.ReadBoolean();
result.IOCOverride = buffer.ReadNullBoolean();
result.IFMOverride = buffer.ReadNullBoolean();
result.PrevVolume = buffer.ReadNullDouble();
result.Slippage = buffer.ReadNullDouble();
return result;
}
public static void WriteFxOrder(this MemoryBuffer buffer, SoftFX.Extended.Data.FxOrder arg)
{
buffer.WriteAString(arg.OrderId);
buffer.WriteAString(arg.ClientOrderId);
buffer.WriteAString(arg.Symbol);
buffer.WriteDouble(arg.InitialVolume);
buffer.WriteNullDouble(arg.Volume);
buffer.WriteNullDouble(arg.MaxVisibleVolume);
buffer.WriteNullDouble(arg.Price);
buffer.WriteNullDouble(arg.StopPrice);
buffer.WriteNullDouble(arg.TakeProfit);
buffer.WriteNullDouble(arg.StopLoss);
buffer.WriteDouble(arg.Commission);
buffer.WriteDouble(arg.AgentCommission);
buffer.WriteDouble(arg.Swap);
buffer.WriteNullDouble(arg.Profit);
buffer.WriteFxOrderType(arg.InitialType);
buffer.WriteFxOrderType(arg.Type);
buffer.WriteTradeRecordSide(arg.Side);
buffer.WriteNullTime(arg.Expiration);
buffer.WriteNullTime(arg.Created);
buffer.WriteNullTime(arg.Modified);
buffer.WriteWString(arg.Comment);
buffer.WriteWString(arg.Tag);
buffer.WriteNullInt32(arg.Magic);
buffer.WriteBoolean(arg.IsReducedOpenCommission);
buffer.WriteBoolean(arg.IsReducedCloseCommission);
buffer.WriteBoolean(arg.ImmediateOrCancel);
buffer.WriteBoolean(arg.MarketWithSlippage);
buffer.WriteNullBoolean(arg.IOCOverride);
buffer.WriteNullBoolean(arg.IFMOverride);
buffer.WriteNullDouble(arg.PrevVolume);
buffer.WriteNullDouble(arg.Slippage);
}
public static SoftFX.Extended.Data.FxOrder[] ReadFxOrderArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new SoftFX.Extended.Data.FxOrder[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadFxOrder();
}
return result;
}
public static void WriteFxOrderArray(this MemoryBuffer buffer, SoftFX.Extended.Data.FxOrder[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WriteFxOrder(element);
}
}
public static SoftFX.Extended.Bar ReadBar(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.Bar();
result.Open = buffer.ReadDouble();
result.Close = buffer.ReadDouble();
result.High = buffer.ReadDouble();
result.Low = buffer.ReadDouble();
result.Volume = buffer.ReadDouble();
result.From = buffer.ReadTime();
return result;
}
public static void WriteBar(this MemoryBuffer buffer, SoftFX.Extended.Bar arg)
{
buffer.WriteDouble(arg.Open);
buffer.WriteDouble(arg.Close);
buffer.WriteDouble(arg.High);
buffer.WriteDouble(arg.Low);
buffer.WriteDouble(arg.Volume);
buffer.WriteTime(arg.From);
}
public static SoftFX.Extended.QuoteEntry ReadQuoteEntry(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.QuoteEntry();
result.Price = buffer.ReadDouble();
result.Volume = buffer.ReadDouble();
return result;
}
public static void WriteQuoteEntry(this MemoryBuffer buffer, SoftFX.Extended.QuoteEntry arg)
{
buffer.WriteDouble(arg.Price);
buffer.WriteDouble(arg.Volume);
}
public static SoftFX.Extended.QuoteEntry[] ReadQuoteEntryArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new SoftFX.Extended.QuoteEntry[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadQuoteEntry();
}
return result;
}
public static void WriteQuoteEntryArray(this MemoryBuffer buffer, SoftFX.Extended.QuoteEntry[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WriteQuoteEntry(element);
}
}
public static SoftFX.Extended.Quote ReadQuote(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.Quote();
result.Symbol = buffer.ReadAString();
result.CreatingTime = buffer.ReadTime();
result.Bids = buffer.ReadQuoteEntryArray();
result.Asks = buffer.ReadQuoteEntryArray();
result.Id = buffer.ReadAString();
result.IndicativeTick = buffer.ReadBoolean();
return result;
}
public static void WriteQuote(this MemoryBuffer buffer, SoftFX.Extended.Quote arg)
{
buffer.WriteAString(arg.Symbol);
buffer.WriteTime(arg.CreatingTime);
buffer.WriteQuoteEntryArray(arg.Bids);
buffer.WriteQuoteEntryArray(arg.Asks);
buffer.WriteAString(arg.Id);
buffer.WriteBoolean(arg.IndicativeTick);
}
public static SoftFX.Extended.Quote[] ReadQuoteArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new SoftFX.Extended.Quote[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadQuote();
}
return result;
}
public static void WriteQuoteArray(this MemoryBuffer buffer, SoftFX.Extended.Quote[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WriteQuote(element);
}
}
public static SoftFX.Extended.Bar[] ReadBarArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new SoftFX.Extended.Bar[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadBar();
}
return result;
}
public static void WriteBarArray(this MemoryBuffer buffer, SoftFX.Extended.Bar[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WriteBar(element);
}
}
public static SoftFX.Extended.Core.FxMessage ReadMessage(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.Core.FxMessage();
result.Type = buffer.ReadInt32();
result.SendingTime = buffer.ReadNullTime();
result.ReceivingTime = buffer.ReadNullTime();
result.Data = buffer.ReadLocalPointer();
return result;
}
public static void WriteMessage(this MemoryBuffer buffer, SoftFX.Extended.Core.FxMessage arg)
{
buffer.WriteInt32(arg.Type);
buffer.WriteNullTime(arg.SendingTime);
buffer.WriteNullTime(arg.ReceivingTime);
buffer.WriteLocalPointer(arg.Data);
}
public static SoftFX.Extended.PosReportType ReadPositionReportType(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.PosReportType)buffer.ReadInt32();
return result;
}
public static void WritePositionReportType(this MemoryBuffer buffer, SoftFX.Extended.PosReportType arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.Position ReadPosition(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.Position();
result.Symbol = buffer.ReadAString();
result.SettlementPrice = buffer.ReadDouble();
result.BuyAmount = buffer.ReadDouble();
result.SellAmount = buffer.ReadDouble();
result.Commission = buffer.ReadDouble();
result.AgentCommission = buffer.ReadDouble();
result.Swap = buffer.ReadDouble();
result.Profit = buffer.ReadNullDouble();
result.BuyPrice = buffer.ReadNullDouble();
result.SellPrice = buffer.ReadNullDouble();
result.PosModified = buffer.ReadNullTime();
result.PosID = buffer.ReadAString();
result.Margin = buffer.ReadNullDouble();
result.CurrentBestAsk = buffer.ReadNullDouble();
result.CurrentBestBid = buffer.ReadNullDouble();
result.PosReportType = buffer.ReadPositionReportType();
return result;
}
public static void WritePosition(this MemoryBuffer buffer, SoftFX.Extended.Position arg)
{
buffer.WriteAString(arg.Symbol);
buffer.WriteDouble(arg.SettlementPrice);
buffer.WriteDouble(arg.BuyAmount);
buffer.WriteDouble(arg.SellAmount);
buffer.WriteDouble(arg.Commission);
buffer.WriteDouble(arg.AgentCommission);
buffer.WriteDouble(arg.Swap);
buffer.WriteNullDouble(arg.Profit);
buffer.WriteNullDouble(arg.BuyPrice);
buffer.WriteNullDouble(arg.SellPrice);
buffer.WriteNullTime(arg.PosModified);
buffer.WriteAString(arg.PosID);
buffer.WriteNullDouble(arg.Margin);
buffer.WriteNullDouble(arg.CurrentBestAsk);
buffer.WriteNullDouble(arg.CurrentBestBid);
buffer.WritePositionReportType(arg.PosReportType);
}
public static SoftFX.Extended.Position[] ReadPositionArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new SoftFX.Extended.Position[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadPosition();
}
return result;
}
public static void WritePositionArray(this MemoryBuffer buffer, SoftFX.Extended.Position[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WritePosition(element);
}
}
public static SoftFX.Extended.Reports.TradeTransactionReportType ReadTradeTransactionReportType(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.Reports.TradeTransactionReportType)buffer.ReadInt32();
return result;
}
public static void WriteTradeTransactionReportType(this MemoryBuffer buffer, SoftFX.Extended.Reports.TradeTransactionReportType arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.Reports.TradeTransactionReason ReadTradeTransactionReason(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.Reports.TradeTransactionReason)buffer.ReadInt32();
return result;
}
public static void WriteTradeTransactionReason(this MemoryBuffer buffer, SoftFX.Extended.Reports.TradeTransactionReason arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.Reports.TradeTransactionReport ReadTradeTransactionReport(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.Reports.TradeTransactionReport();
result.TradeTransactionReportType = buffer.ReadTradeTransactionReportType();
result.TradeTransactionReason = buffer.ReadTradeTransactionReason();
result.AccountBalance = buffer.ReadDouble();
result.TransactionAmount = buffer.ReadDouble();
result.TransactionCurrency = buffer.ReadAString();
result.Id = buffer.ReadAString();
result.ClientId = buffer.ReadAString();
result.Quantity = buffer.ReadDouble();
result.MaxVisibleQuantity = buffer.ReadNullDouble();
result.LeavesQuantity = buffer.ReadDouble();
result.Price = buffer.ReadDouble();
result.StopPrice = buffer.ReadDouble();
result.InitialTradeRecordType = buffer.ReadTradeRecordType();
result.TradeRecordType = buffer.ReadTradeRecordType();
result.TradeRecordSide = buffer.ReadTradeRecordSide();
result.Symbol = buffer.ReadAString();
result.Comment = buffer.ReadWString();
result.Tag = buffer.ReadWString();
result.Magic = buffer.ReadNullInt32();
result.IsReducedOpenCommission = buffer.ReadBoolean();
result.IsReducedCloseCommission = buffer.ReadBoolean();
result.ImmediateOrCancel = buffer.ReadBoolean();
result.MarketWithSlippage = buffer.ReadBoolean();
result.ReqOpenPrice = buffer.ReadNullDouble();
result.ReqOpenQuantity = buffer.ReadNullDouble();
result.ReqClosePrice = buffer.ReadNullDouble();
result.ReqCloseQuantity = buffer.ReadNullDouble();
result.OrderCreated = buffer.ReadTime();
result.OrderModified = buffer.ReadTime();
result.PositionId = buffer.ReadAString();
result.PositionById = buffer.ReadAString();
result.PositionOpened = buffer.ReadTime();
result.PosOpenReqPrice = buffer.ReadDouble();
result.PosOpenPrice = buffer.ReadDouble();
result.PositionQuantity = buffer.ReadDouble();
result.PositionLastQuantity = buffer.ReadDouble();
result.PositionLeavesQuantity = buffer.ReadDouble();
result.PositionCloseRequestedPrice = buffer.ReadDouble();
result.PositionClosePrice = buffer.ReadDouble();
result.PositionClosed = buffer.ReadTime();
result.PositionModified = buffer.ReadTime();
result.PosRemainingSide = buffer.ReadTradeRecordSide();
result.PosRemainingPrice = buffer.ReadNullDouble();
result.Commission = buffer.ReadDouble();
result.AgentCommission = buffer.ReadDouble();
result.Swap = buffer.ReadDouble();
result.CommCurrency = buffer.ReadAString();
result.StopLoss = buffer.ReadDouble();
result.TakeProfit = buffer.ReadDouble();
result.NextStreamPositionId = buffer.ReadAString();
result.TransactionTime = buffer.ReadTime();
result.OrderFillPrice = buffer.ReadNullDouble();
result.OrderLastFillAmount = buffer.ReadNullDouble();
result.OpenConversionRate = buffer.ReadNullDouble();
result.CloseConversionRate = buffer.ReadNullDouble();
result.ActionId = buffer.ReadInt32();
result.Expiration = buffer.ReadNullTime();
result.SrcAssetCurrency = buffer.ReadAString();
result.SrcAssetAmount = buffer.ReadNullDouble();
result.SrcAssetMovement = buffer.ReadNullDouble();
result.DstAssetCurrency = buffer.ReadAString();
result.DstAssetAmount = buffer.ReadNullDouble();
result.DstAssetMovement = buffer.ReadNullDouble();
result.MarginCurrencyToUsdConversionRate = buffer.ReadNullDouble();
result.UsdToMarginCurrencyConversionRate = buffer.ReadNullDouble();
result.MarginCurrency = buffer.ReadAString();
result.ProfitCurrencyToUsdConversionRate = buffer.ReadNullDouble();
result.UsdToProfitCurrencyConversionRate = buffer.ReadNullDouble();
result.ProfitCurrency = buffer.ReadAString();
result.SrcAssetToUsdConversionRate = buffer.ReadNullDouble();
result.UsdToSrcAssetConversionRate = buffer.ReadNullDouble();
result.DstAssetToUsdConversionRate = buffer.ReadNullDouble();
result.UsdToDstAssetConversionRate = buffer.ReadNullDouble();
result.MinCommissionCurrency = buffer.ReadAString();
result.MinCommissionConversionRate = buffer.ReadNullDouble();
result.Slippage = buffer.ReadNullDouble();
result.MarginCurrencyToReportConversionRate = buffer.ReadNullDouble();
result.ReportToMarginCurrencyConversionRate = buffer.ReadNullDouble();
result.ProfitCurrencyToReportConversionRate = buffer.ReadNullDouble();
result.ReportToProfitCurrencyConversionRate = buffer.ReadNullDouble();
result.SrcAssetToReportConversionRate = buffer.ReadNullDouble();
result.ReportToSrcAssetConversionRate = buffer.ReadNullDouble();
result.DstAssetToReportConversionRate = buffer.ReadNullDouble();
result.ReportToDstAssetConversionRate = buffer.ReadNullDouble();
result.ReportCurrency = buffer.ReadAString();
result.TokenCommissionCurrency = buffer.ReadAString();
result.TokenCommissionCurrencyDiscount = buffer.ReadNullDouble();
result.TokenCommissionConversionRate = buffer.ReadNullDouble();
return result;
}
public static void WriteTradeTransactionReport(this MemoryBuffer buffer, SoftFX.Extended.Reports.TradeTransactionReport arg)
{
buffer.WriteTradeTransactionReportType(arg.TradeTransactionReportType);
buffer.WriteTradeTransactionReason(arg.TradeTransactionReason);
buffer.WriteDouble(arg.AccountBalance);
buffer.WriteDouble(arg.TransactionAmount);
buffer.WriteAString(arg.TransactionCurrency);
buffer.WriteAString(arg.Id);
buffer.WriteAString(arg.ClientId);
buffer.WriteDouble(arg.Quantity);
buffer.WriteNullDouble(arg.MaxVisibleQuantity);
buffer.WriteDouble(arg.LeavesQuantity);
buffer.WriteDouble(arg.Price);
buffer.WriteDouble(arg.StopPrice);
buffer.WriteTradeRecordType(arg.InitialTradeRecordType);
buffer.WriteTradeRecordType(arg.TradeRecordType);
buffer.WriteTradeRecordSide(arg.TradeRecordSide);
buffer.WriteAString(arg.Symbol);
buffer.WriteWString(arg.Comment);
buffer.WriteWString(arg.Tag);
buffer.WriteNullInt32(arg.Magic);
buffer.WriteBoolean(arg.IsReducedOpenCommission);
buffer.WriteBoolean(arg.IsReducedCloseCommission);
buffer.WriteBoolean(arg.ImmediateOrCancel);
buffer.WriteBoolean(arg.MarketWithSlippage);
buffer.WriteNullDouble(arg.ReqOpenPrice);
buffer.WriteNullDouble(arg.ReqOpenQuantity);
buffer.WriteNullDouble(arg.ReqClosePrice);
buffer.WriteNullDouble(arg.ReqCloseQuantity);
buffer.WriteTime(arg.OrderCreated);
buffer.WriteTime(arg.OrderModified);
buffer.WriteAString(arg.PositionId);
buffer.WriteAString(arg.PositionById);
buffer.WriteTime(arg.PositionOpened);
buffer.WriteDouble(arg.PosOpenReqPrice);
buffer.WriteDouble(arg.PosOpenPrice);
buffer.WriteDouble(arg.PositionQuantity);
buffer.WriteDouble(arg.PositionLastQuantity);
buffer.WriteDouble(arg.PositionLeavesQuantity);
buffer.WriteDouble(arg.PositionCloseRequestedPrice);
buffer.WriteDouble(arg.PositionClosePrice);
buffer.WriteTime(arg.PositionClosed);
buffer.WriteTime(arg.PositionModified);
buffer.WriteTradeRecordSide(arg.PosRemainingSide);
buffer.WriteNullDouble(arg.PosRemainingPrice);
buffer.WriteDouble(arg.Commission);
buffer.WriteDouble(arg.AgentCommission);
buffer.WriteDouble(arg.Swap);
buffer.WriteAString(arg.CommCurrency);
buffer.WriteDouble(arg.StopLoss);
buffer.WriteDouble(arg.TakeProfit);
buffer.WriteAString(arg.NextStreamPositionId);
buffer.WriteTime(arg.TransactionTime);
buffer.WriteNullDouble(arg.OrderFillPrice);
buffer.WriteNullDouble(arg.OrderLastFillAmount);
buffer.WriteNullDouble(arg.OpenConversionRate);
buffer.WriteNullDouble(arg.CloseConversionRate);
buffer.WriteInt32(arg.ActionId);
buffer.WriteNullTime(arg.Expiration);
buffer.WriteAString(arg.SrcAssetCurrency);
buffer.WriteNullDouble(arg.SrcAssetAmount);
buffer.WriteNullDouble(arg.SrcAssetMovement);
buffer.WriteAString(arg.DstAssetCurrency);
buffer.WriteNullDouble(arg.DstAssetAmount);
buffer.WriteNullDouble(arg.DstAssetMovement);
buffer.WriteNullDouble(arg.MarginCurrencyToUsdConversionRate);
buffer.WriteNullDouble(arg.UsdToMarginCurrencyConversionRate);
buffer.WriteAString(arg.MarginCurrency);
buffer.WriteNullDouble(arg.ProfitCurrencyToUsdConversionRate);
buffer.WriteNullDouble(arg.UsdToProfitCurrencyConversionRate);
buffer.WriteAString(arg.ProfitCurrency);
buffer.WriteNullDouble(arg.SrcAssetToUsdConversionRate);
buffer.WriteNullDouble(arg.UsdToSrcAssetConversionRate);
buffer.WriteNullDouble(arg.DstAssetToUsdConversionRate);
buffer.WriteNullDouble(arg.UsdToDstAssetConversionRate);
buffer.WriteAString(arg.MinCommissionCurrency);
buffer.WriteNullDouble(arg.MinCommissionConversionRate);
buffer.WriteNullDouble(arg.Slippage);
buffer.WriteNullDouble(arg.MarginCurrencyToReportConversionRate);
buffer.WriteNullDouble(arg.ReportToMarginCurrencyConversionRate);
buffer.WriteNullDouble(arg.ProfitCurrencyToReportConversionRate);
buffer.WriteNullDouble(arg.ReportToProfitCurrencyConversionRate);
buffer.WriteNullDouble(arg.SrcAssetToReportConversionRate);
buffer.WriteNullDouble(arg.ReportToSrcAssetConversionRate);
buffer.WriteNullDouble(arg.DstAssetToReportConversionRate);
buffer.WriteNullDouble(arg.ReportToDstAssetConversionRate);
buffer.WriteAString(arg.ReportCurrency);
buffer.WriteAString(arg.TokenCommissionCurrency);
buffer.WriteNullDouble(arg.TokenCommissionCurrencyDiscount);
buffer.WriteNullDouble(arg.TokenCommissionConversionRate);
}
public static SoftFX.Extended.Reports.DailyAccountSnapshotReport ReadDailyAccountSnapshotReport(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.Reports.DailyAccountSnapshotReport();
result.Timestamp = buffer.ReadTime();
result.AccountId = buffer.ReadAString();
result.Type = buffer.ReadAccountType();
result.BalanceCurrency = buffer.ReadAString();
result.Leverage = buffer.ReadInt32();
result.Balance = buffer.ReadDouble();
result.Margin = buffer.ReadDouble();
result.MarginLevel = buffer.ReadDouble();
result.Equity = buffer.ReadDouble();
result.Swap = buffer.ReadDouble();
result.Profit = buffer.ReadDouble();
result.Commission = buffer.ReadDouble();
result.AgentCommission = buffer.ReadDouble();
result.IsValid = buffer.ReadBoolean();
result.IsReadOnly = buffer.ReadBoolean();
result.IsBlocked = buffer.ReadBoolean();
result.BalanceCurrencyToUsdConversionRate = buffer.ReadNullDouble();
result.UsdToBalanceCurrencyConversionRate = buffer.ReadNullDouble();
result.ProfitCurrencyToUsdConversionRate = buffer.ReadNullDouble();
result.UsdToProfitCurrencyConversionRate = buffer.ReadNullDouble();
result.BalanceCurrencyToReportConversionRate = buffer.ReadNullDouble();
result.ReportToBalanceCurrencyConversionRate = buffer.ReadNullDouble();
result.ProfitCurrencyToReportConversionRate = buffer.ReadNullDouble();
result.ReportToProfitCurrencyConversionRate = buffer.ReadNullDouble();
result.Assets = buffer.ReadAssetInfoArray();
result.Positions = buffer.ReadPositionArray();
result.ReportCurrency = buffer.ReadAString();
result.TokenCommissionCurrency = buffer.ReadAString();
result.TokenCommissionCurrencyDiscount = buffer.ReadNullDouble();
result.IsTokenCommissionEnabled = buffer.ReadBoolean();
return result;
}
public static void WriteDailyAccountSnapshotReport(this MemoryBuffer buffer, SoftFX.Extended.Reports.DailyAccountSnapshotReport arg)
{
buffer.WriteTime(arg.Timestamp);
buffer.WriteAString(arg.AccountId);
buffer.WriteAccountType(arg.Type);
buffer.WriteAString(arg.BalanceCurrency);
buffer.WriteInt32(arg.Leverage);
buffer.WriteDouble(arg.Balance);
buffer.WriteDouble(arg.Margin);
buffer.WriteDouble(arg.MarginLevel);
buffer.WriteDouble(arg.Equity);
buffer.WriteDouble(arg.Swap);
buffer.WriteDouble(arg.Profit);
buffer.WriteDouble(arg.Commission);
buffer.WriteDouble(arg.AgentCommission);
buffer.WriteBoolean(arg.IsValid);
buffer.WriteBoolean(arg.IsReadOnly);
buffer.WriteBoolean(arg.IsBlocked);
buffer.WriteNullDouble(arg.BalanceCurrencyToUsdConversionRate);
buffer.WriteNullDouble(arg.UsdToBalanceCurrencyConversionRate);
buffer.WriteNullDouble(arg.ProfitCurrencyToUsdConversionRate);
buffer.WriteNullDouble(arg.UsdToProfitCurrencyConversionRate);
buffer.WriteNullDouble(arg.BalanceCurrencyToReportConversionRate);
buffer.WriteNullDouble(arg.ReportToBalanceCurrencyConversionRate);
buffer.WriteNullDouble(arg.ProfitCurrencyToReportConversionRate);
buffer.WriteNullDouble(arg.ReportToProfitCurrencyConversionRate);
buffer.WriteAssetInfoArray(arg.Assets);
buffer.WritePositionArray(arg.Positions);
buffer.WriteAString(arg.ReportCurrency);
buffer.WriteAString(arg.TokenCommissionCurrency);
buffer.WriteNullDouble(arg.TokenCommissionCurrencyDiscount);
buffer.WriteBoolean(arg.IsTokenCommissionEnabled);
}
public static SoftFX.Extended.ClosePositionResult ReadClosePositionResult(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.ClosePositionResult();
result.ExecutedVolume = buffer.ReadDouble();
result.ExecutedPrice = buffer.ReadDouble();
result.Sucess = buffer.ReadBoolean();
return result;
}
public static void WriteClosePositionResult(this MemoryBuffer buffer, SoftFX.Extended.ClosePositionResult arg)
{
buffer.WriteDouble(arg.ExecutedVolume);
buffer.WriteDouble(arg.ExecutedPrice);
buffer.WriteBoolean(arg.Sucess);
}
public static SoftFX.Extended.ExecutionReport ReadExecutionReport(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.ExecutionReport();
result.OrderId = buffer.ReadAString();
result.ClientOrderId = buffer.ReadAString();
result.TradeRequestId = buffer.ReadAString();
result.OrderStatus = buffer.ReadOrderStatus();
result.ExecutionType = buffer.ReadExecutionType();
result.Symbol = buffer.ReadAString();
result.ExecutedVolume = buffer.ReadDouble();
result.InitialVolume = buffer.ReadNullDouble();
result.LeavesVolume = buffer.ReadDouble();
result.MaxVisibleVolume = buffer.ReadNullDouble();
result.TradeAmount = buffer.ReadNullDouble();
result.Commission = buffer.ReadDouble();
result.AgentCommission = buffer.ReadDouble();
result.Swap = buffer.ReadDouble();
result.InitialOrderType = buffer.ReadTradeRecordType();
result.OrderType = buffer.ReadTradeRecordType();
result.OrderSide = buffer.ReadTradeRecordSide();
result.AveragePrice = buffer.ReadNullDouble();
result.Price = buffer.ReadNullDouble();
result.StopPrice = buffer.ReadNullDouble();
result.TradePrice = buffer.ReadDouble();
result.Expiration = buffer.ReadNullTime();
result.Created = buffer.ReadNullTime();
result.Modified = buffer.ReadNullTime();
result.RejectReason = buffer.ReadRejectReason();
result.TakeProfit = buffer.ReadNullDouble();
result.StopLoss = buffer.ReadNullDouble();
result.Text = buffer.ReadAString();
result.Comment = buffer.ReadWString();
result.Tag = buffer.ReadWString();
result.Magic = buffer.ReadNullInt32();
result.ClosePositionRequestId = buffer.ReadAString();
result.Assets = buffer.ReadAssetInfoArray();
result.Balance = buffer.ReadDouble();
result.IsReducedOpenCommission = buffer.ReadBoolean();
result.IsReducedCloseCommission = buffer.ReadBoolean();
result.ImmediateOrCancel = buffer.ReadBoolean();
result.MarketWithSlippage = buffer.ReadBoolean();
result.ReqOpenPrice = buffer.ReadNullDouble();
result.ReqOpenVolume = buffer.ReadNullDouble();
result.Slippage = buffer.ReadNullDouble();
return result;
}
public static void WriteExecutionReport(this MemoryBuffer buffer, SoftFX.Extended.ExecutionReport arg)
{
buffer.WriteAString(arg.OrderId);
buffer.WriteAString(arg.ClientOrderId);
buffer.WriteAString(arg.TradeRequestId);
buffer.WriteOrderStatus(arg.OrderStatus);
buffer.WriteExecutionType(arg.ExecutionType);
buffer.WriteAString(arg.Symbol);
buffer.WriteDouble(arg.ExecutedVolume);
buffer.WriteNullDouble(arg.InitialVolume);
buffer.WriteDouble(arg.LeavesVolume);
buffer.WriteNullDouble(arg.MaxVisibleVolume);
buffer.WriteNullDouble(arg.TradeAmount);
buffer.WriteDouble(arg.Commission);
buffer.WriteDouble(arg.AgentCommission);
buffer.WriteDouble(arg.Swap);
buffer.WriteTradeRecordType(arg.InitialOrderType);
buffer.WriteTradeRecordType(arg.OrderType);
buffer.WriteTradeRecordSide(arg.OrderSide);
buffer.WriteNullDouble(arg.AveragePrice);
buffer.WriteNullDouble(arg.Price);
buffer.WriteNullDouble(arg.StopPrice);
buffer.WriteDouble(arg.TradePrice);
buffer.WriteNullTime(arg.Expiration);
buffer.WriteNullTime(arg.Created);
buffer.WriteNullTime(arg.Modified);
buffer.WriteRejectReason(arg.RejectReason);
buffer.WriteNullDouble(arg.TakeProfit);
buffer.WriteNullDouble(arg.StopLoss);
buffer.WriteAString(arg.Text);
buffer.WriteWString(arg.Comment);
buffer.WriteWString(arg.Tag);
buffer.WriteNullInt32(arg.Magic);
buffer.WriteAString(arg.ClosePositionRequestId);
buffer.WriteAssetInfoArray(arg.Assets);
buffer.WriteDouble(arg.Balance);
buffer.WriteBoolean(arg.IsReducedOpenCommission);
buffer.WriteBoolean(arg.IsReducedCloseCommission);
buffer.WriteBoolean(arg.ImmediateOrCancel);
buffer.WriteBoolean(arg.MarketWithSlippage);
buffer.WriteNullDouble(arg.ReqOpenPrice);
buffer.WriteNullDouble(arg.ReqOpenVolume);
buffer.WriteNullDouble(arg.Slippage);
}
public static SoftFX.Extended.CurrencyInfo ReadCurrencyInfo(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.CurrencyInfo();
result.Name = buffer.ReadAString();
result.Description = buffer.ReadWString();
result.SortOrder = buffer.ReadInt32();
result.Precision = buffer.ReadInt32();
return result;
}
public static void WriteCurrencyInfo(this MemoryBuffer buffer, SoftFX.Extended.CurrencyInfo arg)
{
buffer.WriteAString(arg.Name);
buffer.WriteWString(arg.Description);
buffer.WriteInt32(arg.SortOrder);
buffer.WriteInt32(arg.Precision);
}
public static SoftFX.Extended.CurrencyInfo[] ReadCurrencyInfoArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new SoftFX.Extended.CurrencyInfo[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadCurrencyInfo();
}
return result;
}
public static void WriteCurrencyInfoArray(this MemoryBuffer buffer, SoftFX.Extended.CurrencyInfo[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WriteCurrencyInfo(element);
}
}
public static SoftFX.Extended.ThrottlingMethod ReadFxThrottlingMethod(this MemoryBuffer buffer)
{
var result = (SoftFX.Extended.ThrottlingMethod)buffer.ReadInt32();
return result;
}
public static void WriteFxThrottlingMethod(this MemoryBuffer buffer, SoftFX.Extended.ThrottlingMethod arg)
{
buffer.WriteInt32((int)arg);
}
public static SoftFX.Extended.ThrottlingMethodInfo ReadThrottlingMethodInfo(this MemoryBuffer buffer)
{
var result = new SoftFX.Extended.ThrottlingMethodInfo();
result.Method = buffer.ReadFxThrottlingMethod();
result.RequestsPerSecond = buffer.ReadInt32();
return result;
}
public static void WriteThrottlingMethodInfo(this MemoryBuffer buffer, SoftFX.Extended.ThrottlingMethodInfo arg)
{
buffer.WriteFxThrottlingMethod(arg.Method);
buffer.WriteInt32(arg.RequestsPerSecond);
}
public static SoftFX.Extended.ThrottlingMethodInfo[] ReadThrottlingMethodInfoArray(this MemoryBuffer buffer)
{
int length = buffer.ReadCount();
var result = new SoftFX.Extended.ThrottlingMethodInfo[length];
for(int index = 0; index < length; ++index)
{
result[index] = buffer.ReadThrottlingMethodInfo();
}
return result;
}
public static void WriteThrottlingMethodInfoArray(this MemoryBuffer buffer, SoftFX.Extended.ThrottlingMethodInfo[] arg)
{
buffer.WriteInt32(arg.Length);
foreach(var element in arg)
{
buffer.WriteThrottlingMethodInfo(element);
}
}
public static void Throw(System.Int32 status, MemoryBuffer buffer)
{
if(status >= 0)
{
return;
}
if(MagicNumbers.LRP_EXCEPTION != status)
{
throw new System.Exception("Unexpected exception has been encountered");
}
System.Int32 _id = buffer.ReadInt32();
if(0 == _id)
{
throw ReadArgumentNullException(buffer);
}
if(1 == _id)
{
throw ReadArgumentException(buffer);
}
if(2 == _id)
{
throw ReadInvalidHandleException(buffer);
}
if(3 == _id)
{
throw ReadRejectException(buffer);
}
if(4 == _id)
{
throw ReadTimeoutException(buffer);
}
if(5 == _id)
{
throw ReadSendException(buffer);
}
if(6 == _id)
{
throw ReadLogoutException(buffer);
}
if(7 == _id)
{
throw ReadUnsupportedFeatureException(buffer);
}
if(8 == _id)
{
throw ReadRuntimeException(buffer);
}
System.String _message = buffer.ReadAString();
throw new System.Exception(_message);
}
}
}
| |
using System;
using System.Reflection;
using IBatisNet.Common.Test.Domain;
using IBatisNet.Common.Utilities;
using IBatisNet.Common.Utilities.Objects.Members;
using NUnit.Framework;
namespace IBatisNet.Common.Test.NUnit.CommonTests.Utilities
{
/// <summary>
/// Summary description for FieldAccessorTest.
/// </summary>
[TestFixture]
public abstract class BaseMemberTest
{
protected ISetAccessorFactory factorySet = null;
protected IGetAccessorFactory factoryGet = null;
protected ISetAccessor intSetAccessor = null;
protected IGetAccessor intGetAccessor = null;
protected ISetAccessor longSetAccessor = null;
protected IGetAccessor longGetAccessor = null;
protected ISetAccessor sbyteSetAccessor = null;
protected IGetAccessor sbyteGetAccessor = null;
protected ISetAccessor datetimeSetAccessor = null;
protected IGetAccessor datetimeGetAccessor = null;
protected ISetAccessor decimalSetAccessor = null;
protected IGetAccessor decimalGetAccessor = null;
protected ISetAccessor byteSetAccessor = null;
protected IGetAccessor byteGetAccessor = null;
protected ISetAccessor stringSetAccessor = null;
protected IGetAccessor stringGetAccessor = null;
protected ISetAccessor charSetAccessor = null;
protected IGetAccessor charGetAccessor = null;
protected ISetAccessor shortSetAccessor = null;
protected IGetAccessor shortGetAccessor = null;
protected ISetAccessor ushortSetAccessor = null;
protected IGetAccessor ushortGetAccessor = null;
protected ISetAccessor uintSetAccessor = null;
protected IGetAccessor uintGetAccessor = null;
protected ISetAccessor ulongSetAccessor = null;
protected IGetAccessor ulongGetAccessor = null;
protected ISetAccessor boolSetAccessor = null;
protected IGetAccessor boolGetAccessor = null;
protected ISetAccessor doubleSetAccessor = null;
protected IGetAccessor doubleGetAccessor = null;
protected ISetAccessor floatSetAccessor = null;
protected IGetAccessor floatGetAccessor = null;
protected ISetAccessor guidSetAccessor = null;
protected IGetAccessor guidGetAccessor = null;
protected ISetAccessor timespanSetAccessor = null;
protected IGetAccessor timespanGetAccessor = null;
protected ISetAccessor accountSetAccessor = null;
protected IGetAccessor accountGetAccessor = null;
protected ISetAccessor enumSetAccessor = null;
protected IGetAccessor enumGetAccessor = null;
#if dotnet2
protected ISetAccessor nullableSetAccessor = null;
protected IGetAccessor nullableGetAccessor = null;
#endif
/// <summary>
/// Initialize an sqlMap
/// </summary>
[TestFixtureSetUp]
protected virtual void SetUpFixture()
{
factoryGet = new GetAccessorFactory(true);
factorySet = new SetAccessorFactory(true);
}
/// <summary>
/// Dispose the SqlMap
/// </summary>
[TestFixtureTearDown]
protected virtual void TearDownFixture()
{
factoryGet = null;
factorySet = null;
}
/// <summary>
/// Test setting null on integer property.
/// </summary>
[Test]
public void TestSetNullOnIntegerProperty()
{
Property prop = new Property();
prop.Int = -99;
// Property accessor
intSetAccessor.Set(prop, null);
Assert.AreEqual(0, prop.Int);
}
/// <summary>
/// Test setting an integer property.
/// </summary>
[Test]
public void TestSetInteger()
{
Property prop = new Property();
prop.Int = -99;
// Property accessor
int test = 57;
intSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.Int);
}
/// <summary>
/// Test getting an integer property.
/// </summary>
[Test]
public void TestGetInteger()
{
int test = -99;
Property prop = new Property();
prop.Int = test;
// Property accessor
Assert.AreEqual(test, intGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on Long property.
/// </summary>
[Test]
public void TestSetNullOnLongProperty()
{
Property prop = new Property();
prop.Long = 78945566664213223;
// Property accessor
longSetAccessor.Set(prop, null);
Assert.AreEqual((long)0, prop.Long);
}
/// <summary>
/// Test setting an Long property.
/// </summary>
[Test]
public void TestSetLong()
{
Property prop = new Property();
prop.Long = 78945566664213223;
// Property accessor
long test = 123456789987456;
longSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.Long);
}
/// <summary>
/// Test getting an long property.
/// </summary>
[Test]
public void TestGetLong()
{
long test = 78945566664213223;
Property prop = new Property();
prop.Long = test;
// Property accessor
Assert.AreEqual(test, longGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on sbyte property.
/// </summary>
[Test]
public void TestSetNullOnSbyteProperty()
{
Property prop = new Property();
prop.SByte = 78;
// Property accessor
sbyteSetAccessor.Set(prop, null);
Assert.AreEqual((sbyte)0, prop.SByte);
}
/// <summary>
/// Test setting an sbyte property.
/// </summary>
[Test]
public void TestSetSbyte()
{
Property prop = new Property();
prop.SByte = 78;
// Property accessor
sbyte test = 19;
sbyteSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.SByte);
}
/// <summary>
/// Test getting an sbyte property.
/// </summary>
[Test]
public void TestGetSbyte()
{
sbyte test = 78;
Property prop = new Property();
prop.SByte = test;
// Property accessor
Assert.AreEqual(test, sbyteGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on String property.
/// </summary>
[Test]
public void TestSetNullOnStringProperty()
{
Property prop = new Property();
prop.String = "abc";
// Property accessor
stringSetAccessor.Set(prop, null);
Assert.IsNull(prop.String);
}
/// <summary>
/// Test setting an String property.
/// </summary>
[Test]
public void TestSetString()
{
Property prop = new Property();
prop.String = "abc";
// Property accessor
string test = "wxc";
stringSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.String);
}
/// <summary>
/// Test getting an String property.
/// </summary>
[Test]
public void TestGetString()
{
string test = "abc";
Property prop = new Property();
prop.String = test;
// Property accessor
Assert.AreEqual(test, stringGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on DateTime property.
/// </summary>
[Test]
public void TestSetNullOnDateTimeProperty()
{
Property prop = new Property();
prop.DateTime = DateTime.Now;
// Property accessor
datetimeSetAccessor.Set(prop, null);
Assert.AreEqual(DateTime.MinValue, prop.DateTime);
}
/// <summary>
/// Test setting an DateTime property.
/// </summary>
[Test]
public void TestSetDateTime()
{
Property prop = new Property();
prop.DateTime = DateTime.Now;
// Property accessor
DateTime test = new DateTime(1987,11,25);
datetimeSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.DateTime);
}
/// <summary>
/// Test getting an DateTime property.
/// </summary>
[Test]
public void TestGetDateTime()
{
DateTime test = new DateTime(1987, 11, 25);
Property prop = new Property();
prop.DateTime = test;
// Property accessor
Assert.AreEqual(test, datetimeGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on decimal property.
/// </summary>
[Test]
public void TestSetNullOnDecimalProperty()
{
Property prop = new Property();
prop.Decimal = 45.187M;
// Property accessor
decimalSetAccessor.Set(prop, null);
Assert.AreEqual(0.0M, prop.Decimal);
}
/// <summary>
/// Test setting an decimal property.
/// </summary>
[Test]
public void TestSetDecimal()
{
Property prop = new Property();
prop.Decimal = 45.187M;
// Property accessor
Decimal test = 789456.141516M;
decimalSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.Decimal);
}
/// <summary>
/// Test getting an decimal property.
/// </summary>
[Test]
public void TestGetDecimal()
{
Decimal test = 789456.141516M;
Property prop = new Property();
prop.Decimal = test;
// Property accessor
Assert.AreEqual(test, decimalGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on byte property.
/// </summary>
[Test]
public void TestSetNullOnByteProperty()
{
Property prop = new Property();
prop.Byte = 78;
// Property accessor
byteSetAccessor.Set(prop, null);
Assert.AreEqual((byte)0, prop.Byte);
}
/// <summary>
/// Test setting an byte property.
/// </summary>
[Test]
public void TestSetByte()
{
Property prop = new Property();
prop.Byte = 15;
// Property accessor
byte test = 94;
byteSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.Byte);
}
/// <summary>
/// Test getting an byte property.
/// </summary>
[Test]
public void TestGetByte()
{
byte test = 78;
Property prop = new Property();
prop.Byte = test;
// Property accessor
Assert.AreEqual(test, byteGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on char property.
/// </summary>
[Test]
public void TestSetNullOnCharProperty()
{
Property prop = new Property();
prop.Char = 'r';
// Property accessor
charSetAccessor.Set(prop, null);
Assert.AreEqual('\0', prop.Char);
}
/// <summary>
/// Test setting an char property.
/// </summary>
[Test]
public void TestSetChar()
{
Property prop = new Property();
prop.Char = 'b';
// Property accessor
char test = 'j';
charSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.Char);
}
/// <summary>
/// Test getting an char property.
/// </summary>
[Test]
public void TestGetChar()
{
char test = 'z';
Property prop = new Property();
prop.Char = test;
// Property accessor
Assert.AreEqual(test, charGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on short property.
/// </summary>
[Test]
public void TestSetNullOnShortProperty()
{
Property prop = new Property();
prop.Short = 5;
// Property accessor
shortSetAccessor.Set(prop, null);
Assert.AreEqual((short)0, prop.Short);
}
/// <summary>
/// Test setting an short property.
/// </summary>
[Test]
public void TestSetShort()
{
Property prop = new Property();
prop.Short = 9;
// Property accessor
short test = 45;
shortSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.Short);
}
/// <summary>
/// Test getting an short property.
/// </summary>
[Test]
public void TestGetShort()
{
short test = 99;
Property prop = new Property();
prop.Short = test;
// Property accessor
Assert.AreEqual(test, shortGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on ushort property.
/// </summary>
[Test]
public void TestSetNullOnUShortProperty()
{
Property prop = new Property();
prop.UShort = 5;
// Property accessor
ushortSetAccessor.Set(prop, null);
Assert.AreEqual((ushort)0, prop.UShort);
}
/// <summary>
/// Test setting an ushort property.
/// </summary>
[Test]
public void TestSetUShort()
{
Property prop = new Property();
prop.UShort = 9;
// Property accessor
ushort test = 45;
ushortSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.UShort);
}
/// <summary>
/// Test getting an ushort property.
/// </summary>
[Test]
public void TestGetUShort()
{
ushort test = 99;
Property prop = new Property();
prop.UShort = test;
// Property accessor
Assert.AreEqual(test, ushortGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on uint property.
/// </summary>
[Test]
public void TestSetNullOnUIntProperty()
{
Property prop = new Property();
prop.UInt = 5;
// Property accessor
uintSetAccessor.Set(prop, null);
Assert.AreEqual((uint)0, prop.UInt);
}
/// <summary>
/// Test setting an uint property.
/// </summary>
[Test]
public void TestSetUInt()
{
Property prop = new Property();
prop.UInt = 9;
// Property accessor
uint test = 45;
uintSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.UInt);
}
/// <summary>
/// Test getting an uint property.
/// </summary>
[Test]
public void TestGetUInt()
{
uint test = 99;
Property prop = new Property();
prop.UInt = test;
// Property accessor
Assert.AreEqual(test, uintGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on ulong property.
/// </summary>
[Test]
public void TestSetNullOnULongProperty()
{
Property prop = new Property();
prop.ULong = 5L;
// Property accessor
ulongSetAccessor.Set(prop, null);
Assert.AreEqual((ulong)0, prop.ULong);
}
/// <summary>
/// Test setting an ulong property.
/// </summary>
[Test]
public void TestSetULong()
{
Property prop = new Property();
prop.ULong = 45464646578;
// Property accessor
ulong test = 45;
ulongSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.ULong);
}
/// <summary>
/// Test getting an ulong property.
/// </summary>
[Test]
public void TestGetULong()
{
ulong test = 99;
Property prop = new Property();
prop.ULong = test;
// Property accessor
Assert.AreEqual(test, ulongGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on bool property.
/// </summary>
[Test]
public void TestSetNullOnBoolProperty()
{
Property prop = new Property();
prop.Bool = true;
// Property accessor
boolSetAccessor.Set(prop, null);
Assert.AreEqual(false, prop.Bool);
}
/// <summary>
/// Test setting an bool property.
/// </summary>
[Test]
public void TestSetBool()
{
Property prop = new Property();
prop.Bool = false;
// Property accessor
bool test = true;
boolSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.Bool);
}
/// <summary>
/// Test getting an bool property.
/// </summary>
[Test]
public void TestGetBool()
{
bool test = false;
Property prop = new Property();
prop.Bool = test;
// Property accessor
Assert.AreEqual(test, boolGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on double property.
/// </summary>
[Test]
public void TestSetNullOnDoubleProperty()
{
Property prop = new Property();
prop.Double = 788956.56D;
// Property accessor
doubleSetAccessor.Set(prop, null);
Assert.AreEqual(0.0D, prop.Double);
}
/// <summary>
/// Test setting an double property.
/// </summary>
[Test]
public void TestSetDouble()
{
Property prop = new Property();
prop.Double = 56789123.45888D;
// Property accessor
double test = 788956.56D;
doubleSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.Double);
}
/// <summary>
/// Test getting an double property.
/// </summary>
[Test]
public void TestGetDouble()
{
double test = 788956.56D;
Property prop = new Property();
prop.Double = test;
// Property accessor
Assert.AreEqual(test, doubleGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on float property.
/// </summary>
[Test]
public void TestSetNullOnFloatProperty()
{
Property prop = new Property();
prop.Float = 565.45F;
// Property accessor
floatSetAccessor.Set(prop, null);
Assert.AreEqual(0.0D, prop.Float);
}
/// <summary>
/// Test setting an float property.
/// </summary>
[Test]
public void TestSetFloat()
{
Property prop = new Property();
prop.Float = 565.45F;
// Property accessor
float test = 4567.45F;
floatSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.Float);
}
/// <summary>
/// Test getting an float property.
/// </summary>
[Test]
public void TestGetFloat()
{
float test = 565.45F;
Property prop = new Property();
prop.Float = test;
// Property accessor
Assert.AreEqual(test, floatGetAccessor.Get(prop));
}
/// <summary>
/// Test setting null on Guid property.
/// </summary>
[Test]
public void TestSetNullOnGuidProperty()
{
Property prop = new Property();
prop.Guid = Guid.NewGuid();
// Property accessor
guidSetAccessor.Set(prop, null);
Assert.AreEqual(Guid.Empty, prop.Guid);
}
/// <summary>
/// Test setting an Guid property.
/// </summary>
[Test]
public void TestSetGuid()
{
Property prop = new Property();
prop.Guid = Guid.NewGuid();
// Property accessor
Guid test = Guid.NewGuid();
guidSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.Guid);
}
/// <summary>
/// Test getting an Guid property.
/// </summary>
[Test]
public void TestGetGuid()
{
Guid test = Guid.NewGuid();
Property prop = new Property();
prop.Guid = test;
// Property accessor
Assert.AreEqual(test, guidGetAccessor.Get(prop));
}
/// <summary>
/// Test the setting null on a TimeSpan property.
/// </summary>
[Test]
public void TestSetNullOnTimeSpanProperty()
{
Property prop = new Property();
prop.TimeSpan = new TimeSpan(5, 12, 57, 21, 13);
// Property accessor
timespanSetAccessor.Set(prop, null);
Assert.AreEqual(new TimeSpan(0,0,0), prop.TimeSpan);
}
/// <summary>
/// Test setting an TimeSpan property.
/// </summary>
[Test]
public void TestSetTimeSpan()
{
Property prop = new Property();
prop.TimeSpan = new TimeSpan(5, 12, 57, 21, 13);
// Property accessor
TimeSpan test = new TimeSpan(15, 5, 21, 45, 35);
timespanSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.TimeSpan);
}
/// <summary>
/// Test getting an TimeSpan property.
/// </summary>
[Test]
public void TestGetTimeSpan()
{
TimeSpan test = new TimeSpan(5, 12, 57, 21, 13);
Property prop = new Property();
prop.TimeSpan = test;
// Property accessor
Assert.AreEqual(test, timespanGetAccessor.Get(prop));
}
/// <summary>
/// Test the setting null on a object property.
/// </summary>
[Test]
public void TestSetNullOnAccountProperty()
{
Property prop = new Property();
prop.Account = new Account() ;
prop.Account.FirstName = "test";
// Property accessor
accountSetAccessor.Set(prop, null);
Assert.AreEqual(null, prop.Account);
}
/// <summary>
/// Test getting an object property.
/// </summary>
[Test]
public void TestGetAccount()
{
Account test = new Account();
test.FirstName = "Gilles";
Property prop = new Property();
prop.Account = test;
// Property accessor
Assert.AreEqual(HashCodeProvider.GetIdentityHashCode(test), HashCodeProvider.GetIdentityHashCode(prop.Account));
Assert.AreEqual(test.FirstName, ((Account)accountGetAccessor.Get(prop)).FirstName);
}
/// <summary>
/// Test setting an object property.
/// </summary>
[Test]
public void TestSetAccount()
{
Property prop = new Property();
prop.Account = new Account() ;
prop.Account.FirstName = "test";
// Property accessor
string firstName = "Gilles";
Account test = new Account();
test.FirstName = firstName;
accountSetAccessor.Set(prop, test);
Assert.AreEqual(firstName, prop.Account.FirstName);
}
/// <summary>
/// Test the setting null on a Enum property.
/// </summary>
[Test]
public void TestSetNullOnEnumProperty()
{
Property prop = new Property();
prop.Day = Days.Thu;
PropertyInfo propertyInfo = typeof(Property).GetProperty("Day", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance);
propertyInfo.SetValue(prop, null, null);
// Property accessor
enumSetAccessor.Set(prop, null);
Assert.AreEqual(0, (int)prop.Day);
}
/// <summary>
/// Test setting an Enum property.
/// </summary>
[Test]
public void TestSetEnum()
{
Property prop = new Property();
prop.Day = Days.Thu;
// Property accessor
Days test = Days.Wed;
enumSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.Day);
}
/// <summary>
/// Test getting an Enum property.
/// </summary>
[Test]
public void TestGetEnum()
{
Days test = Days.Wed;
Property prop = new Property();
prop.Day = test;
// Property accessor
Assert.AreEqual(test, enumGetAccessor.Get(prop));
}
#if dotnet2
/// <summary>
/// Test the setting null on a nullable int property.
/// </summary>
[Test]
public void TestSetNullOnNullableIntProperty()
{
Property prop = new Property();
prop.IntNullable = 85;
// Property accessor
nullableSetAccessor.Set(prop, null);
Assert.AreEqual(null, prop.IntNullable);
}
/// <summary>
/// Test getting an nullable int property.
/// </summary>
[Test]
public void TestGetNullableInt()
{
Int32? test = 55;
Property prop = new Property();
prop.IntNullable = test;
// Property accessor
Assert.AreEqual(test, nullableGetAccessor.Get(prop));
}
/// <summary>
/// Test setting an nullable int property.
/// </summary>
[Test]
public void TestSetNullableInt()
{
Property prop = new Property();
prop.IntNullable = 99;
// Property accessor
Int32? test = 55;
nullableSetAccessor.Set(prop, test);
Assert.AreEqual(test, prop.IntNullable);
}
#endif
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using Encog.ML.Data.Market;
using Encog.Util.CSV;
using System.IO;
using Encog.ML.Data.Market.Loader;
namespace ErrorTesterConsoleApplication
{
public class MultiCsvLoader : IMarketLoader
{
#region IMarketLoader Members
string Precision { get; set; }
private string LoadedFile { get; set; }
/// <summary>
/// Set CSVFormat, default CSVFormat.DecimalPoint
/// </summary>
public CSVFormat LoadedFormat { get; set; }
/// <summary>
/// Use to indicate that Date and Time exist in different columns, default true
/// </summary>
bool DateTimeDualColumn { get; set; }
/// <summary>
/// Use to set format for Date or DateTime column, default MM/dd/yyyy
/// </summary>
string DateFormat { get; set; }
/// <summary>
/// Use to set format for Time column, default HHmm
/// </summary>
string TimeFormat { get; set; }
/// <summary>
/// Links a TickerSymbol to a CSV file
/// </summary>
private IDictionary<TickerSymbol, string> fileList = new Dictionary<TickerSymbol, string>();
/// <summary>
/// Construct a multi CSV file loader
/// </summary>
public MultiCsvLoader()
{
LoadedFormat = CSVFormat.DecimalPoint;
DateTimeDualColumn = true;
DateFormat = "MM/dd/yyyy";
TimeFormat = "HHmm";
}
/// <summary>
/// Construct a multi CSV file loader with option to set loaded format and indicate if CSV date is in two columns
/// </summary>
/// <param name="format">Set the CSV format</param>
/// <param name="dualDateTimeColumn"> Indicate true for DateTime information in two separate columns</param>
public MultiCsvLoader(CSVFormat format, bool dualDateTimeColumn)
{
LoadedFormat = format;
DateTimeDualColumn = dualDateTimeColumn;
}
/// <summary>
/// Reads and parses CSV data from file
/// </summary>
/// <param name="ticker">Ticker associated with CSV file</param>
/// <param name="neededTypes">Columns to parse (headers)</param>
/// <param name="from">DateTime from</param>
/// <param name="to">DateTime to</param>
/// <param name="File">Filepath to CSV</param>
/// <returns>Marketdata</returns>
public ICollection<LoadedMarketData> ReadAndCallLoader(TickerSymbol ticker, IList<MarketDataType> neededTypes, DateTime from, DateTime to, string File)
{
try
{
LoadedFile = File;
Console.WriteLine("Loading instrument: " + ticker.Symbol + " from: " + File);
//We got a file, lets load it.
ICollection<LoadedMarketData> result = new List<LoadedMarketData>();
ReadCSV csv = new ReadCSV(File, true, LoadedFormat);
if (DateTimeDualColumn)
{
csv.DateFormat = DateFormat;
csv.TimeFormat = TimeFormat;
}
else
{
csv.DateFormat = DateFormat;
}
//"Date","Time","Open","High","Low","Close","Volume"
while (csv.Next())
{
string datetime = "";
if (DateTimeDualColumn)
{
datetime = csv.GetDate("Date").ToShortDateString() + " " +
csv.GetTime("Time").ToShortTimeString();
}
else
{
datetime = csv.GetDate("Date").ToShortDateString();
}
DateTime date = DateTime.Parse(datetime);
if (date > from && date < to)
{
// CSV columns
double open = csv.GetDouble("Open");
double high = csv.GetDouble("High");
double low = csv.GetDouble("Low");
double close = csv.GetDouble("Close");
double volume = csv.GetDouble("Volume");
LoadedMarketData data = new LoadedMarketData(date, ticker);
foreach (MarketDataType marketDataType in neededTypes)
{
switch (marketDataType.ToString())
{
case "Open":
data.SetData(MarketDataType.Open, open);
break;
case "High":
data.SetData(MarketDataType.High, high);
break;
case "Low":
data.SetData(MarketDataType.Low, low);
break;
case "Close":
data.SetData(MarketDataType.Close, close);
break;
case "Volume":
data.SetData(MarketDataType.Volume, volume);
break;
case "RangeHighLow":
data.SetData(MarketDataType.RangeHighLow, Math.Round(Math.Abs(high - low), 6));
break;
case "RangeOpenClose":
data.SetData(MarketDataType.RangeOpenClose, Math.Round(Math.Abs(close - open), 6));
break;
case "RangeOpenCloseNonAbsolute":
data.SetData(MarketDataType.RangeOpenCloseNonAbsolute, Math.Round(close - open, 6));
break;
case "Weighted":
data.SetData(MarketDataType.Weighted, Math.Round((high + low + 2 * close) / 4, 6));
break;
}
}
result.Add(data);
}
}
csv.Close();
return result;
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong reading the csv: " + ex.Message);
}
return null;
}
/// <summary>
/// Set correct CSVFormat, e.g. "Decimal Point"
/// </summary>
/// <param name="csvformat">Enter format, e.g. "Decimal Point"</param>
/// <returns></returns>
public CSVFormat fromStringCSVFormattoCSVFormat(string csvformat)
{
switch (csvformat)
{
case "Decimal Point":
LoadedFormat = CSVFormat.DecimalPoint;
break;
case "Decimal Comma":
LoadedFormat = CSVFormat.DecimalComma;
break;
case "English Format":
LoadedFormat = CSVFormat.English;
break;
case "EG Format":
LoadedFormat = CSVFormat.EgFormat;
break;
default:
break;
}
return LoadedFormat;
}
#region IMarketLoader Members
/// <derived/>
public ICollection<LoadedMarketData> Load(TickerSymbol ticker, IList<MarketDataType> dataNeeded,
DateTime from, DateTime to)
{
try
{
string fileCSV = "";
foreach (TickerSymbol tickerSymbol in fileList.Keys)
{
if (tickerSymbol.Symbol.ToLower().Equals(ticker.Symbol.ToLower()))
{
if (fileList.TryGetValue(tickerSymbol, out fileCSV))
{
return File.Exists(fileCSV) ?
(ReadAndCallLoader(tickerSymbol, dataNeeded, from, to, fileCSV)) : null; //If file does not exist
}
return null; //Problem reading list
}
}
return null; //if ticker is not defined
}
catch (FileNotFoundException fnfe)
{
Console.WriteLine("Problem with loading data for instruments", fnfe);
return null;
}
}
//Should be removed/changed in interface
public string GetFile(string file)
{
return LoadedFile;
}
#endregion
/// <summary>
/// Add filepaths with matching ticker symbols
/// </summary>
/// <param name="ticker">Set Ticker, e.g. EURUSD</param>
/// <param name="fileName">Set filepath, e.g. .\\EURUSD.csv</param>
/// <returns>True returned if file exists, if file does not exist FileNotFoundException thrown,
/// if TickerSymbol exist false is returned</returns>
public bool SetFiles(string ticker, string fileName)
{
if (!File.Exists(fileName))
{
throw new FileNotFoundException("File submitted did not exist", fileName);
}
else if (!fileList.ContainsKey(new TickerSymbol(ticker)))
{
fileList.Add(new TickerSymbol(ticker), fileName);
return true;
}
return false; //Ticker exists
}
#endregion
}
}
| |
#region Using Directives
#endregion
namespace SPALM.SPSF.Library.Actions
{
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using EnvDTE;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using SPALM.SPSF.SharePointBridge;
using Process = System.Diagnostics.Process;
/// <summary>
/// Exports a given
/// </summary>
[ServiceDependency(typeof(DTE))]
public class RunContentExport : ConfigurableAction
{
private Project _TargetProject = null;
private string _TargetFolder = "";
private SharePointExportSettings _ExportSettings;
private string _ExportDataFolder = "";
private bool _ExtractAfterExport = false;
private string _IncludeSecurity = "";
private string _IncludeVersions = "";
private string _ExportMethod = "";
private bool _ExcludeDependencies = false;
private const string EXPORTFILENAME = "exportedData.cab";
private DTE dte = null;
[Input(Required = true)]
public Project TargetProject
{
get { return _TargetProject; }
set { _TargetProject = value; }
}
[Input(Required = true)]
public string TargetFolder
{
get { return _TargetFolder; }
set { _TargetFolder = value; }
}
[Input(Required = true)]
public string ExportDataFolder
{
get { return _ExportDataFolder; }
set { _ExportDataFolder = value; }
}
[Input(Required = false)]
public bool ExtractAfterExport
{
get { return _ExtractAfterExport; }
set { _ExtractAfterExport = value; }
}
[Input(Required = true)]
public string ExportMethod
{
get { return _ExportMethod; }
set { _ExportMethod = value; }
}
[Input(Required = true)]
public string IncludeSecurity
{
get { return _IncludeSecurity; }
set { _IncludeSecurity = value; }
}
[Input(Required = true)]
public string IncludeVersions
{
get { return _IncludeVersions; }
set { _IncludeVersions = value; }
}
[Input(Required = true)]
public bool ExcludeDependencies
{
get { return _ExcludeDependencies; }
set { _ExcludeDependencies = value; }
}
[Input(Required = true)]
public SharePointExportSettings ExportSettings
{
get { return _ExportSettings; }
set { _ExportSettings = value; }
}
private string tempFilename = "";
private string tempExportDir = "";
private string tempLogFilePath = "";
public override void Execute()
{
dte = GetService<DTE>(true);
//set the directory where to place the output
tempExportDir = Path.Combine(Path.GetTempPath(), "SPSFExport" + Guid.NewGuid().ToString());
Directory.CreateDirectory(tempExportDir);
tempFilename = EXPORTFILENAME;
tempLogFilePath = Path.Combine(tempExportDir, "SPSFExport.log");
_ExportSettings.ExportMethod = _ExportMethod;
_ExportSettings.IncludeSecurity = _IncludeSecurity;
_ExportSettings.IncludeVersions = _IncludeVersions;
_ExportSettings.ExcludeDependencies = _ExcludeDependencies;
//start bridge
SharePointBrigdeHelper helper = new SharePointBrigdeHelper(dte);
helper.ExportContent(_ExportSettings, tempExportDir, tempFilename, tempLogFilePath);
if (_ExtractAfterExport)
{
//should they be extracted before
string tempExtractFolder = tempExportDir; // Path.Combine(tempExportDir, "extracted");
//Directory.CreateDirectory(tempExtractFolder);
string fileToExtract = Path.Combine(tempExportDir, EXPORTFILENAME);
// Launch the process and wait until it's done (with a 10 second timeout).
string commandarguments = "\"" + fileToExtract + "\" \"" + tempExtractFolder + "\" -F:*";
ProcessStartInfo startInfo = new ProcessStartInfo("expand ", commandarguments);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
Process snProcess = Process.Start(startInfo);
snProcess.WaitForExit(20000);
//rename
bool renameFilesAfterExport = true;
if (renameFilesAfterExport)
{
//get the manifest.xml
string manifestFilename = Path.Combine(tempExportDir, "Manifest.xml");
if (File.Exists(manifestFilename))
{
XmlDocument doc = new XmlDocument();
doc.Load(manifestFilename);
//get the contents of the elements node in the new xml
XmlNamespaceManager newnsmgr = new XmlNamespaceManager(doc.NameTable);
newnsmgr.AddNamespace("ns", "urn:deployment-manifest-schema");
//read all
XmlNodeList datFiles = doc.SelectNodes("/ns:SPObjects/ns:SPObject/ns:File", newnsmgr);
foreach (XmlNode datFile in datFiles)
{
//DispForm.aspx
if (datFile.Attributes["Name"] != null)
{
if (datFile.Attributes["FileValue"] != null)
{
//is there a file with name 00000001.dat
string datFilename = datFile.Attributes["FileValue"].Value;
string datFilePath = Path.Combine(tempExportDir, datFilename);
if (File.Exists(datFilePath))
{
//ok, lets change the name
string newfilename = Path.GetFileNameWithoutExtension(datFilePath);
string itemname = datFile.Attributes["Name"].Value;
itemname = itemname.Replace(".", "_");
itemname = itemname.Replace(" ", "_");
newfilename = newfilename + SPSFConstants.NameSeparator + itemname + ".dat";
string newfilePath = Path.Combine(tempExportDir, newfilename);
//rename the file
File.Move(datFilePath, newfilePath);
//update the manifest.xml
datFile.Attributes["FileValue"].Value = newfilename;
}
}
}
}
doc.Save(manifestFilename);
}
}
//todo delete the cmp file
if (File.Exists(fileToExtract))
{
File.Delete(fileToExtract);
}
//create the ddf out of the contents (except the logfile);
StringBuilder ddfcontent = new StringBuilder();
ddfcontent.AppendLine(";*** Sample Source Code MakeCAB Directive file example");
ddfcontent.AppendLine(";");
ddfcontent.AppendLine(".OPTION EXPLICIT ; Generate errors");
ddfcontent.AppendLine(".Set CabinetNameTemplate=exportedData.cab");
ddfcontent.AppendLine(".set DiskDirectoryTemplate=CDROM ; All cabinets go in a single directory");
ddfcontent.AppendLine(".Set CompressionType=MSZIP;** All files are compressed in cabinet files");
ddfcontent.AppendLine(".Set UniqueFiles=\"OFF\"");
ddfcontent.AppendLine(".Set Cabinet=on");
ddfcontent.AppendLine(".Set DiskDirectory1=.");
ddfcontent.AppendLine(".Set CabinetFileCountThreshold=0");
ddfcontent.AppendLine(".Set FolderFileCountThreshold=0");
ddfcontent.AppendLine(".Set FolderSizeThreshold=0");
ddfcontent.AppendLine(".Set MaxCabinetSize=0");
ddfcontent.AppendLine(".Set MaxDiskFileCount=0");
ddfcontent.AppendLine(".Set MaxDiskSize=0");
foreach (string s in Directory.GetFiles(tempExportDir, "*.*", SearchOption.AllDirectories))
{
if (!s.EndsWith(".log"))
{
FileInfo info = new FileInfo(s);
ddfcontent.AppendLine(info.Name);
}
}
ddfcontent.AppendLine("");
ddfcontent.AppendLine(";*** The end");
//write the ddf file
string ddfFilename = Path.Combine(tempExportDir, "_exportedData.ddf");
TextWriter writer = new StreamWriter(ddfFilename);
writer.Write(ddfcontent.ToString());
writer.Close();
}
//add all elements in temp folder to the folder exported objects in the project
ProjectItem targetFolder = Helpers.GetProjectItemByName(TargetProject.ProjectItems, TargetFolder);
if (targetFolder != null)
{
//is there already a folder named "ExportedData"
ProjectItem exportedDataFolder = null;
try
{
exportedDataFolder = Helpers.GetProjectItemByName(targetFolder.ProjectItems, "ExportedData");
}
catch (Exception)
{
}
if (exportedDataFolder == null)
{
exportedDataFolder = targetFolder.ProjectItems.AddFolder("ExportedData", EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
}
//empty the exportedDataFolder
foreach (ProjectItem subitem in exportedDataFolder.ProjectItems)
{
subitem.Delete();
}
//add all files in temp folder to the project (except log file
foreach (string s in Directory.GetFiles(tempExportDir, "*.*", SearchOption.AllDirectories))
{
if (!s.EndsWith(".log"))
{
exportedDataFolder.ProjectItems.AddFromFileCopy(s);
}
}
//add log file to the parent folder
if (File.Exists(tempLogFilePath))
{
targetFolder.ProjectItems.AddFromFileCopy(tempLogFilePath);
}
}
}
/// <summary>
/// Removes the previously added reference, if it was created
/// </summary>
public override void Undo()
{
}
}
}
| |
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Q42.HueApi.Extensions;
using Newtonsoft.Json;
using Q42.HueApi.Models.Groups;
using Q42.HueApi.Models;
using System.Dynamic;
using Q42.HueApi.Interfaces;
namespace Q42.HueApi
{
/// <summary>
/// Partial HueClient, contains requests to the /scenes/ url
/// </summary>
public partial class HueClient : IHueClient_Scenes
{
/// <summary>
/// Asynchronously gets all scenes registered with the bridge.
/// </summary>
/// <returns>An enumerable of <see cref="Scene"/>s registered with the bridge.</returns>
public async Task<IReadOnlyCollection<Scene>> GetScenesAsync()
{
CheckInitialized();
HttpClient client = await GetHttpClient().ConfigureAwait(false);
string stringResult = await client.GetStringAsync(new Uri(String.Format("{0}scenes", ApiBase))).ConfigureAwait(false);
List<Scene> results = new List<Scene>();
JToken token = JToken.Parse(stringResult);
if (token.Type == JTokenType.Object)
{
//Each property is a scene
var jsonResult = (JObject)token;
foreach (var prop in jsonResult.Properties())
{
Scene? scene = JsonConvert.DeserializeObject<Scene>(prop.Value.ToString());
if (scene != null)
{
scene.Id = prop.Name;
results.Add(scene);
}
}
}
return results;
}
public async Task<string?> CreateSceneAsync(Scene scene)
{
CheckInitialized();
if (scene == null)
throw new ArgumentNullException(nameof(scene));
if ((scene.Type == null || scene.Type == SceneType.LightScene) && (scene.Lights == null || !scene.Lights.Any()))
throw new ArgumentNullException(nameof(scene.Lights));
if (scene.Type == SceneType.GroupScene && string.IsNullOrEmpty(scene.Group))
throw new ArgumentNullException(nameof(scene.Group));
if (scene.Name == null)
throw new ArgumentNullException(nameof(scene.Name));
//It defaults to false, but fails when omitted
//https://github.com/Q42/Q42.HueApi/issues/56
if (!scene.Recycle.HasValue)
scene.Recycle = false;
//Filter non updatable properties
//Set these fields to null
var sceneJson = JObject.FromObject(scene, new JsonSerializer() { NullValueHandling = NullValueHandling.Ignore });
sceneJson.Remove("Id");
sceneJson.Remove("version");
sceneJson.Remove("lastupdated");
sceneJson.Remove("locked");
sceneJson.Remove("owner");
string jsonString = JsonConvert.SerializeObject(sceneJson, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
HttpClient client = await GetHttpClient().ConfigureAwait(false);
var response = await client.PostAsync(new Uri(String.Format("{0}scenes", ApiBase)), new JsonContent(jsonString)).ConfigureAwait(false);
var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
HueResults sceneResult = DeserializeDefaultHueResult(jsonResult);
if (sceneResult.Count > 0 && sceneResult.First().Success != null && !string.IsNullOrEmpty(sceneResult.First().Success.Id))
{
return sceneResult.First().Success.Id;
}
if (sceneResult.HasErrors())
throw new HueException(sceneResult.Errors.First().Error.Description);
return null;
}
/// <summary>
/// UpdateSceneAsync
/// </summary>
/// <param name="id"></param>
/// <param name="name"></param>
/// <param name="lights"></param>
/// <param name="storeLightState">If set, the lightstates of the lights in the scene will be overwritten by the current state of the lights. Can also be used in combination with transitiontime to update the transition time of a scene.</param>
/// <param name="transitionTime">Can be used in combination with storeLightState</param>
/// <returns></returns>
public async Task<HueResults> UpdateSceneAsync(string id, string name, IEnumerable<string> lights, bool? storeLightState = null, TimeSpan? transitionTime = null)
{
CheckInitialized();
if (id == null)
throw new ArgumentNullException(nameof(id));
if (id.Trim() == String.Empty)
throw new ArgumentException("id must not be empty", nameof(id));
if (lights == null)
throw new ArgumentNullException(nameof(lights));
JObject jsonObj = new JObject();
jsonObj.Add("lights", JToken.FromObject(lights));
if (storeLightState.HasValue)
{
jsonObj.Add("storelightstate", storeLightState.Value);
//Transitiontime can only be used in combination with storeLightState
if (transitionTime.HasValue)
{
jsonObj.Add("transitiontime", (uint)transitionTime.Value.TotalSeconds * 10);
}
}
if (!string.IsNullOrEmpty(name))
jsonObj.Add("name", name);
string jsonString = JsonConvert.SerializeObject(jsonObj, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
HttpClient client = await GetHttpClient().ConfigureAwait(false);
var response = await client.PutAsync(new Uri(String.Format("{0}scenes/{1}", ApiBase, id)), new JsonContent(jsonString)).ConfigureAwait(false);
var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return DeserializeDefaultHueResult(jsonResult);
}
/// <summary>
/// UpdateSceneAsync
/// </summary>
/// <param name="id"></param>
/// <param name="scene"></param>
/// <returns></returns>
public async Task<HueResults> UpdateSceneAsync(string id, Scene scene)
{
CheckInitialized();
if (id == null)
throw new ArgumentNullException(nameof(id));
if (id.Trim() == String.Empty)
throw new ArgumentException("id must not be empty", nameof(id));
if (scene == null)
throw new ArgumentNullException(nameof(scene));
//Set these fields to null
var sceneJson = JObject.FromObject(scene, new JsonSerializer() { NullValueHandling = NullValueHandling.Ignore });
sceneJson.Remove("Id");
sceneJson.Remove("recycle");
sceneJson.Remove("version");
sceneJson.Remove("lastupdated");
sceneJson.Remove("locked");
sceneJson.Remove("owner");
sceneJson.Remove("type");
sceneJson.Remove("group");
if (scene.AppData?.Data == null && scene.AppData?.Version == null)
sceneJson.Remove("appdata");
string jsonString = JsonConvert.SerializeObject(sceneJson, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
HttpClient client = await GetHttpClient().ConfigureAwait(false);
var response = await client.PutAsync(new Uri(String.Format("{0}scenes/{1}", ApiBase, id)), new JsonContent(jsonString)).ConfigureAwait(false);
var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return DeserializeDefaultHueResult(jsonResult);
}
public async Task<HueResults> ModifySceneAsync(string sceneId, string lightId, LightCommand command)
{
CheckInitialized();
if (sceneId == null)
throw new ArgumentNullException(nameof(sceneId));
if (sceneId.Trim() == String.Empty)
throw new ArgumentException("sceneId must not be empty", nameof(sceneId));
if (lightId == null)
throw new ArgumentNullException(nameof(lightId));
if (lightId.Trim() == String.Empty)
throw new ArgumentException("lightId must not be empty", nameof(lightId));
if (command == null)
throw new ArgumentNullException(nameof(command));
string jsonCommand = JsonConvert.SerializeObject(command, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
HttpClient client = await GetHttpClient().ConfigureAwait(false);
var response = await client.PutAsync(new Uri(String.Format("{0}scenes/{1}/lights/{2}/state", ApiBase, sceneId, lightId)), new JsonContent(jsonCommand)).ConfigureAwait(false);
var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return DeserializeDefaultHueResult(jsonResult);
}
public Task<HueResults> RecallSceneAsync(string sceneId, string groupId = "0")
{
if (sceneId == null)
throw new ArgumentNullException(nameof(sceneId));
var groupCommand = new SceneCommand() { Scene = sceneId };
return this.SendGroupCommandAsync(groupCommand, groupId);
}
/// <summary>
/// Deletes a scene
/// </summary>
/// <param name="sceneId"></param>
/// <returns></returns>
public async Task<IReadOnlyCollection<DeleteDefaultHueResult>> DeleteSceneAsync(string sceneId)
{
CheckInitialized();
HttpClient client = await GetHttpClient().ConfigureAwait(false);
var result = await client.DeleteAsync(new Uri(String.Format("{0}scenes/{1}", ApiBase, sceneId))).ConfigureAwait(false);
string jsonResult = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
return DeserializeDefaultHueResult<DeleteDefaultHueResult>(jsonResult);
}
/// <summary>
/// Get a single scene
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<Scene?> GetSceneAsync(string id)
{
CheckInitialized();
HttpClient client = await GetHttpClient().ConfigureAwait(false);
string stringResult = await client.GetStringAsync(new Uri(String.Format("{0}scenes/{1}", ApiBase, id))).ConfigureAwait(false);
Scene? scene = DeserializeResult<Scene>(stringResult);
if (scene != null && string.IsNullOrEmpty(scene.Id))
scene.Id = id;
return scene;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Sep.Git.Tfs.Commands;
using Sep.Git.Tfs.Core.TfsInterop;
namespace Sep.Git.Tfs.Core
{
public class TfsWorkspace : ITfsWorkspace
{
private readonly IWorkspace _workspace;
private readonly string _localDirectory;
private readonly TextWriter _stdout;
private readonly TfsChangesetInfo _contextVersion;
private readonly CheckinOptions _checkinOptions;
private readonly ITfsHelper _tfsHelper;
private readonly CheckinPolicyEvaluator _policyEvaluator;
public IGitTfsRemote Remote { get; private set; }
public TfsWorkspace(IWorkspace workspace, string localDirectory, TextWriter stdout, TfsChangesetInfo contextVersion, IGitTfsRemote remote, CheckinOptions checkinOptions, ITfsHelper tfsHelper, CheckinPolicyEvaluator policyEvaluator)
{
_workspace = workspace;
_policyEvaluator = policyEvaluator;
_contextVersion = contextVersion;
_checkinOptions = checkinOptions;
_tfsHelper = tfsHelper;
_localDirectory = remote.Repository.IsBare ? Path.GetFullPath(localDirectory) : localDirectory;
_stdout = stdout;
this.Remote = remote;
}
public void Shelve(string shelvesetName, bool evaluateCheckinPolicies, CheckinOptions checkinOptions, Func<string> generateCheckinComment)
{
var pendingChanges = _workspace.GetPendingChanges();
if (pendingChanges.IsEmpty())
throw new GitTfsException("Nothing to shelve!");
var shelveset = _tfsHelper.CreateShelveset(_workspace, shelvesetName);
shelveset.Comment = string.IsNullOrWhiteSpace(_checkinOptions.CheckinComment) && !_checkinOptions.NoGenerateCheckinComment ? generateCheckinComment() : _checkinOptions.CheckinComment;
shelveset.WorkItemInfo = GetWorkItemInfos(checkinOptions).ToArray();
if (evaluateCheckinPolicies)
{
foreach (var message in _policyEvaluator.EvaluateCheckin(_workspace, pendingChanges, shelveset.Comment, null, shelveset.WorkItemInfo).Messages)
{
_stdout.WriteLine("[Checkin Policy] " + message);
}
}
_workspace.Shelve(shelveset, pendingChanges, _checkinOptions.Force ? TfsShelvingOptions.Replace : TfsShelvingOptions.None);
}
public int CheckinTool(Func<string> generateCheckinComment)
{
var pendingChanges = _workspace.GetPendingChanges();
if (pendingChanges.IsEmpty())
throw new GitTfsException("Nothing to checkin!");
var checkinComment = _checkinOptions.CheckinComment;
if (string.IsNullOrWhiteSpace(checkinComment) && !_checkinOptions.NoGenerateCheckinComment)
checkinComment = generateCheckinComment();
var newChangesetId = _tfsHelper.ShowCheckinDialog(_workspace, pendingChanges, GetWorkItemCheckedInfos(), checkinComment);
if (newChangesetId <= 0)
throw new GitTfsException("Checkin canceled!");
return newChangesetId;
}
public void Merge(string sourceTfsPath, string tfsRepositoryPath)
{
_workspace.Merge(sourceTfsPath, tfsRepositoryPath);
}
public int Checkin(CheckinOptions options, Func<string> generateCheckinComment = null)
{
if (options == null) options = _checkinOptions;
var checkinComment = options.CheckinComment;
if (string.IsNullOrWhiteSpace(checkinComment) && !options.NoGenerateCheckinComment && generateCheckinComment != null)
checkinComment = generateCheckinComment();
var pendingChanges = _workspace.GetPendingChanges();
if (pendingChanges.IsEmpty())
throw new GitTfsException("Nothing to checkin!");
var workItemInfos = GetWorkItemInfos(options);
var checkinNote = _tfsHelper.CreateCheckinNote(options.CheckinNotes);
var checkinProblems = _policyEvaluator.EvaluateCheckin(_workspace, pendingChanges, checkinComment, checkinNote, workItemInfos);
if (checkinProblems.HasErrors)
{
foreach (var message in checkinProblems.Messages)
{
if (options.Force && string.IsNullOrWhiteSpace(options.OverrideReason) == false)
{
_stdout.WriteLine("[OVERRIDDEN] " + message);
}
else
{
_stdout.WriteLine("[ERROR] " + message);
}
}
if (!options.Force)
{
throw new GitTfsException("No changes checked in.");
}
if (String.IsNullOrWhiteSpace(options.OverrideReason))
{
throw new GitTfsException("A reason must be supplied (-f REASON) to override the policy violations.");
}
}
var policyOverride = GetPolicyOverrides(options, checkinProblems.Result);
try
{
var newChangeset = _workspace.Checkin(pendingChanges, checkinComment, options.AuthorTfsUserId, checkinNote, workItemInfos, policyOverride, options.OverrideGatedCheckIn);
if (newChangeset == 0)
{
throw new GitTfsException("Checkin failed!");
}
else
{
return newChangeset;
}
}
catch(GitTfsGatedCheckinException e)
{
return LaunchGatedCheckinBuild(e.AffectedBuildDefinitions, e.ShelvesetName, e.CheckInTicket);
}
}
private int LaunchGatedCheckinBuild(ReadOnlyCollection<KeyValuePair<string, Uri>> affectedBuildDefinitions, string shelvesetName, string checkInTicket)
{
_stdout.WriteLine("Due to a gated check-in, a shelveset '" + shelvesetName + "' containing your changes has been created and need to be built before it can be committed.");
KeyValuePair<string, Uri> buildDefinition;
if (affectedBuildDefinitions.Count == 1)
{
buildDefinition = affectedBuildDefinitions.First();
}
else
{
int choice;
do
{
_stdout.WriteLine("Build definitions that can be used:");
for (int i = 0; i < affectedBuildDefinitions.Count; i++)
{
_stdout.WriteLine((i + 1) + ": " + affectedBuildDefinitions[i].Key);
}
_stdout.WriteLine("Please choose the build definition to trigger?");
} while (!int.TryParse(Console.ReadLine(), out choice) || choice <= 0 || choice > affectedBuildDefinitions.Count);
buildDefinition = affectedBuildDefinitions.ElementAt(choice - 1);
}
return Remote.Tfs.QueueGatedCheckinBuild(buildDefinition.Value, buildDefinition.Key, shelvesetName, checkInTicket);
}
private TfsPolicyOverrideInfo GetPolicyOverrides(CheckinOptions options, ICheckinEvaluationResult checkinProblems)
{
if (!options.Force || String.IsNullOrWhiteSpace(options.OverrideReason))
return null;
return new TfsPolicyOverrideInfo { Comment = options.OverrideReason, Failures = checkinProblems.PolicyFailures };
}
public string GetLocalPath(string path)
{
return Path.Combine(_localDirectory, path);
}
public void Add(string path)
{
_stdout.WriteLine(" add " + path);
var added = _workspace.PendAdd(GetLocalPath(path));
if (added != 1) throw new Exception("One item should have been added, but actually added " + added + " items.");
}
public void Edit(string path)
{
var localPath = GetLocalPath(path);
_stdout.WriteLine(" edit " + localPath);
GetFromTfs(localPath);
var edited = _workspace.PendEdit(localPath);
if (edited != 1)
{
if (_checkinOptions.IgnoreMissingItems)
{
_stdout.WriteLine("Warning: One item should have been edited, but actually edited " + edited + ". Ignoring item.");
}
else if (edited == 0 && _checkinOptions.AddMissingItems)
{
_stdout.WriteLine("Warning: One item should have been edited, but was not found. Adding the file instead.");
Add(path);
}
else
{
throw new Exception("One item should have been edited, but actually edited " + edited + " items.");
}
}
}
public void Delete(string path)
{
path = GetLocalPath(path);
_stdout.WriteLine(" delete " + path);
GetFromTfs(path);
var deleted = _workspace.PendDelete(path);
if (deleted != 1) throw new Exception("One item should have been deleted, but actually deleted " + deleted + " items.");
}
public void Rename(string pathFrom, string pathTo, string score)
{
_stdout.WriteLine(" rename " + pathFrom + " to " + pathTo + " (score: " + score + ")");
GetFromTfs(GetLocalPath(pathFrom));
var result = _workspace.PendRename(GetLocalPath(pathFrom), GetLocalPath(pathTo));
if (result != 1) throw new ApplicationException("Unable to rename item from " + pathFrom + " to " + pathTo);
}
private void GetFromTfs(string path)
{
_workspace.ForceGetFile(_workspace.GetServerItemForLocalItem(path), _contextVersion.ChangesetId);
}
public void Get(int changesetId)
{
_workspace.GetSpecificVersion(changesetId);
}
public void Get(IChangeset changeset)
{
_workspace.GetSpecificVersion(changeset);
}
public void Get(int changesetId, IEnumerable<IChange> changes)
{
if (changes.Any())
{
_workspace.GetSpecificVersion(changesetId, changes);
}
}
public string GetLocalItemForServerItem(string serverItem)
{
return _workspace.GetLocalItemForServerItem(serverItem);
}
private IEnumerable<IWorkItemCheckinInfo> GetWorkItemInfos(CheckinOptions options = null)
{
return GetWorkItemInfosHelper<IWorkItemCheckinInfo>(_tfsHelper.GetWorkItemInfos, options);
}
private IEnumerable<IWorkItemCheckedInfo> GetWorkItemCheckedInfos()
{
return GetWorkItemInfosHelper<IWorkItemCheckedInfo>(_tfsHelper.GetWorkItemCheckedInfos);
}
private IEnumerable<T> GetWorkItemInfosHelper<T>(Func<IEnumerable<string>, TfsWorkItemCheckinAction, IEnumerable<T>> func, CheckinOptions options = null)
{
var checkinOptions = options ?? _checkinOptions;
var workItemInfos = func(checkinOptions.WorkItemsToAssociate, TfsWorkItemCheckinAction.Associate);
workItemInfos = workItemInfos.Append(
func(checkinOptions.WorkItemsToResolve, TfsWorkItemCheckinAction.Resolve));
return workItemInfos;
}
}
}
| |
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Shapes;
using Avalonia.Controls.Templates;
using Avalonia.Media;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class LayoutTransformControlTests
{
[Fact]
public void Measure_On_Scale_x2_Is_Correct()
{
double scale = 2;
TransformMeasureSizeTest(
new Size(100, 50),
new ScaleTransform() { ScaleX = scale, ScaleY = scale },
new Size(200, 100));
}
[Fact]
public void Measure_On_Scale_x0_5_Is_Correct()
{
double scale = 0.5;
TransformMeasureSizeTest(
new Size(100, 50),
new ScaleTransform() { ScaleX = scale, ScaleY = scale },
new Size(50, 25));
}
[Fact]
public void Measure_On_Skew_X_axis_45_degrees_Is_Correct()
{
TransformMeasureSizeTest(
new Size(100, 100),
new SkewTransform() { AngleX = 45 },
new Size(200, 100));
}
[Fact]
public void Measure_On_Skew_Y_axis_45_degrees_Is_Correct()
{
TransformMeasureSizeTest(
new Size(100, 100),
new SkewTransform() { AngleY = 45 },
new Size(100, 200));
}
[Fact]
public void Measure_On_Skew_X_axis_minus_45_degrees_Is_Correct()
{
TransformMeasureSizeTest(
new Size(100, 100),
new SkewTransform() { AngleX = -45 },
new Size(200, 100));
}
[Fact]
public void Measure_On_Skew_Y_axis_minus_45_degrees_Is_Correct()
{
TransformMeasureSizeTest(
new Size(100, 100),
new SkewTransform() { AngleY = -45 },
new Size(100, 200));
}
[Fact]
public void Measure_On_Skew_0_degrees_Is_Correct()
{
TransformMeasureSizeTest(
new Size(100, 100),
new SkewTransform() { AngleX = 0, AngleY = 0 },
new Size(100, 100));
}
[Fact]
public void Measure_On_Rotate_90_degrees_Is_Correct()
{
TransformMeasureSizeTest(
new Size(100, 25),
new RotateTransform() { Angle = 90 },
new Size(25, 100));
}
[Fact]
public void Measure_On_Rotate_minus_90_degrees_Is_Correct()
{
TransformMeasureSizeTest(
new Size(100, 25),
new RotateTransform() { Angle = -90 },
new Size(25, 100));
}
[Fact]
public void Measure_On_Rotate_0_degrees_Is_Correct()
{
TransformMeasureSizeTest(
new Size(100, 25),
new RotateTransform() { Angle = 0 },
new Size(100, 25));
}
[Fact]
public void Measure_On_Rotate_180_degrees_Is_Correct()
{
TransformMeasureSizeTest(
new Size(100, 25),
new RotateTransform() { Angle = 180 },
new Size(100, 25));
}
[Fact]
public void Bounds_On_Scale_x2_Are_correct()
{
double scale = 2;
TransformRootBoundsTest(
new Size(100, 50),
new ScaleTransform() { ScaleX = scale, ScaleY = scale },
new Rect(0, 0, 100, 50));
}
[Fact]
public void Bounds_On_Scale_x0_5_Are_correct()
{
double scale = 0.5;
TransformRootBoundsTest(
new Size(100, 50),
new ScaleTransform() { ScaleX = scale, ScaleY = scale },
new Rect(0, 0, 100, 50));
}
[Fact]
public void Bounds_On_Rotate_180_degrees_Are_correct()
{
TransformRootBoundsTest(
new Size(100, 25),
new RotateTransform() { Angle = 180 },
new Rect(100, 25, 100, 25));
}
[Fact]
public void Bounds_On_Rotate_0_degrees_Are_correct()
{
TransformRootBoundsTest(
new Size(100, 25),
new RotateTransform() { Angle = 0 },
new Rect(0, 0, 100, 25));
}
[Fact]
public void Bounds_On_Rotate_90_degrees_Are_correct()
{
TransformRootBoundsTest(
new Size(100, 25),
new RotateTransform() { Angle = 90 },
new Rect(25, 0, 100, 25));
}
[Fact]
public void Bounds_On_Rotate_minus_90_degrees_Are_correct()
{
TransformRootBoundsTest(
new Size(100, 25),
new RotateTransform() { Angle = -90 },
new Rect(0, 100, 100, 25));
}
[Fact]
public void Should_Generate_RotateTransform_90_degrees()
{
LayoutTransformControl lt = CreateWithChildAndMeasureAndTransform(
100,
25,
new RotateTransform() { Angle = 90 });
Assert.NotNull(lt.TransformRoot.RenderTransform);
Matrix m = lt.TransformRoot.RenderTransform.Value;
Matrix res = Matrix.CreateRotation(Matrix.ToRadians(90));
Assert.Equal(m.M11, res.M11, 3);
Assert.Equal(m.M12, res.M12, 3);
Assert.Equal(m.M21, res.M21, 3);
Assert.Equal(m.M22, res.M22, 3);
Assert.Equal(m.M31, res.M31, 3);
Assert.Equal(m.M32, res.M32, 3);
}
[Fact]
public void Should_Generate_RotateTransform_minus_90_degrees()
{
LayoutTransformControl lt = CreateWithChildAndMeasureAndTransform(
100,
25,
new RotateTransform() { Angle = -90 });
Assert.NotNull(lt.TransformRoot.RenderTransform);
var m = lt.TransformRoot.RenderTransform.Value;
var res = Matrix.CreateRotation(Matrix.ToRadians(-90));
Assert.Equal(m.M11, res.M11, 3);
Assert.Equal(m.M12, res.M12, 3);
Assert.Equal(m.M21, res.M21, 3);
Assert.Equal(m.M22, res.M22, 3);
Assert.Equal(m.M31, res.M31, 3);
Assert.Equal(m.M32, res.M32, 3);
}
[Fact]
public void Should_Generate_ScaleTransform_x2()
{
LayoutTransformControl lt = CreateWithChildAndMeasureAndTransform(
100,
50,
new ScaleTransform() { ScaleX = 2, ScaleY = 2 });
Assert.NotNull(lt.TransformRoot.RenderTransform);
Matrix m = lt.TransformRoot.RenderTransform.Value;
Matrix res = Matrix.CreateScale(2, 2);
Assert.Equal(m.M11, res.M11, 3);
Assert.Equal(m.M12, res.M12, 3);
Assert.Equal(m.M21, res.M21, 3);
Assert.Equal(m.M22, res.M22, 3);
Assert.Equal(m.M31, res.M31, 3);
Assert.Equal(m.M32, res.M32, 3);
}
[Fact]
public void Should_Generate_SkewTransform_45_degrees()
{
LayoutTransformControl lt = CreateWithChildAndMeasureAndTransform(
100,
100,
new SkewTransform() { AngleX = 45, AngleY = 45 });
Assert.NotNull(lt.TransformRoot.RenderTransform);
Matrix m = lt.TransformRoot.RenderTransform.Value;
Matrix res = Matrix.CreateSkew(Matrix.ToRadians(45), Matrix.ToRadians(45));
Assert.Equal(m.M11, res.M11, 3);
Assert.Equal(m.M12, res.M12, 3);
Assert.Equal(m.M21, res.M21, 3);
Assert.Equal(m.M22, res.M22, 3);
Assert.Equal(m.M31, res.M31, 3);
Assert.Equal(m.M32, res.M32, 3);
}
[Fact]
public void Should_Generate_SkewTransform_minus_45_degrees()
{
LayoutTransformControl lt = CreateWithChildAndMeasureAndTransform(
100,
100,
new SkewTransform() { AngleX = -45, AngleY = -45 });
Assert.NotNull(lt.TransformRoot.RenderTransform);
Matrix m = lt.TransformRoot.RenderTransform.Value;
Matrix res = Matrix.CreateSkew(Matrix.ToRadians(-45), Matrix.ToRadians(-45));
Assert.Equal(m.M11, res.M11, 3);
Assert.Equal(m.M12, res.M12, 3);
Assert.Equal(m.M21, res.M21, 3);
Assert.Equal(m.M22, res.M22, 3);
Assert.Equal(m.M31, res.M31, 3);
Assert.Equal(m.M32, res.M32, 3);
}
private static void TransformMeasureSizeTest(Size size, Transform transform, Size expectedSize)
{
LayoutTransformControl lt = CreateWithChildAndMeasureAndTransform(
size.Width,
size.Height,
transform);
Size outSize = lt.DesiredSize;
Assert.Equal(outSize.Width, expectedSize.Width);
Assert.Equal(outSize.Height, expectedSize.Height);
}
private static void TransformRootBoundsTest(Size size, Transform transform, Rect expectedBounds)
{
LayoutTransformControl lt = CreateWithChildAndMeasureAndTransform(size.Width, size.Height, transform);
Rect outBounds = lt.TransformRoot.Bounds;
Assert.Equal(outBounds.X, expectedBounds.X);
Assert.Equal(outBounds.Y, expectedBounds.Y);
Assert.Equal(outBounds.Width, expectedBounds.Width);
Assert.Equal(outBounds.Height, expectedBounds.Height);
}
private static LayoutTransformControl CreateWithChildAndMeasureAndTransform(
double width,
double height,
Transform transform)
{
var lt = new LayoutTransformControl()
{
LayoutTransform = transform,
Template = new FuncControlTemplate<LayoutTransformControl>(
p => new ContentPresenter() { Content = p.Content })
};
lt.Content = new Rectangle() { Width = width, Height = height };
lt.ApplyTemplate();
//we need to force create visual child
//so the measure after is correct
(lt.Presenter as ContentPresenter).UpdateChild();
Assert.NotNull(lt.Presenter?.Child);
lt.Measure(Size.Infinity);
lt.Arrange(new Rect(lt.DesiredSize));
return lt;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Helper class for "Fix all occurrences" code fix providers.
/// </summary>
internal partial class BatchFixAllProvider : FixAllProvider, IIntervalIntrospector<TextChange>
{
public static readonly FixAllProvider Instance = new BatchFixAllProvider();
protected BatchFixAllProvider() { }
#region "AbstractFixAllProvider methods"
public override async Task<CodeAction> GetFixAsync(FixAllContext fixAllContext)
{
if (fixAllContext.Document != null)
{
var documentsAndDiagnosticsToFixMap = await fixAllContext.GetDocumentDiagnosticsToFixAsync().ConfigureAwait(false);
return await GetFixAsync(documentsAndDiagnosticsToFixMap, fixAllContext.State, fixAllContext.CancellationToken).ConfigureAwait(false);
}
else
{
var projectsAndDiagnosticsToFixMap = await fixAllContext.GetProjectDiagnosticsToFixAsync().ConfigureAwait(false);
return await GetFixAsync(projectsAndDiagnosticsToFixMap, fixAllContext.State, fixAllContext.CancellationToken).ConfigureAwait(false);
}
}
#endregion
internal override async Task<CodeAction> GetFixAsync(
ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentsAndDiagnosticsToFixMap,
FixAllState fixAllState, CancellationToken cancellationToken)
{
if (documentsAndDiagnosticsToFixMap?.Any() == true)
{
FixAllLogger.LogDiagnosticsStats(documentsAndDiagnosticsToFixMap);
var diagnosticsAndCodeActions = await GetDiagnosticsAndCodeActions(
documentsAndDiagnosticsToFixMap, fixAllState, cancellationToken).ConfigureAwait(false);
if (diagnosticsAndCodeActions.Length > 0)
{
using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Merge, cancellationToken))
{
FixAllLogger.LogFixesToMergeStats(diagnosticsAndCodeActions.Length);
return await TryGetMergedFixAsync(
diagnosticsAndCodeActions, fixAllState, cancellationToken).ConfigureAwait(false);
}
}
}
return null;
}
private async Task<ImmutableArray<(Diagnostic diagnostic, CodeAction action)>> GetDiagnosticsAndCodeActions(
ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentsAndDiagnosticsToFixMap,
FixAllState fixAllState, CancellationToken cancellationToken)
{
var fixesBag = new ConcurrentBag<(Diagnostic diagnostic, CodeAction action)>();
using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Fixes, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
var tasks = new List<Task>();
foreach (var kvp in documentsAndDiagnosticsToFixMap)
{
var document = kvp.Key;
var diagnosticsToFix = kvp.Value;
Debug.Assert(!diagnosticsToFix.IsDefaultOrEmpty);
if (!diagnosticsToFix.IsDefaultOrEmpty)
{
tasks.Add(AddDocumentFixesAsync(
document, diagnosticsToFix, fixesBag, fixAllState, cancellationToken));
}
}
await Task.WhenAll(tasks).ConfigureAwait(false);
}
return fixesBag.ToImmutableArray();
}
protected async virtual Task AddDocumentFixesAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> fixes,
FixAllState fixAllState, CancellationToken cancellationToken)
{
Debug.Assert(!diagnostics.IsDefault);
cancellationToken.ThrowIfCancellationRequested();
var registerCodeFix = GetRegisterCodeFixAction(fixAllState, fixes);
var fixerTasks = new List<Task>();
foreach (var diagnostic in diagnostics)
{
cancellationToken.ThrowIfCancellationRequested();
fixerTasks.Add(Task.Run(() =>
{
var context = new CodeFixContext(document, diagnostic, registerCodeFix, cancellationToken);
// TODO: Wrap call to ComputeFixesAsync() below in IExtensionManager.PerformFunctionAsync() so that
// a buggy extension that throws can't bring down the host?
return fixAllState.CodeFixProvider.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask;
}));
}
await Task.WhenAll(fixerTasks).ConfigureAwait(false);
}
internal override async Task<CodeAction> GetFixAsync(
ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectsAndDiagnosticsToFixMap,
FixAllState fixAllState, CancellationToken cancellationToken)
{
if (projectsAndDiagnosticsToFixMap != null && projectsAndDiagnosticsToFixMap.Any())
{
FixAllLogger.LogDiagnosticsStats(projectsAndDiagnosticsToFixMap);
var bag = new ConcurrentBag<(Diagnostic diagnostic, CodeAction action)>();
using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Fixes, cancellationToken))
{
var projects = projectsAndDiagnosticsToFixMap.Keys;
var tasks = projects.Select(p => AddProjectFixesAsync(
p, projectsAndDiagnosticsToFixMap[p], bag, fixAllState, cancellationToken)).ToArray();
await Task.WhenAll(tasks).ConfigureAwait(false);
}
var result = bag.ToImmutableArray();
if (result.Length > 0)
{
using (Logger.LogBlock(FunctionId.CodeFixes_FixAllOccurrencesComputation_Merge, cancellationToken))
{
FixAllLogger.LogFixesToMergeStats(result.Length);
return await TryGetMergedFixAsync(
result, fixAllState, cancellationToken).ConfigureAwait(false);
}
}
}
return null;
}
private static Action<CodeAction, ImmutableArray<Diagnostic>> GetRegisterCodeFixAction(
FixAllState fixAllState,
ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> result)
=> (action, diagnostics) =>
{
if (action != null && action.EquivalenceKey == fixAllState.CodeActionEquivalenceKey)
{
result.Add((diagnostics.First(), action));
}
};
protected virtual Task AddProjectFixesAsync(
Project project, ImmutableArray<Diagnostic> diagnostics,
ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> fixes,
FixAllState fixAllState, CancellationToken cancellationToken)
{
Debug.Assert(!diagnostics.IsDefault);
cancellationToken.ThrowIfCancellationRequested();
var registerCodeFix = GetRegisterCodeFixAction(fixAllState, fixes);
var context = new CodeFixContext(
project, diagnostics, registerCodeFix, cancellationToken);
// TODO: Wrap call to ComputeFixesAsync() below in IExtensionManager.PerformFunctionAsync() so that
// a buggy extension that throws can't bring down the host?
return fixAllState.CodeFixProvider.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask;
}
public virtual async Task<CodeAction> TryGetMergedFixAsync(
ImmutableArray<(Diagnostic diagnostic, CodeAction action)> batchOfFixes,
FixAllState fixAllState, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(batchOfFixes.Any());
var solution = fixAllState.Solution;
var newSolution = await TryMergeFixesAsync(
solution, batchOfFixes, fixAllState, cancellationToken).ConfigureAwait(false);
if (newSolution != null && newSolution != solution)
{
var title = GetFixAllTitle(fixAllState);
return new CodeAction.SolutionChangeAction(title, _ => Task.FromResult(newSolution));
}
return null;
}
public virtual string GetFixAllTitle(FixAllState fixAllState)
{
return fixAllState.GetDefaultFixAllTitle();
}
public virtual async Task<Solution> TryMergeFixesAsync(
Solution oldSolution,
ImmutableArray<(Diagnostic diagnostic, CodeAction action)> diagnosticsAndCodeActions,
FixAllState fixAllState, CancellationToken cancellationToken)
{
var documentIdToChangedDocuments = await GetDocumentIdToChangedDocuments(
oldSolution, diagnosticsAndCodeActions, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
// Now, in parallel, process all the changes to any individual document, producing
// the final source text for any given document.
var documentIdToFinalText = await GetDocumentIdToFinalTextAsync(
oldSolution, documentIdToChangedDocuments,
diagnosticsAndCodeActions, cancellationToken).ConfigureAwait(false);
// Finally, apply the changes to each document to the solution, producing the
// new solution.
var currentSolution = oldSolution;
foreach (var kvp in documentIdToFinalText)
{
currentSolution = currentSolution.WithDocumentText(kvp.Key, kvp.Value);
}
return currentSolution;
}
private async Task<IReadOnlyDictionary<DocumentId, ConcurrentBag<(CodeAction, Document)>>> GetDocumentIdToChangedDocuments(
Solution oldSolution,
ImmutableArray<(Diagnostic diagnostic, CodeAction action)> diagnosticsAndCodeActions,
CancellationToken cancellationToken)
{
var documentIdToChangedDocuments = new ConcurrentDictionary<DocumentId, ConcurrentBag<(CodeAction, Document)>>();
// Process all code actions in parallel to find all the documents that are changed.
// For each changed document, also keep track of the associated code action that
// produced it.
var getChangedDocumentsTasks = new List<Task>();
foreach (var diagnosticAndCodeAction in diagnosticsAndCodeActions)
{
getChangedDocumentsTasks.Add(GetChangedDocumentsAsync(
oldSolution, documentIdToChangedDocuments,
diagnosticAndCodeAction.action, cancellationToken));
}
await Task.WhenAll(getChangedDocumentsTasks).ConfigureAwait(false);
return documentIdToChangedDocuments;
}
private async Task<IReadOnlyDictionary<DocumentId, SourceText>> GetDocumentIdToFinalTextAsync(
Solution oldSolution,
IReadOnlyDictionary<DocumentId, ConcurrentBag<(CodeAction, Document)>> documentIdToChangedDocuments,
ImmutableArray<(Diagnostic diagnostic, CodeAction action)> diagnosticsAndCodeActions,
CancellationToken cancellationToken)
{
// We process changes to a document in 'Diagnostic' order. i.e. we apply the change
// created for an earlier diagnostic before the change applied to a later diagnostic.
// It's as if we processed the diagnostics in the document, in order, finding the code
// action for it and applying it right then.
var codeActionToDiagnosticLocation = diagnosticsAndCodeActions.ToDictionary(
tuple => tuple.action, tuple => tuple.diagnostic?.Location.SourceSpan.Start ?? 0);
var documentIdToFinalText = new ConcurrentDictionary<DocumentId, SourceText>();
var getFinalDocumentTasks = new List<Task>();
foreach (var kvp in documentIdToChangedDocuments)
{
getFinalDocumentTasks.Add(GetFinalDocumentTextAsync(
oldSolution, codeActionToDiagnosticLocation, documentIdToFinalText,
kvp.Value, cancellationToken));
}
await Task.WhenAll(getFinalDocumentTasks).ConfigureAwait(false);
return documentIdToFinalText;
}
private async Task GetFinalDocumentTextAsync(
Solution oldSolution,
Dictionary<CodeAction, int> codeActionToDiagnosticLocation,
ConcurrentDictionary<DocumentId, SourceText> documentIdToFinalText,
IEnumerable<(CodeAction action, Document document)> changedDocuments,
CancellationToken cancellationToken)
{
// Merges all the text changes made to a single document by many code actions
// into the final text for that document.
var orderedDocuments = changedDocuments.OrderBy(t => codeActionToDiagnosticLocation[t.action])
.ThenBy(t => t.action.Title)
.ToImmutableArray();
if (orderedDocuments.Length == 1)
{
// Super simple case. Only one code action changed this document. Just use
// its final result.
var document = orderedDocuments[0].document;
var finalText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
documentIdToFinalText.TryAdd(document.Id, finalText);
return;
}
Debug.Assert(orderedDocuments.Length > 1);
// More complex case. We have multiple changes to the document. Apply them in order
// to get the final document.
var totalChangesIntervalTree = SimpleIntervalTree.Create(this);
var oldDocument = oldSolution.GetDocument(orderedDocuments[0].document.Id);
var differenceService = oldSolution.Workspace.Services.GetService<IDocumentTextDifferencingService>();
foreach (var (_, currentDocument) in orderedDocuments)
{
cancellationToken.ThrowIfCancellationRequested();
Debug.Assert(currentDocument.Id == oldDocument.Id);
await TryAddDocumentMergeChangesAsync(
differenceService,
oldDocument,
currentDocument,
totalChangesIntervalTree,
cancellationToken).ConfigureAwait(false);
}
// WithChanges requires a ordered list of TextChanges without any overlap.
var changesToApply = totalChangesIntervalTree.Distinct().OrderBy(tc => tc.Span.Start);
var oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
var newText = oldText.WithChanges(changesToApply);
documentIdToFinalText.TryAdd(oldDocument.Id, newText);
}
int IIntervalIntrospector<TextChange>.GetStart(TextChange value) => value.Span.Start;
int IIntervalIntrospector<TextChange>.GetLength(TextChange value) => value.Span.Length;
private static Func<DocumentId, ConcurrentBag<(CodeAction, Document)>> s_getValue =
_ => new ConcurrentBag<(CodeAction, Document)>();
private async Task GetChangedDocumentsAsync(
Solution oldSolution,
ConcurrentDictionary<DocumentId, ConcurrentBag<(CodeAction, Document)>> documentIdToChangedDocuments,
CodeAction codeAction,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var changedSolution = await codeAction.GetChangedSolutionInternalAsync(
cancellationToken: cancellationToken).ConfigureAwait(false);
var solutionChanges = new SolutionChanges(changedSolution, oldSolution);
// TODO: Handle added/removed documents
// TODO: Handle changed/added/removed additional documents
var documentIdsWithChanges = solutionChanges
.GetProjectChanges()
.SelectMany(p => p.GetChangedDocuments());
foreach (var documentId in documentIdsWithChanges)
{
var changedDocument = changedSolution.GetDocument(documentId);
documentIdToChangedDocuments.GetOrAdd(documentId, s_getValue).Add(
(codeAction, changedDocument));
}
}
/// <summary>
/// Try to merge the changes between <paramref name="newDocument"/> and <paramref name="oldDocument"/>
/// into <paramref name="cumulativeChanges"/>. If there is any conflicting change in
/// <paramref name="newDocument"/> with existing <paramref name="cumulativeChanges"/>, then no
/// changes are added
/// </summary>
private static async Task TryAddDocumentMergeChangesAsync(
IDocumentTextDifferencingService differenceService,
Document oldDocument,
Document newDocument,
SimpleIntervalTree<TextChange> cumulativeChanges,
CancellationToken cancellationToken)
{
var currentChanges = await differenceService.GetTextChangesAsync(
oldDocument, newDocument, cancellationToken).ConfigureAwait(false);
if (AllChangesCanBeApplied(cumulativeChanges, currentChanges))
{
foreach (var change in currentChanges)
{
cumulativeChanges.AddIntervalInPlace(change);
}
}
}
private static bool AllChangesCanBeApplied(
SimpleIntervalTree<TextChange> cumulativeChanges,
ImmutableArray<TextChange> currentChanges)
{
var overlappingSpans = ArrayBuilder<TextChange>.GetInstance();
var intersectingSpans = ArrayBuilder<TextChange>.GetInstance();
var result = AllChangesCanBeApplied(
cumulativeChanges, currentChanges,
overlappingSpans: overlappingSpans,
intersectingSpans: intersectingSpans);
overlappingSpans.Free();
intersectingSpans.Free();
return result;
}
private static bool AllChangesCanBeApplied(
SimpleIntervalTree<TextChange> cumulativeChanges,
ImmutableArray<TextChange> currentChanges,
ArrayBuilder<TextChange> overlappingSpans,
ArrayBuilder<TextChange> intersectingSpans)
{
foreach (var change in currentChanges)
{
overlappingSpans.Clear();
intersectingSpans.Clear();
cumulativeChanges.FillWithIntervalsThatOverlapWith(
change.Span.Start, change.Span.Length, overlappingSpans);
cumulativeChanges.FillWithIntervalsThatIntersectWith(
change.Span.Start, change.Span.Length, intersectingSpans);
var value = ChangeCanBeApplied(change,
overlappingSpans: overlappingSpans,
intersectingSpans: intersectingSpans);
if (!value)
{
return false;
}
}
// All the changes would merge in fine. We can absorb this.
return true;
}
private static bool ChangeCanBeApplied(
TextChange change,
ArrayBuilder<TextChange> overlappingSpans,
ArrayBuilder<TextChange> intersectingSpans)
{
// We distinguish two types of changes that can happen. 'Pure Insertions'
// and 'Overwrites'. Pure-Insertions are those that are just inserting
// text into a specific *position*. They do not replace any existing text.
// 'Overwrites' end up replacing existing text with some other piece of
// (possibly-empty) text.
//
// Overwrites of text tend to be easy to understand and merge. It is very
// clear what code is being overwritten and how it should interact with
// other changes. Pure-insertions are more ambiguous to deal with. For
// example, say there are two pure-insertions at some position. There is
// no way for us to know what to do with this. For example, we could take
// one insertion then the other, or vice versa. Because of this ambiguity
// we conservatively disallow cases like this.
return IsPureInsertion(change)
? PureInsertionChangeCanBeApplied(change, overlappingSpans, intersectingSpans)
: OverwriteChangeCanBeApplied(change, overlappingSpans, intersectingSpans);
}
private static bool IsPureInsertion(TextChange change)
=> change.Span.IsEmpty;
private static bool PureInsertionChangeCanBeApplied(
TextChange change,
ArrayBuilder<TextChange> overlappingSpans,
ArrayBuilder<TextChange> intersectingSpans)
{
// Pure insertions can't ever overlap anything. (They're just an insertion at a
// single position, and overlaps can't occur with single-positions).
Debug.Assert(IsPureInsertion(change));
Debug.Assert(overlappingSpans.Count == 0);
if (intersectingSpans.Count == 0)
{
// Our pure-insertion didn't hit any other changes. This is safe to apply.
return true;
}
if (intersectingSpans.Count == 1)
{
// Our pure-insertion hit another change. Thats safe when:
// 1) if both changes are the same.
// 2) the change we're hitting is an overwrite-change and we're at the end of it.
// Specifically, it is not safe for us to insert somewhere in start-to-middle of an
// existing overwrite-change. And if we have another pure-insertion change, then it's
// not safe for both of us to be inserting at the same point (except when the
// change is identical).
// Note: you may wonder why we don't support hitting an overwriting change at the
// start of the overwrite. This is because it's now ambiguous as to which of these
// changes should be applied first.
var otherChange = intersectingSpans[0];
if (otherChange == change)
{
// We're both pure-inserting the same text at the same position.
// We assume this is a case of some provider making the same changes and
// we allow this.
return true;
}
return !IsPureInsertion(otherChange) &&
otherChange.Span.End == change.Span.Start;
}
// We're intersecting multiple changes. That's never OK.
return false;
}
private static bool OverwriteChangeCanBeApplied(
TextChange change,
ArrayBuilder<TextChange> overlappingSpans,
ArrayBuilder<TextChange> intersectingSpans)
{
Debug.Assert(!IsPureInsertion(change));
return !OverwriteChangeConflictsWithOverlappingSpans(change, overlappingSpans) &&
!OverwriteChangeConflictsWithIntersectingSpans(change, intersectingSpans);
}
private static bool OverwriteChangeConflictsWithOverlappingSpans(
TextChange change,
ArrayBuilder<TextChange> overlappingSpans)
{
Debug.Assert(!IsPureInsertion(change));
if (overlappingSpans.Count == 0)
{
// This overwrite didn't overlap with any other changes. This change is safe to make.
return false;
}
// The change we want to make overlapped an existing change we're making. Only allow
// this if there was a single overlap and we are exactly the same change as it.
// Otherwise, this is a conflict.
var isSafe = overlappingSpans.Count == 1 && overlappingSpans[0] == change;
return !isSafe;
}
private static bool OverwriteChangeConflictsWithIntersectingSpans(
TextChange change,
ArrayBuilder<TextChange> intersectingSpans)
{
Debug.Assert(!IsPureInsertion(change));
// We care about our intersections with pure-insertion changes. Overwrite-changes that
// we overlap are already handled in OverwriteChangeConflictsWithOverlappingSpans.
// And overwrite spans that we abut (i.e. which we're adjacent to) are totally safe
// for both to be applied.
//
// However, pure-insertion changes are extremely ambiguous. It is not possible to tell which
// change should be applied first. So if we get any pure-insertions we have to bail
// on applying this span.
foreach (var otherSpan in intersectingSpans)
{
if (IsPureInsertion(otherSpan))
{
// Intersecting with a pure-insertion is too ambiguous, so we just consider
// this a conflict.
return true;
}
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Server.Botany.Components;
using Content.Server.Botany.Systems;
using Content.Shared.Atmos;
using Content.Shared.Popups;
using Content.Shared.Random.Helpers;
using Content.Shared.Tag;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype.List;
using Robust.Shared.Utility;
namespace Content.Server.Botany;
public enum HarvestType : byte
{
NoRepeat,
Repeat,
SelfHarvest
}
/*
public enum PlantSpread : byte
{
NoSpread,
Creepers,
Vines,
}
public enum PlantMutation : byte
{
NoMutation,
Mutable,
HighlyMutable,
}
public enum PlantCarnivorous : byte
{
NotCarnivorous,
EatPests,
EatLivingBeings,
}
public enum PlantJuicy : byte
{
NotJuicy,
Juicy,
Slippery,
}
*/
[DataDefinition]
public struct SeedChemQuantity
{
[DataField("Min")] public int Min;
[DataField("Max")] public int Max;
[DataField("PotencyDivisor")] public int PotencyDivisor;
}
[Prototype("seed")]
public sealed class SeedPrototype : IPrototype
{
public const string Prototype = "SeedBase";
[DataField("id", required: true)] public string ID { get; private init; } = default!;
/// <summary>
/// Unique identifier of this seed. Do NOT set this.
/// </summary>
public int Uid { get; internal set; } = -1;
#region Tracking
[DataField("name")] public string Name = string.Empty;
[DataField("seedName")] public string SeedName = string.Empty;
[DataField("seedNoun")] public string SeedNoun = "seeds";
[DataField("displayName")] public string DisplayName = string.Empty;
[DataField("roundStart")] public bool RoundStart = true;
[DataField("mysterious")] public bool Mysterious;
[DataField("immutable")] public bool Immutable;
#endregion
#region Output
[DataField("productPrototypes", customTypeSerializer: typeof(PrototypeIdListSerializer<EntityPrototype>))]
public List<string> ProductPrototypes = new();
[DataField("chemicals")] public Dictionary<string, SeedChemQuantity> Chemicals = new();
[DataField("consumeGasses")] public Dictionary<Gas, float> ConsumeGasses = new();
[DataField("exudeGasses")] public Dictionary<Gas, float> ExudeGasses = new();
#endregion
#region Tolerances
[DataField("nutrientConsumption")] public float NutrientConsumption = 0.25f;
[DataField("waterConsumption")] public float WaterConsumption = 3f;
[DataField("idealHeat")] public float IdealHeat = 293f;
[DataField("heatTolerance")] public float HeatTolerance = 20f;
[DataField("idealLight")] public float IdealLight = 7f;
[DataField("lightTolerance")] public float LightTolerance = 5f;
[DataField("toxinsTolerance")] public float ToxinsTolerance = 4f;
[DataField("lowPressureTolerance")] public float LowPressureTolerance = 25f;
[DataField("highPressureTolerance")] public float HighPressureTolerance = 200f;
[DataField("pestTolerance")] public float PestTolerance = 5f;
[DataField("weedTolerance")] public float WeedTolerance = 5f;
#endregion
#region General traits
[DataField("endurance")] public float Endurance = 100f;
[DataField("yield")] public int Yield;
[DataField("lifespan")] public float Lifespan;
[DataField("maturation")] public float Maturation;
[DataField("production")] public float Production;
[DataField("growthStages")] public int GrowthStages = 6;
[DataField("harvestRepeat")] public HarvestType HarvestRepeat = HarvestType.NoRepeat;
[DataField("potency")] public float Potency = 1f;
// No, I'm not removing these.
//public PlantSpread Spread { get; set; }
//public PlantMutation Mutation { get; set; }
//public float AlterTemperature { get; set; }
//public PlantCarnivorous Carnivorous { get; set; }
//public bool Parasite { get; set; }
//public bool Hematophage { get; set; }
//public bool Thorny { get; set; }
//public bool Stinging { get; set; }
[DataField("ligneous")] public bool Ligneous;
// public bool Teleporting { get; set; }
// public PlantJuicy Juicy { get; set; }
#endregion
#region Cosmetics
[DataField("plantRsi", required: true)]
public ResourcePath PlantRsi { get; set; } = default!;
[DataField("plantIconState")] public string PlantIconState { get; set; } = "produce";
[DataField("bioluminescent")] public bool Bioluminescent { get; set; }
[DataField("bioluminescentColor")] public Color BioluminescentColor { get; set; } = Color.White;
[DataField("splatPrototype")] public string? SplatPrototype { get; set; }
#endregion
public SeedPrototype Clone()
{
var newSeed = new SeedPrototype
{
ID = ID,
Name = Name,
SeedName = SeedName,
SeedNoun = SeedNoun,
RoundStart = RoundStart,
Mysterious = Mysterious,
ProductPrototypes = new List<string>(ProductPrototypes),
Chemicals = new Dictionary<string, SeedChemQuantity>(Chemicals),
ConsumeGasses = new Dictionary<Gas, float>(ConsumeGasses),
ExudeGasses = new Dictionary<Gas, float>(ExudeGasses),
NutrientConsumption = NutrientConsumption,
WaterConsumption = WaterConsumption,
IdealHeat = IdealHeat,
HeatTolerance = HeatTolerance,
IdealLight = IdealLight,
LightTolerance = LightTolerance,
ToxinsTolerance = ToxinsTolerance,
LowPressureTolerance = LowPressureTolerance,
HighPressureTolerance = HighPressureTolerance,
PestTolerance = PestTolerance,
WeedTolerance = WeedTolerance,
Endurance = Endurance,
Yield = Yield,
Lifespan = Lifespan,
Maturation = Maturation,
Production = Production,
GrowthStages = GrowthStages,
HarvestRepeat = HarvestRepeat,
Potency = Potency,
PlantRsi = PlantRsi,
PlantIconState = PlantIconState,
Bioluminescent = Bioluminescent,
BioluminescentColor = BioluminescentColor,
SplatPrototype = SplatPrototype
};
return newSeed;
}
public SeedPrototype Diverge(bool modified)
{
return Clone();
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using MonoTouch;
using AVFoundation;
using Foundation;
using UIKit;
using MonoTouch.Dialog;
using AudioToolbox;
using AudioUnit;
using CoreFoundation;
using AudioFileID = System.IntPtr;
namespace AudioQueueOfflineRenderDemo
{
[Register ("AppDelegate")]
public unsafe partial class AppDelegate : UIApplicationDelegate
{
UIWindow window;
DialogViewController dvc;
StyledStringElement element;
bool busy;
AVAudioPlayer player;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
dvc = new DialogViewController (new RootElement ("Audio Queue Offline Render Demo") {
new Section ("Audio Queue Offline Render Demo") {
(element = new StyledStringElement ("Render audio", RenderAudioAsync) { Alignment = UITextAlignment.Center }),
}
});
element.Alignment = UITextAlignment.Center;
window = new UIWindow (UIScreen.MainScreen.Bounds);
window.RootViewController = dvc;
window.MakeKeyAndVisible ();
return true;
}
void SetCaption (string caption)
{
BeginInvokeOnMainThread (() => {
element.Caption = caption;
dvc.ReloadData ();
});
}
void RenderAudioAsync ()
{
CFUrl sourceUrl = CFUrl.FromFile (NSBundle.MainBundle.PathForResource ("composeaudio", "mp3"));
CFUrl destinationUrl = CFUrl.FromFile (System.IO.Path.Combine (System.Environment.GetFolderPath (Environment.SpecialFolder.Personal), "output.caf"));
if (busy)
return;
busy = true;
SetCaption ("Rendering...");
var thread = new System.Threading.Thread (() => {
try {
RenderAudio (sourceUrl, destinationUrl);
} catch (Exception ex) {
Console.WriteLine (ex);
}
BeginInvokeOnMainThread (() => {
SetCaption ("Playing...");
using (var playUrl = new NSUrl (destinationUrl.FileSystemPath)) {
player = AVAudioPlayer.FromUrl (playUrl);
}
player.Play ();
player.FinishedPlaying += (sender, e) => {
BeginInvokeOnMainThread (() => {
player.Dispose ();
player = null;
SetCaption ("Render audio");
busy = false;
});
};
});
});
thread.IsBackground = true;
thread.Start ();
}
static void CalculateBytesForTime (AudioStreamBasicDescription desc, int maxPacketSize, double seconds, out int bufferSize, out int packetCount)
{
const int maxBufferSize = 0x10000;
const int minBufferSize = 0x4000;
if (desc.FramesPerPacket > 0) {
bufferSize = (int)(desc.SampleRate / desc.FramesPerPacket * seconds * maxPacketSize);
} else {
bufferSize = maxBufferSize > maxPacketSize ? maxBufferSize : maxPacketSize;
}
if (bufferSize > maxBufferSize && bufferSize > maxPacketSize) {
bufferSize = maxBufferSize;
} else if (bufferSize < minBufferSize) {
bufferSize = minBufferSize;
}
packetCount = bufferSize / maxPacketSize;
}
unsafe static void HandleOutput (AudioFile audioFile, AudioQueue queue, AudioQueueBuffer*audioQueueBuffer, ref int packetsToRead, ref long currentPacket, ref bool done, ref bool flushed, ref AudioStreamPacketDescription[] packetDescriptions)
{
int bytes;
int packets;
if (done)
return;
packets = packetsToRead;
bytes = (int)audioQueueBuffer->AudioDataBytesCapacity;
packetDescriptions = audioFile.ReadPacketData (false, currentPacket, ref packets, audioQueueBuffer->AudioData, ref bytes);
if (packets > 0) {
audioQueueBuffer->AudioDataByteSize = (uint)bytes;
queue.EnqueueBuffer (audioQueueBuffer, packetDescriptions);
currentPacket += packets;
} else {
if (!flushed) {
queue.Flush ();
flushed = true;
}
queue.Stop (false);
done = true;
}
}
unsafe static void RenderAudio (CFUrl sourceUrl, CFUrl destinationUrl)
{
AudioStreamBasicDescription dataFormat;
AudioQueueBuffer* buffer = null;
long currentPacket = 0;
int packetsToRead = 0;
AudioStreamPacketDescription[] packetDescs = null;
bool flushed = false;
bool done = false;
int bufferSize;
using (var audioFile = AudioFile.Open (sourceUrl, AudioFilePermission.Read, (AudioFileType)0)) {
dataFormat = audioFile.StreamBasicDescription;
using (var queue = new OutputAudioQueue (dataFormat, CFRunLoop.Current, CFRunLoop.ModeCommon)) {
queue.BufferCompleted += (sender, e) => {
HandleOutput (audioFile, queue, buffer, ref packetsToRead, ref currentPacket, ref done, ref flushed, ref packetDescs);
};
// we need to calculate how many packets we read at a time and how big a buffer we need
// we base this on the size of the packets in the file and an approximate duration for each buffer
bool isVBR = dataFormat.BytesPerPacket == 0 || dataFormat.FramesPerPacket == 0;
// first check to see what the max size of a packet is - if it is bigger
// than our allocation default size, that needs to become larger
// adjust buffer size to represent about a second of audio based on this format
CalculateBytesForTime (dataFormat, audioFile.MaximumPacketSize, 1.0, out bufferSize, out packetsToRead);
if (isVBR) {
packetDescs = new AudioStreamPacketDescription [packetsToRead];
} else {
packetDescs = null; // we don't provide packet descriptions for constant bit rate formats (like linear PCM)
}
if (audioFile.MagicCookie.Length != 0)
queue.MagicCookie = audioFile.MagicCookie;
// allocate the input read buffer
queue.AllocateBuffer (bufferSize, out buffer);
// prepare the capture format
var captureFormat = AudioStreamBasicDescription.CreateLinearPCM (dataFormat.SampleRate, (uint)dataFormat.ChannelsPerFrame, 32);
captureFormat.BytesPerFrame = captureFormat.BytesPerPacket = dataFormat.ChannelsPerFrame * 4;
queue.SetOfflineRenderFormat (captureFormat, audioFile.ChannelLayout);
// prepare the target format
var dstFormat = AudioStreamBasicDescription.CreateLinearPCM (dataFormat.SampleRate, (uint)dataFormat.ChannelsPerFrame);
using (var captureFile = ExtAudioFile.CreateWithUrl (destinationUrl, AudioFileType.CAF, dstFormat, AudioFileFlags.EraseFlags)) {
captureFile.ClientDataFormat = captureFormat;
int captureBufferSize = bufferSize / 2;
AudioBuffers captureABL = new AudioBuffers (1);
AudioQueueBuffer* captureBuffer;
queue.AllocateBuffer (captureBufferSize, out captureBuffer);
captureABL [0] = new AudioBuffer () {
Data = captureBuffer->AudioData,
NumberChannels = captureFormat.ChannelsPerFrame
};
queue.Start ();
double ts = 0;
queue.RenderOffline (ts, captureBuffer, 0);
HandleOutput (audioFile, queue, buffer, ref packetsToRead, ref currentPacket, ref done, ref flushed, ref packetDescs);
while (true) {
int reqFrames = captureBufferSize / captureFormat.BytesPerFrame;
queue.RenderOffline (ts, captureBuffer, reqFrames);
captureABL.SetData (0, captureBuffer->AudioData, (int)captureBuffer->AudioDataByteSize);
var writeFrames = captureABL [0].DataByteSize / captureFormat.BytesPerFrame;
// Console.WriteLine ("ts: {0} AudioQueueOfflineRender: req {1} frames / {2} bytes, got {3} frames / {4} bytes",
// ts, reqFrames, captureBufferSize, writeFrames, captureABL.Buffers [0].DataByteSize);
captureFile.WriteAsync ((uint)writeFrames, captureABL);
if (flushed)
break;
ts += writeFrames;
}
CFRunLoop.Current.RunInMode (CFRunLoop.ModeDefault, 1, false);
}
}
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data.
/// </summary>
public abstract class JsonReader : IDisposable
{
/// <summary>
/// Specifies the state of the reader.
/// </summary>
protected internal enum State
{
/// <summary>
/// The Read method has not been called.
/// </summary>
Start,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Complete,
/// <summary>
/// Reader is at a property.
/// </summary>
Property,
/// <summary>
/// Reader is at the start of an object.
/// </summary>
ObjectStart,
/// <summary>
/// Reader is in an object.
/// </summary>
Object,
/// <summary>
/// Reader is at the start of an array.
/// </summary>
ArrayStart,
/// <summary>
/// Reader is in an array.
/// </summary>
Array,
/// <summary>
/// The Close method has been called.
/// </summary>
Closed,
/// <summary>
/// Reader has just read a value.
/// </summary>
PostValue,
/// <summary>
/// Reader is at the start of a constructor.
/// </summary>
ConstructorStart,
/// <summary>
/// Reader in a constructor.
/// </summary>
Constructor,
/// <summary>
/// An error occurred that prevents the read operation from continuing.
/// </summary>
Error,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Finished
}
// current Token data
private JsonToken _tokenType;
private object _value;
internal char _quoteChar;
internal State _currentState;
internal ReadType _readType;
private JsonPosition _currentPosition;
private CultureInfo _culture;
private DateTimeZoneHandling _dateTimeZoneHandling;
private int? _maxDepth;
private bool _hasExceededMaxDepth;
internal DateParseHandling _dateParseHandling;
internal FloatParseHandling _floatParseHandling;
private string _dateFormatString;
private List<JsonPosition> _stack;
/// <summary>
/// Gets the current reader state.
/// </summary>
/// <value>The current reader state.</value>
protected State CurrentState
{
get { return _currentState; }
}
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the reader is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the reader is closed; otherwise false. The default is true.
/// </value>
public bool CloseInput { get; set; }
/// <summary>
/// Gets or sets a value indicating whether multiple pieces of JSON content can
/// be read from a continuous stream without erroring.
/// </summary>
/// <value>
/// true to support reading multiple pieces of JSON content; otherwise false. The default is false.
/// </value>
public bool SupportMultipleContent { get; set; }
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
public virtual char QuoteChar
{
get { return _quoteChar; }
protected internal set { _quoteChar = value; }
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling; }
set
{
if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
{
throw new ArgumentOutOfRangeException("value");
}
_dateTimeZoneHandling = value;
}
}
/// <summary>
/// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON.
/// </summary>
public DateParseHandling DateParseHandling
{
get { return _dateParseHandling; }
set
{
if (value < DateParseHandling.None ||
#if !NET20
value > DateParseHandling.DateTimeOffset
#else
value > DateParseHandling.DateTime
#endif
)
{
throw new ArgumentOutOfRangeException("value");
}
_dateParseHandling = value;
}
}
/// <summary>
/// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// </summary>
public FloatParseHandling FloatParseHandling
{
get { return _floatParseHandling; }
set
{
if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal)
{
throw new ArgumentOutOfRangeException("value");
}
_floatParseHandling = value;
}
}
/// <summary>
/// Get or set how custom date formatted strings are parsed when reading JSON.
/// </summary>
public string DateFormatString
{
get { return _dateFormatString; }
set { _dateFormatString = value; }
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
/// </summary>
public int? MaxDepth
{
get { return _maxDepth; }
set
{
if (value <= 0)
throw new ArgumentException("Value must be positive.", "value");
_maxDepth = value;
}
}
/// <summary>
/// Gets the type of the current JSON token.
/// </summary>
public virtual JsonToken TokenType
{
get { return _tokenType; }
}
/// <summary>
/// Gets the text value of the current JSON token.
/// </summary>
public virtual object Value
{
get { return _value; }
}
/// <summary>
/// Gets The Common Language Runtime (CLR) type for the current JSON token.
/// </summary>
public virtual Type ValueType
{
get { return (_value != null) ? _value.GetType() : null; }
}
/// <summary>
/// Gets the depth of the current token in the JSON document.
/// </summary>
/// <value>The depth of the current token in the JSON document.</value>
public virtual int Depth
{
get
{
int depth = (_stack != null) ? _stack.Count : 0;
if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
{
return depth;
}
else
{
return depth + 1;
}
}
}
/// <summary>
/// Gets the path of the current JSON token.
/// </summary>
public virtual string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
return string.Empty;
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null;
return JsonPosition.BuildPath(_stack, current);
}
}
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
internal JsonPosition GetPosition(int depth)
{
if (_stack != null && depth < _stack.Count)
{
return _stack[depth];
}
return _currentPosition;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
/// </summary>
protected JsonReader()
{
_currentState = State.Start;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
_dateParseHandling = DateParseHandling.DateTime;
_floatParseHandling = FloatParseHandling.Double;
CloseInput = true;
}
private void Push(JsonContainerType value)
{
UpdateScopeWithFinishedValue();
if (_currentPosition.Type == JsonContainerType.None)
{
_currentPosition = new JsonPosition(value);
}
else
{
if (_stack == null)
{
_stack = new List<JsonPosition>();
}
_stack.Add(_currentPosition);
_currentPosition = new JsonPosition(value);
// this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler
if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth)
{
_hasExceededMaxDepth = true;
throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
}
}
}
private JsonContainerType Pop()
{
JsonPosition oldPosition;
if (_stack != null && _stack.Count > 0)
{
oldPosition = _currentPosition;
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
oldPosition = _currentPosition;
_currentPosition = new JsonPosition();
}
if (_maxDepth != null && Depth <= _maxDepth)
{
_hasExceededMaxDepth = false;
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns>
public abstract bool Read();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract int? ReadAsInt32();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract string ReadAsString();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Byte"/>[].
/// </summary>
/// <returns>A <see cref="Byte"/>[] or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns>
public abstract byte[] ReadAsBytes();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract decimal? ReadAsDecimal();
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{DateTime}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract DateTime? ReadAsDateTime();
#if !NET20
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns>
public abstract DateTimeOffset? ReadAsDateTimeOffset();
#endif
internal virtual bool ReadInternal()
{
throw new NotImplementedException();
}
#if !NET20
internal DateTimeOffset? ReadAsDateTimeOffsetInternal()
{
_readType = ReadType.ReadAsDateTimeOffset;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Date)
{
if (Value is DateTime)
SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), false);
return (DateTimeOffset)Value;
}
if (t == JsonToken.Null)
return null;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
DateTimeOffset dt;
if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out dt))
{
SetToken(JsonToken.Date, dt, false);
return dt;
}
if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
SetToken(JsonToken.Date, dt, false);
return dt;
}
throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
#endif
internal byte[] ReadAsBytesInternal()
{
_readType = ReadType.ReadAsBytes;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (IsWrappedInTypeObject())
{
byte[] data = ReadAsBytes();
ReadInternal();
SetToken(JsonToken.Bytes, data, false);
return data;
}
// attempt to convert possible base 64 or GUID string to bytes
// GUID has to have format 00000000-0000-0000-0000-000000000000
if (t == JsonToken.String)
{
string s = (string)Value;
byte[] data;
Guid g;
if (s.Length == 0)
{
data = new byte[0];
}
else if (ConvertUtils.TryConvertGuid(s, out g))
{
data = g.ToByteArray();
}
else
{
data = Convert.FromBase64String(s);
}
SetToken(JsonToken.Bytes, data, false);
return data;
}
if (t == JsonToken.Null)
return null;
if (t == JsonToken.Bytes)
{
if (ValueType == typeof(Guid))
{
byte[] data = ((Guid)Value).ToByteArray();
SetToken(JsonToken.Bytes, data, false);
return data;
}
return (byte[])Value;
}
if (t == JsonToken.StartArray)
{
List<byte> data = new List<byte>();
while (ReadInternal())
{
t = TokenType;
switch (t)
{
case JsonToken.Integer:
data.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
break;
case JsonToken.EndArray:
byte[] d = data.ToArray();
SetToken(JsonToken.Bytes, d, false);
return d;
case JsonToken.Comment:
// skip
break;
default:
throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
}
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal decimal? ReadAsDecimalInternal()
{
_readType = ReadType.ReadAsDecimal;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Integer || t == JsonToken.Float)
{
if (!(Value is decimal))
SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), false);
return (decimal)Value;
}
if (t == JsonToken.Null)
return null;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
decimal d;
if (decimal.TryParse(s, NumberStyles.Number, Culture, out d))
{
SetToken(JsonToken.Float, d, false);
return d;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal int? ReadAsInt32Internal()
{
_readType = ReadType.ReadAsInt32;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.Integer || t == JsonToken.Float)
{
if (!(Value is int))
SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), false);
return (int)Value;
}
if (t == JsonToken.Null)
return null;
int i;
if (t == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
if (int.TryParse(s, NumberStyles.Integer, Culture, out i))
{
SetToken(JsonToken.Integer, i, false);
return i;
}
else
{
throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
internal string ReadAsStringInternal()
{
_readType = ReadType.ReadAsString;
JsonToken t;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
if (t == JsonToken.String)
return (string)Value;
if (t == JsonToken.Null)
return null;
if (JsonTokenUtils.IsPrimitiveToken(t))
{
if (Value != null)
{
string s;
if (Value is IFormattable)
s = ((IFormattable)Value).ToString(null, Culture);
else
s = Value.ToString();
SetToken(JsonToken.String, s, false);
return s;
}
}
if (t == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal DateTime? ReadAsDateTimeInternal()
{
_readType = ReadType.ReadAsDateTime;
do
{
if (!ReadInternal())
{
SetToken(JsonToken.None);
return null;
}
} while (TokenType == JsonToken.Comment);
if (TokenType == JsonToken.Date)
return (DateTime)Value;
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.String)
{
string s = (string)Value;
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null);
return null;
}
DateTime dt;
if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt, false);
return dt;
}
if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt, false);
return dt;
}
throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value));
}
if (TokenType == JsonToken.EndArray)
return null;
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
private bool IsWrappedInTypeObject()
{
_readType = ReadType.Read;
if (TokenType == JsonToken.StartObject)
{
if (!ReadInternal())
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
if (Value.ToString() == JsonTypeReflector.TypePropertyName)
{
ReadInternal();
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
ReadInternal();
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
{
return true;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
return false;
}
/// <summary>
/// Skips the children of the current token.
/// </summary>
public void Skip()
{
if (TokenType == JsonToken.PropertyName)
Read();
if (JsonTokenUtils.IsStartToken(TokenType))
{
int depth = Depth;
while (Read() && (depth < Depth))
{
}
}
}
/// <summary>
/// Sets the current token.
/// </summary>
/// <param name="newToken">The new token.</param>
protected void SetToken(JsonToken newToken)
{
SetToken(newToken, null, true);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
protected void SetToken(JsonToken newToken, object value)
{
SetToken(newToken, value, true);
}
internal void SetToken(JsonToken newToken, object value, bool updateIndex)
{
_tokenType = newToken;
_value = value;
switch (newToken)
{
case JsonToken.StartObject:
_currentState = State.ObjectStart;
Push(JsonContainerType.Object);
break;
case JsonToken.StartArray:
_currentState = State.ArrayStart;
Push(JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
_currentState = State.ConstructorStart;
Push(JsonContainerType.Constructor);
break;
case JsonToken.EndObject:
ValidateEnd(JsonToken.EndObject);
break;
case JsonToken.EndArray:
ValidateEnd(JsonToken.EndArray);
break;
case JsonToken.EndConstructor:
ValidateEnd(JsonToken.EndConstructor);
break;
case JsonToken.PropertyName:
_currentState = State.Property;
_currentPosition.PropertyName = (string)value;
break;
case JsonToken.Undefined:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.String:
case JsonToken.Raw:
case JsonToken.Bytes:
SetPostValueState(updateIndex);
break;
}
}
internal void SetPostValueState(bool updateIndex)
{
if (Peek() != JsonContainerType.None)
_currentState = State.PostValue;
else
SetFinished();
if (updateIndex)
UpdateScopeWithFinishedValue();
}
private void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
_currentPosition.Position++;
}
private void ValidateEnd(JsonToken endToken)
{
JsonContainerType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject)
throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject));
if (Peek() != JsonContainerType.None)
_currentState = State.PostValue;
else
SetFinished();
}
/// <summary>
/// Sets the state based on current token type.
/// </summary>
protected void SetStateBasedOnCurrent()
{
JsonContainerType currentObject = Peek();
switch (currentObject)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Constructor;
break;
case JsonContainerType.None:
SetFinished();
break;
default:
throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject));
}
}
private void SetFinished()
{
if (SupportMultipleContent)
_currentState = State.Start;
else
_currentState = State.Finished;
}
private JsonContainerType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JsonContainerType.Object;
case JsonToken.EndArray:
return JsonContainerType.Array;
case JsonToken.EndConstructor:
return JsonContainerType.Constructor;
default:
throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token));
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
void IDisposable.Dispose()
{
Dispose(true);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
Close();
}
/// <summary>
/// Changes the <see cref="State"/> to Closed.
/// </summary>
public virtual void Close()
{
_currentState = State.Closed;
_tokenType = JsonToken.None;
_value = null;
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.ComponentModel;
using Axiom.MathLib;
using Axiom.SceneManagers.Multiverse;
namespace Multiverse.Tools.WorldEditor
{
public class AlphaSplatTerrainDisplay : IWorldObject
{
protected WorldTerrain parent;
protected WorldEditor app;
protected WorldTreeNode node;
protected WorldTreeNode parentNode;
protected float textureTileSize = 5;
protected bool useParams = true;
protected string alpha0MosaicName;
protected string alpha1MosaicName;
protected string l1TextureName = "";
protected string l2TextureName = "";
protected string l3TextureName = "";
protected string l4TextureName = "";
protected string l5TextureName = "";
protected string l6TextureName = "";
protected string l7TextureName = "";
protected string l8TextureName = "";
protected string detailTextureName = "";
protected bool inScene = false;
protected bool inTree = false;
protected AlphaSplatTerrainConfig terrainConfig;
protected List<ToolStripButton> buttonBar;
public AlphaSplatTerrainDisplay(WorldTerrain parent, WorldEditor worldEditor)
{
this.parent = parent;
this.app = worldEditor;
}
public AlphaSplatTerrainDisplay(WorldTerrain parent, WorldEditor worldEditor, XmlReader r)
{
this.parent = parent;
this.app = worldEditor;
FromXml(r);
}
[DescriptionAttribute("Set this property to false if you are using your own terrain material that uses different vertex and pixel shader parameters than the default terrain shaders provided by Multiverse."), CategoryAttribute("Display Parameters")]
public bool UseParams
{
get
{
return useParams;
}
set
{
useParams = value;
if (inScene)
{
terrainConfig.UseParams = useParams;
}
}
}
[DescriptionAttribute("Area (in meters) covered by one terrain texture tile."), CategoryAttribute("Display Parameters")]
public float TextureTileSize
{
get
{
return textureTileSize;
}
set
{
textureTileSize = value;
if (inScene)
{
terrainConfig.TextureTileSize = textureTileSize;
}
}
}
[BrowsableAttribute(true), CategoryAttribute("Alpha Map Mosaics"), DescriptionAttribute("Name of the texture mosaic file in the asset repository to use for layers 1-4.")]
public string Alpha0MosaicName
{
get
{
return alpha0MosaicName;
}
set
{
alpha0MosaicName = value;
if (inScene)
{
terrainConfig.SetAlphaMapName(0, alpha0MosaicName);
}
}
}
[BrowsableAttribute(true), CategoryAttribute("Alpha Map Mosaics"), DescriptionAttribute("Name of the texture mosaic file in the asset repository to use for layers 5-8.")]
public string Alpha1MosaicName
{
get
{
return alpha1MosaicName;
}
set
{
alpha1MosaicName = value;
if (inScene)
{
terrainConfig.SetAlphaMapName(1, alpha1MosaicName);
}
}
}
[EditorAttribute(typeof(TextureSelectorTypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Name of the texture file in the asset repository to use for layer 1. This texture corresponds with the red channel of Alpha map 0."), CategoryAttribute("Display Parameters")]
public string Layer1TextureName
{
get
{
return l1TextureName;
}
set
{
l1TextureName = value;
if (inScene)
{
terrainConfig.SetLayerTextureName(0, l1TextureName);
}
}
}
[EditorAttribute(typeof(TextureSelectorTypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Name of the texture file in the asset repository to use for layer 2. This texture corresponds with the green channel of Alpha map 0."), CategoryAttribute("Display Parameters")]
public string Layer2TextureName
{
get
{
return l2TextureName;
}
set
{
l2TextureName = value;
if (inScene)
{
terrainConfig.SetLayerTextureName(1, l2TextureName);
}
}
}
[EditorAttribute(typeof(TextureSelectorTypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Name of the texture file in the asset repository to use for layer 3. This texture corresponds with the blue channel of Alpha map 0."), CategoryAttribute("Display Parameters")]
public string Layer3TextureName
{
get
{
return l3TextureName;
}
set
{
l3TextureName = value;
if (inScene)
{
terrainConfig.SetLayerTextureName(2, l3TextureName);
}
}
}
[EditorAttribute(typeof(TextureSelectorTypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Name of the texture file in the asset repository to use for layer 4. This texture corresponds with the alpha channel of Alpha map 0."), CategoryAttribute("Display Parameters")]
public string Layer4TextureName
{
get
{
return l4TextureName;
}
set
{
l4TextureName = value;
if (inScene)
{
terrainConfig.SetLayerTextureName(3, l4TextureName);
}
}
}
[EditorAttribute(typeof(TextureSelectorTypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Name of the texture file in the asset repository to use for layer 5. This texture corresponds with the red channel of Alpha map 1."), CategoryAttribute("Display Parameters")]
public string Layer5TextureName
{
get
{
return l5TextureName;
}
set
{
l5TextureName = value;
if (inScene)
{
terrainConfig.SetLayerTextureName(4, l5TextureName);
}
}
}
[EditorAttribute(typeof(TextureSelectorTypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Name of the texture file in the asset repository to use for layer 6. This texture corresponds with the green channel of Alpha map 1."), CategoryAttribute("Display Parameters")]
public string Layer6TextureName
{
get
{
return l6TextureName;
}
set
{
l6TextureName = value;
if (inScene)
{
terrainConfig.SetLayerTextureName(5, l6TextureName);
}
}
}
[EditorAttribute(typeof(TextureSelectorTypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Name of the texture file in the asset repository to use for layer 7. This texture corresponds with the blue channel of Alpha map 1."), CategoryAttribute("Display Parameters")]
public string Layer7TextureName
{
get
{
return l7TextureName;
}
set
{
l7TextureName = value;
if (inScene)
{
terrainConfig.SetLayerTextureName(6, l7TextureName);
}
}
}
[EditorAttribute(typeof(TextureSelectorTypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Name of the texture file in the asset repository to use for layer 8. This texture corresponds with the alpha channel of Alpha map 1."), CategoryAttribute("Display Parameters")]
public string Layer8TextureName
{
get
{
return l8TextureName;
}
set
{
l8TextureName = value;
if (inScene)
{
terrainConfig.SetLayerTextureName(7, l8TextureName);
}
}
}
[EditorAttribute(typeof(TextureSelectorTypeEditor), typeof(System.Drawing.Design.UITypeEditor)), DescriptionAttribute("Name of the texture file in the asset repository to use as a detail map."), CategoryAttribute("Display Parameters")]
public string DetailTextureName
{
get
{
return detailTextureName;
}
set
{
detailTextureName = value;
if (inScene)
{
terrainConfig.DetailTextureName = detailTextureName;
}
}
}
#region IWorldObject Members
public void AddToTree(WorldTreeNode parentNode)
{
this.parentNode = parentNode;
// add the terrain node
node = app.MakeTreeNode(this, "Terrain Display");
parentNode.Nodes.Add(node);
CommandMenuBuilder menuBuilder = new CommandMenuBuilder();
menuBuilder.Add("Copy Description", "", app.copyToClipboardMenuButton_Click);
menuBuilder.Add("Help", "Alpha_Splat_Terrain_Display", app.HelpClickHandler);
node.ContextMenuStrip = menuBuilder.Menu;
inTree = true;
buttonBar = menuBuilder.ButtonBar;
}
[BrowsableAttribute(false)]
public List<ToolStripButton> ButtonBar
{
get
{
return buttonBar;
}
}
public void Clone(IWorldContainer copyParent)
{
}
[BrowsableAttribute(false)]
public bool WorldViewSelectable
{
get
{
return false;
}
set
{
// this property is not applicable to this object
}
}
[BrowsableAttribute(false)]
public string ObjectAsString
{
get
{
string objString = String.Format("Name:{0}\r\n", ObjectType);
objString += String.Format("\tUseParams={0}\r\n",UseParams);
objString += String.Format("\tTextureTileSize:{0}\r\n",TextureTileSize);
objString += String.Format("\tAlpha0MosaicName:{0}\r\n",Alpha0MosaicName);
objString += String.Format("\tAlpha1MosaicName:{0}\r\n",Alpha1MosaicName);
objString += String.Format("\tLayer1TextureName:{0}\r\n",Layer1TextureName);
objString += String.Format("\tLayer2TextureName:{0}\r\n",Layer2TextureName);
objString += String.Format("\tLayer3TextureName:{0}\r\n",Layer3TextureName);
objString += String.Format("\tLayer4TextureName:{0}\r\n",Layer4TextureName);
objString += String.Format("\tLayer5TextureName:{0}\r\n",Layer5TextureName);
objString += String.Format("\tLayer6TextureName:{0}\r\n",Layer6TextureName);
objString += String.Format("\tLayer7TextureName:{0}\r\n",Layer7TextureName);
objString += String.Format("\tLayer8TextureName:{0}\r\n",Layer8TextureName);
objString += String.Format("\tDetailTextureName:{0}\r\n",DetailTextureName);
objString += "\r\n";
return objString;
}
}
[BrowsableAttribute(false)]
public bool AcceptObjectPlacement
{
get
{
return false;
}
set
{
//not implemented for this type of object
}
}
public void RemoveFromTree()
{
if (node.IsSelected)
{
node.UnSelect();
}
parentNode.Nodes.Remove(node);
parentNode = null;
node = null;
inTree = false;
}
public void AddToScene()
{
inScene = true;
terrainConfig = new AlphaSplatTerrainConfig();
terrainConfig.UseParams = useParams;
terrainConfig.TextureTileSize = textureTileSize;
terrainConfig.SetAlphaMapName(0, alpha0MosaicName);
terrainConfig.SetAlphaMapName(1, alpha1MosaicName);
terrainConfig.SetLayerTextureName(0, l1TextureName);
terrainConfig.SetLayerTextureName(1, l2TextureName);
terrainConfig.SetLayerTextureName(2, l3TextureName);
terrainConfig.SetLayerTextureName(3, l4TextureName);
terrainConfig.SetLayerTextureName(4, l5TextureName);
terrainConfig.SetLayerTextureName(5, l6TextureName);
terrainConfig.SetLayerTextureName(6, l7TextureName);
terrainConfig.SetLayerTextureName(7, l8TextureName);
terrainConfig.DetailTextureName = detailTextureName;
TerrainManager.Instance.TerrainMaterialConfig = terrainConfig;
}
public void RemoveFromScene()
{
inScene = false;
}
protected void CheckAsset(string name)
{
if ((name != null) && (name != ""))
{
if (!app.CheckAssetFileExists(name))
{
app.AddMissingAsset(name);
}
}
}
[BrowsableAttribute(false)]
public bool IsGlobal
{
get
{
return true;
}
}
[BrowsableAttribute(false)]
public bool IsTopLevel
{
get
{
return false;
}
}
public void CheckAssets()
{
if ((alpha0MosaicName != null) && (alpha0MosaicName != ""))
{
CheckAsset(string.Format("{0}.mmf", alpha0MosaicName));
}
if ((alpha1MosaicName != null) && (alpha1MosaicName != ""))
{
CheckAsset(string.Format("{0}.mmf", alpha1MosaicName));
}
CheckAsset(l1TextureName);
CheckAsset(l2TextureName);
CheckAsset(l3TextureName);
CheckAsset(l4TextureName);
CheckAsset(l5TextureName);
CheckAsset(l6TextureName);
CheckAsset(l7TextureName);
CheckAsset(l8TextureName);
CheckAsset(detailTextureName);
}
public void ToXml(System.Xml.XmlWriter w)
{
w.WriteStartElement("TerrainDisplay");
w.WriteAttributeString("Type", "AlphaSplat");
w.WriteAttributeString("UseParams", useParams.ToString());
w.WriteAttributeString("TextureTileSize", textureTileSize.ToString());
w.WriteAttributeString("Alpha0MosaicName", alpha0MosaicName);
w.WriteAttributeString("Alpha1MosaicName", alpha1MosaicName);
w.WriteAttributeString("Layer1TextureName", l1TextureName);
w.WriteAttributeString("Layer2TextureName", l2TextureName);
w.WriteAttributeString("Layer3TextureName", l3TextureName);
w.WriteAttributeString("Layer4TextureName", l4TextureName);
w.WriteAttributeString("Layer5TextureName", l5TextureName);
w.WriteAttributeString("Layer6TextureName", l6TextureName);
w.WriteAttributeString("Layer7TextureName", l7TextureName);
w.WriteAttributeString("Layer8TextureName", l8TextureName);
w.WriteAttributeString("DetailTextureName", detailTextureName);
w.WriteEndElement();
}
public void FromXml(XmlReader r)
{
for (int i = 0; i < r.AttributeCount; i++)
{
r.MoveToAttribute(i);
switch (r.Name)
{
case "Type":
break;
case "UseParams":
useParams = (r.Value == "True");
break;
case "TextureTileSize":
textureTileSize = float.Parse(r.Value);
break;
case "Alpha0MosaicName":
alpha0MosaicName = r.Value;
break;
case "Alpha1MosaicName":
alpha1MosaicName = r.Value;
break;
case "Layer1TextureName":
l1TextureName = r.Value;
break;
case "Layer2TextureName":
l2TextureName = r.Value;
break;
case "Layer3TextureName":
l3TextureName = r.Value;
break;
case "Layer4TextureName":
l4TextureName = r.Value;
break;
case "Layer5TextureName":
l5TextureName = r.Value;
break;
case "Layer6TextureName":
l6TextureName = r.Value;
break;
case "Layer7TextureName":
l7TextureName = r.Value;
break;
case "Layer8TextureName":
l8TextureName = r.Value;
break;
case "DetailTextureName":
detailTextureName = r.Value;
break;
}
}
r.MoveToElement();
}
[BrowsableAttribute(false)]
public Vector3 FocusLocation
{
get
{
return Vector3.Zero;
}
}
[BrowsableAttribute(false)]
public bool Highlight
{
get
{
return false;
}
set
{
// do nothing
}
}
[BrowsableAttribute(false)]
public WorldTreeNode Node
{
get
{
return node;
}
}
public void ToManifest(System.IO.StreamWriter w)
{
w.WriteLine("Mosaic:{0}", alpha0MosaicName);
w.WriteLine("Mosaic:{0}", alpha1MosaicName);
w.WriteLine("Texture:{0}", Layer1TextureName);
w.WriteLine("Texture:{0}", Layer2TextureName);
w.WriteLine("Texture:{0}", Layer3TextureName);
w.WriteLine("Texture:{0}", Layer4TextureName);
w.WriteLine("Texture:{0}", Layer5TextureName);
w.WriteLine("Texture:{0}", Layer6TextureName);
w.WriteLine("Texture:{0}", Layer7TextureName);
w.WriteLine("Texture:{0}", Layer8TextureName);
w.WriteLine("Texture:{0}", DetailTextureName);
}
#endregion
#region IDisposable Members
public void Dispose()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IWorldObject Members
public void UpdateScene(UpdateTypes type, UpdateHint hint)
{
}
[DescriptionAttribute("The type of this object."), CategoryAttribute("Miscellaneous")]
public string ObjectType
{
get
{
return "AlphaSplatTerrainDisplay";
}
}
#endregion
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Text;
using Org.BouncyCastle.Math;
namespace Org.BouncyCastle.Utilities
{
/// <summary> General array utilities.</summary>
public abstract class Arrays
{
public static bool AreEqual(
bool[] a,
bool[] b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
return HaveSameContents(a, b);
}
public static bool AreEqual(
char[] a,
char[] b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
return HaveSameContents(a, b);
}
/// <summary>
/// Are two arrays equal.
/// </summary>
/// <param name="a">Left side.</param>
/// <param name="b">Right side.</param>
/// <returns>True if equal.</returns>
public static bool AreEqual(
byte[] a,
byte[] b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
return HaveSameContents(a, b);
}
[Obsolete("Use 'AreEqual' method instead")]
public static bool AreSame(
byte[] a,
byte[] b)
{
return AreEqual(a, b);
}
/// <summary>
/// A constant time equals comparison - does not terminate early if
/// test will fail.
/// </summary>
/// <param name="a">first array</param>
/// <param name="b">second array</param>
/// <returns>true if arrays equal, false otherwise.</returns>
public static bool ConstantTimeAreEqual(
byte[] a,
byte[] b)
{
int i = a.Length;
if (i != b.Length)
return false;
int cmp = 0;
while (i != 0)
{
--i;
cmp |= (a[i] ^ b[i]);
}
return cmp == 0;
}
public static bool AreEqual(
int[] a,
int[] b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
return HaveSameContents(a, b);
}
public static bool AreEqual(uint[] a, uint[] b)
{
if (a == b)
return true;
if (a == null || b == null)
return false;
return HaveSameContents(a, b);
}
private static bool HaveSameContents(
bool[] a,
bool[] b)
{
int i = a.Length;
if (i != b.Length)
return false;
while (i != 0)
{
--i;
if (a[i] != b[i])
return false;
}
return true;
}
private static bool HaveSameContents(
char[] a,
char[] b)
{
int i = a.Length;
if (i != b.Length)
return false;
while (i != 0)
{
--i;
if (a[i] != b[i])
return false;
}
return true;
}
private static bool HaveSameContents(
byte[] a,
byte[] b)
{
int i = a.Length;
if (i != b.Length)
return false;
while (i != 0)
{
--i;
if (a[i] != b[i])
return false;
}
return true;
}
private static bool HaveSameContents(
int[] a,
int[] b)
{
int i = a.Length;
if (i != b.Length)
return false;
while (i != 0)
{
--i;
if (a[i] != b[i])
return false;
}
return true;
}
private static bool HaveSameContents(uint[] a, uint[] b)
{
int i = a.Length;
if (i != b.Length)
return false;
while (i != 0)
{
--i;
if (a[i] != b[i])
return false;
}
return true;
}
public static string ToString(
object[] a)
{
StringBuilder sb = new StringBuilder('[');
if (a.Length > 0)
{
sb.Append(a[0]);
for (int index = 1; index < a.Length; ++index)
{
sb.Append(", ").Append(a[index]);
}
}
sb.Append(']');
return sb.ToString();
}
public static int GetHashCode(byte[] data)
{
if (data == null)
{
return 0;
}
int i = data.Length;
int hc = i + 1;
while (--i >= 0)
{
hc *= 257;
hc ^= data[i];
}
return hc;
}
public static int GetHashCode(byte[] data, int off, int len)
{
if (data == null)
{
return 0;
}
int i = len;
int hc = i + 1;
while (--i >= 0)
{
hc *= 257;
hc ^= data[off + i];
}
return hc;
}
public static int GetHashCode(int[] data)
{
if (data == null)
return 0;
int i = data.Length;
int hc = i + 1;
while (--i >= 0)
{
hc *= 257;
hc ^= data[i];
}
return hc;
}
public static int GetHashCode(int[] data, int off, int len)
{
if (data == null)
return 0;
int i = len;
int hc = i + 1;
while (--i >= 0)
{
hc *= 257;
hc ^= data[off + i];
}
return hc;
}
public static int GetHashCode(uint[] data)
{
if (data == null)
return 0;
int i = data.Length;
int hc = i + 1;
while (--i >= 0)
{
hc *= 257;
hc ^= (int)data[i];
}
return hc;
}
public static int GetHashCode(uint[] data, int off, int len)
{
if (data == null)
return 0;
int i = len;
int hc = i + 1;
while (--i >= 0)
{
hc *= 257;
hc ^= (int)data[off + i];
}
return hc;
}
public static int GetHashCode(ulong[] data)
{
if (data == null)
return 0;
int i = data.Length;
int hc = i + 1;
while (--i >= 0)
{
ulong di = data[i];
hc *= 257;
hc ^= (int)di;
hc *= 257;
hc ^= (int)(di >> 32);
}
return hc;
}
public static int GetHashCode(ulong[] data, int off, int len)
{
if (data == null)
return 0;
int i = len;
int hc = i + 1;
while (--i >= 0)
{
ulong di = data[off + i];
hc *= 257;
hc ^= (int)di;
hc *= 257;
hc ^= (int)(di >> 32);
}
return hc;
}
public static byte[] Clone(
byte[] data)
{
return data == null ? null : (byte[])data.Clone();
}
public static byte[] Clone(
byte[] data,
byte[] existing)
{
if (data == null)
{
return null;
}
if ((existing == null) || (existing.Length != data.Length))
{
return Clone(data);
}
Array.Copy(data, 0, existing, 0, existing.Length);
return existing;
}
public static int[] Clone(
int[] data)
{
return data == null ? null : (int[])data.Clone();
}
internal static uint[] Clone(uint[] data)
{
return data == null ? null : (uint[])data.Clone();
}
public static long[] Clone(long[] data)
{
return data == null ? null : (long[])data.Clone();
}
public static ulong[] Clone(
ulong[] data)
{
return data == null ? null : (ulong[]) data.Clone();
}
public static ulong[] Clone(
ulong[] data,
ulong[] existing)
{
if (data == null)
{
return null;
}
if ((existing == null) || (existing.Length != data.Length))
{
return Clone(data);
}
Array.Copy(data, 0, existing, 0, existing.Length);
return existing;
}
public static bool Contains(byte[] a, byte n)
{
for (int i = 0; i < a.Length; ++i)
{
if (a[i] == n)
return true;
}
return false;
}
public static bool Contains(short[] a, short n)
{
for (int i = 0; i < a.Length; ++i)
{
if (a[i] == n)
return true;
}
return false;
}
public static bool Contains(int[] a, int n)
{
for (int i = 0; i < a.Length; ++i)
{
if (a[i] == n)
return true;
}
return false;
}
public static void Fill(
byte[] buf,
byte b)
{
int i = buf.Length;
while (i > 0)
{
buf[--i] = b;
}
}
public static byte[] CopyOf(byte[] data, int newLength)
{
byte[] tmp = new byte[newLength];
Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length));
return tmp;
}
public static char[] CopyOf(char[] data, int newLength)
{
char[] tmp = new char[newLength];
Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length));
return tmp;
}
public static int[] CopyOf(int[] data, int newLength)
{
int[] tmp = new int[newLength];
Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length));
return tmp;
}
public static long[] CopyOf(long[] data, int newLength)
{
long[] tmp = new long[newLength];
Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length));
return tmp;
}
public static BigInteger[] CopyOf(BigInteger[] data, int newLength)
{
BigInteger[] tmp = new BigInteger[newLength];
Array.Copy(data, 0, tmp, 0, System.Math.Min(newLength, data.Length));
return tmp;
}
/**
* Make a copy of a range of bytes from the passed in data array. The range can
* extend beyond the end of the input array, in which case the return array will
* be padded with zeroes.
*
* @param data the array from which the data is to be copied.
* @param from the start index at which the copying should take place.
* @param to the final index of the range (exclusive).
*
* @return a new byte array containing the range given.
*/
public static byte[] CopyOfRange(byte[] data, int from, int to)
{
int newLength = GetLength(from, to);
byte[] tmp = new byte[newLength];
Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from));
return tmp;
}
public static int[] CopyOfRange(int[] data, int from, int to)
{
int newLength = GetLength(from, to);
int[] tmp = new int[newLength];
Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from));
return tmp;
}
public static long[] CopyOfRange(long[] data, int from, int to)
{
int newLength = GetLength(from, to);
long[] tmp = new long[newLength];
Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from));
return tmp;
}
public static BigInteger[] CopyOfRange(BigInteger[] data, int from, int to)
{
int newLength = GetLength(from, to);
BigInteger[] tmp = new BigInteger[newLength];
Array.Copy(data, from, tmp, 0, System.Math.Min(newLength, data.Length - from));
return tmp;
}
private static int GetLength(int from, int to)
{
int newLength = to - from;
if (newLength < 0)
throw new ArgumentException(from + " > " + to);
return newLength;
}
public static byte[] Append(byte[] a, byte b)
{
if (a == null)
return new byte[] { b };
int length = a.Length;
byte[] result = new byte[length + 1];
Array.Copy(a, 0, result, 0, length);
result[length] = b;
return result;
}
public static short[] Append(short[] a, short b)
{
if (a == null)
return new short[] { b };
int length = a.Length;
short[] result = new short[length + 1];
Array.Copy(a, 0, result, 0, length);
result[length] = b;
return result;
}
public static int[] Append(int[] a, int b)
{
if (a == null)
return new int[] { b };
int length = a.Length;
int[] result = new int[length + 1];
Array.Copy(a, 0, result, 0, length);
result[length] = b;
return result;
}
public static byte[] Concatenate(byte[] a, byte[] b)
{
if (a == null)
return Clone(b);
if (b == null)
return Clone(a);
byte[] rv = new byte[a.Length + b.Length];
Array.Copy(a, 0, rv, 0, a.Length);
Array.Copy(b, 0, rv, a.Length, b.Length);
return rv;
}
public static int[] Concatenate(int[] a, int[] b)
{
if (a == null)
return Clone(b);
if (b == null)
return Clone(a);
int[] rv = new int[a.Length + b.Length];
Array.Copy(a, 0, rv, 0, a.Length);
Array.Copy(b, 0, rv, a.Length, b.Length);
return rv;
}
public static byte[] Prepend(byte[] a, byte b)
{
if (a == null)
return new byte[] { b };
int length = a.Length;
byte[] result = new byte[length + 1];
Array.Copy(a, 0, result, 1, length);
result[0] = b;
return result;
}
public static short[] Prepend(short[] a, short b)
{
if (a == null)
return new short[] { b };
int length = a.Length;
short[] result = new short[length + 1];
Array.Copy(a, 0, result, 1, length);
result[0] = b;
return result;
}
public static int[] Prepend(int[] a, int b)
{
if (a == null)
return new int[] { b };
int length = a.Length;
int[] result = new int[length + 1];
Array.Copy(a, 0, result, 1, length);
result[0] = b;
return result;
}
public static byte[] Reverse(byte[] a)
{
if (a == null)
return null;
int p1 = 0, p2 = a.Length;
byte[] result = new byte[p2];
while (--p2 >= 0)
{
result[p2] = a[p1++];
}
return result;
}
}
}
#endif
| |
using System;
using System.Net.Http;
using System.Net.Http.Headers;
namespace FluentRest
{
/// <summary>
/// Fluent header builder
/// </summary>
public class HeaderBuilder : HeaderBuilder<HeaderBuilder>
{
/// <summary>
/// Initializes a new instance of the <see cref="HeaderBuilder"/> class.
/// </summary>
/// <param name="requestMessage">The fluent HTTP request being built.</param>
public HeaderBuilder(HttpRequestMessage requestMessage) : base(requestMessage)
{
}
}
/// <summary>
/// Fluent header builder
/// </summary>
/// <typeparam name="TBuilder">The type of the builder.</typeparam>
public abstract class HeaderBuilder<TBuilder> : RequestBuilder<TBuilder>
where TBuilder : HeaderBuilder<TBuilder>
{
/// <summary>
/// Initializes a new instance of the <see cref="HeaderBuilder{TBuilder}"/> class.
/// </summary>
/// <param name="requestMessage">The fluent HTTP request being built.</param>
protected HeaderBuilder(HttpRequestMessage requestMessage) : base(requestMessage)
{
}
/// <summary>
/// Append the media-type to the Accept header for an HTTP request.
/// </summary>
/// <param name="mediaType">The media-type header value.</param>
/// <param name="quality">The quality associated with the header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Accept(string mediaType, double? quality = null)
{
var header = quality.HasValue
? new MediaTypeWithQualityHeaderValue(mediaType, quality.Value)
: new MediaTypeWithQualityHeaderValue(mediaType);
RequestMessage.Headers.Accept.Add(header);
return this as TBuilder;
}
/// <summary>
/// Append the value to the Accept-Charset header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <param name="quality">The quality associated with the header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder AcceptCharset(string value, double? quality = null)
{
var header = quality.HasValue
? new StringWithQualityHeaderValue(value, quality.Value)
: new StringWithQualityHeaderValue(value);
RequestMessage.Headers.AcceptCharset.Add(header);
return this as TBuilder;
}
/// <summary>
/// Append the value to the Accept-Encoding header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <param name="quality">The quality associated with the header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder AcceptEncoding(string value, double? quality = null)
{
var header = quality.HasValue
? new StringWithQualityHeaderValue(value, quality.Value)
: new StringWithQualityHeaderValue(value);
RequestMessage.Headers.AcceptEncoding.Add(header);
return this as TBuilder;
}
/// <summary>
/// Append the value to the Accept-Language header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <param name="quality">The quality associated with the header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder AcceptLanguage(string value, double? quality = null)
{
var header = quality.HasValue
? new StringWithQualityHeaderValue(value, quality.Value)
: new StringWithQualityHeaderValue(value);
RequestMessage.Headers.AcceptLanguage.Add(header);
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Authorization header for an HTTP request.
/// </summary>
/// <param name="scheme">The scheme to use for authorization.</param>
/// <param name="parameter">The credentials containing the authentication information.</param>
/// <returns>A fluent header builder.</returns>
/// <exception cref="System.ArgumentNullException"></exception>
public TBuilder Authorization(string scheme, string parameter = null)
{
if (scheme == null)
throw new ArgumentNullException(nameof(scheme));
var header = new AuthenticationHeaderValue(scheme, parameter);
RequestMessage.Headers.Authorization = header;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Cache-Control header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <see langword="null"/></exception>
public TBuilder CacheControl(string value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var header = CacheControlHeaderValue.Parse(value);
RequestMessage.Headers.CacheControl = header;
return this as TBuilder;
}
/// <summary>
/// Append the value of the Expect header for an HTTP request.
/// </summary>
/// <param name="name">The header name.</param>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Expect(string name, string value = null)
{
var header = new NameValueWithParametersHeaderValue(name, value);
RequestMessage.Headers.Expect.Add(header);
return this as TBuilder;
}
/// <summary>
/// Sets the value of the From header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder From(string value)
{
RequestMessage.Headers.From = value;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Host header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Host(string value)
{
RequestMessage.Headers.Host = value;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the If-Modified-Since header for an HTTP request.
/// </summary>
/// <param name="modifiedDate">The modified date.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder IfModifiedSince(DateTimeOffset? modifiedDate)
{
RequestMessage.Headers.IfModifiedSince = modifiedDate;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the If-Unmodified-Since header for an HTTP request.
/// </summary>
/// <param name="modifiedDate">The modified date.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder IfUnmodifiedSince(DateTimeOffset? modifiedDate)
{
RequestMessage.Headers.IfUnmodifiedSince = modifiedDate;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Proxy-Authorization header for an HTTP request.
/// </summary>
/// <param name="scheme">The scheme to use for authorization.</param>
/// <param name="parameter">The credentials containing the authentication information.</param>
/// <returns>A fluent header builder.</returns>
/// <exception cref="ArgumentNullException"><paramref name="scheme"/> is <see langword="null"/></exception>
public TBuilder ProxyAuthorization(string scheme, string parameter = null)
{
if (scheme == null)
throw new ArgumentNullException(nameof(scheme));
var header = new AuthenticationHeaderValue(scheme, parameter);
RequestMessage.Headers.ProxyAuthorization = header;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Range header for an HTTP request.
/// </summary>
/// <param name="from">The position at which to start sending data.</param>
/// <param name="to">The position at which to stop sending data.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Range(long? from, long? to)
{
var header = new RangeHeaderValue(from, to);
RequestMessage.Headers.Range = header;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Referrer header for an HTTP request.
/// </summary>
/// <param name="uri">The header URI.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Referrer(Uri uri)
{
RequestMessage.Headers.Referrer = uri;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the Referrer header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder Referrer(string value)
{
if (string.IsNullOrEmpty(value))
return this as TBuilder;
var uri = new Uri(value);
RequestMessage.Headers.Referrer = uri;
return this as TBuilder;
}
/// <summary>
/// Sets the value of the User-Agent header for an HTTP request.
/// </summary>
/// <param name="value">The header value.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder UserAgent(string value)
{
if (string.IsNullOrEmpty(value))
return this as TBuilder;
var header = ProductInfoHeaderValue.Parse(value);
RequestMessage.Headers.UserAgent.Add(header);
return this as TBuilder;
}
/// <summary>
/// Sets the value of the X-HTTP-Method-Override header for an HTTP request.
/// </summary>
/// <param name="method">The HTTP method.</param>
/// <returns>A fluent header builder.</returns>
public TBuilder MethodOverride(HttpMethod method)
{
RequestMessage.Headers.Add(HttpRequestHeaders.MethodOverride, method.ToString());
return this as TBuilder;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace AutoMapper
{
internal class FormatterExpression : IFormatterExpression, IFormatterConfiguration, IFormatterCtorConfigurator, IMappingOptions
{
private readonly Func<Type, IValueFormatter> _formatterCtor;
private readonly IList<IValueFormatter> _formatters = new List<IValueFormatter>();
private readonly IDictionary<Type, IFormatterConfiguration> _typeSpecificFormatters = new Dictionary<Type, IFormatterConfiguration>();
private readonly IList<Type> _formattersToSkip = new List<Type>();
private static readonly Func<string, string, string> PrefixFunc = (src, prefix) => Regex.Replace(src, string.Format("(?:^{0})?(.*)", prefix), "$1");
private static readonly Func<string, string, string> PostfixFunc = (src, prefix) => Regex.Replace(src, string.Format("(.*)(?:{0})$", prefix), "$1");
private static readonly Func<string, string, string, string> AliasFunc = (src, original, alias) => Regex.Replace(src, string.Format("^({0})$", original), alias);
public FormatterExpression(Func<Type, IValueFormatter> formatterCtor)
{
_formatterCtor = formatterCtor;
SourceMemberNamingConvention = new PascalCaseNamingConvention();
DestinationMemberNamingConvention = new PascalCaseNamingConvention();
SourceMemberNameTransformer = s => Regex.Replace(s, "(?:^Get)?(.*)", "$1");
DestinationMemberNameTransformer = s => s;
AllowNullDestinationValues = true;
}
public bool AllowNullDestinationValues { get; set; }
public bool AllowNullCollections { get; set; }
public INamingConvention SourceMemberNamingConvention { get; set; }
public INamingConvention DestinationMemberNamingConvention { get; set; }
public Func<string, string> SourceMemberNameTransformer { get; set; }
public Func<string, string> DestinationMemberNameTransformer { get; set; }
public IFormatterCtorExpression<TValueFormatter> AddFormatter<TValueFormatter>() where TValueFormatter : IValueFormatter
{
var formatter = new DeferredInstantiatedFormatter(BuildCtor(typeof(TValueFormatter)));
AddFormatter(formatter);
return new FormatterCtorExpression<TValueFormatter>(this);
}
public IFormatterCtorExpression AddFormatter(Type valueFormatterType)
{
var formatter = new DeferredInstantiatedFormatter(BuildCtor(valueFormatterType));
AddFormatter(formatter);
return new FormatterCtorExpression(valueFormatterType, this);
}
public void AddFormatter(IValueFormatter valueFormatter)
{
_formatters.Add(valueFormatter);
}
public void AddFormatExpression(Func<ResolutionContext, string> formatExpression)
{
_formatters.Add(new ExpressionValueFormatter(formatExpression));
}
public void SkipFormatter<TValueFormatter>() where TValueFormatter : IValueFormatter
{
_formattersToSkip.Add(typeof(TValueFormatter));
}
public IFormatterExpression ForSourceType<TSource>()
{
var valueFormatter = new FormatterExpression(_formatterCtor);
_typeSpecificFormatters[typeof (TSource)] = valueFormatter;
return valueFormatter;
}
public IValueFormatter[] GetFormatters()
{
return _formatters.ToArray();
}
public IDictionary<Type, IFormatterConfiguration> GetTypeSpecificFormatters()
{
return new Dictionary<Type, IFormatterConfiguration>(_typeSpecificFormatters);
}
public Type[] GetFormatterTypesToSkip()
{
return _formattersToSkip.ToArray();
}
public IEnumerable<IValueFormatter> GetFormattersToApply(ResolutionContext context)
{
return GetFormatters(context);
}
private IEnumerable<IValueFormatter> GetFormatters(ResolutionContext context)
{
Type valueType = context.SourceType;
IFormatterConfiguration typeSpecificFormatterConfig;
if (context.PropertyMap != null)
{
foreach (IValueFormatter formatter in context.PropertyMap.GetFormatters())
{
yield return formatter;
}
if (GetTypeSpecificFormatters().TryGetValue(valueType, out typeSpecificFormatterConfig))
{
if (!context.PropertyMap.FormattersToSkipContains(typeSpecificFormatterConfig.GetType()))
{
foreach (var typeSpecificFormatter in typeSpecificFormatterConfig.GetFormattersToApply(context))
{
yield return typeSpecificFormatter;
}
}
}
}
else if (GetTypeSpecificFormatters().TryGetValue(valueType, out typeSpecificFormatterConfig))
{
foreach (var typeSpecificFormatter in typeSpecificFormatterConfig.GetFormattersToApply(context))
{
yield return typeSpecificFormatter;
}
}
foreach (IValueFormatter formatter in GetFormatters())
{
Type formatterType = GetFormatterType(formatter, context);
if (CheckPropertyMapSkipList(context, formatterType) &&
CheckTypeSpecificSkipList(typeSpecificFormatterConfig, formatterType))
{
yield return formatter;
}
}
}
public void ConstructFormatterBy(Type formatterType, Func<IValueFormatter> instantiator)
{
_formatters.RemoveAt(_formatters.Count - 1);
_formatters.Add(new DeferredInstantiatedFormatter(ctxt => instantiator()));
}
public bool MapNullSourceValuesAsNull
{
get { return AllowNullDestinationValues; }
}
public bool MapNullSourceCollectionsAsNull
{
get { return AllowNullCollections; }
}
public void RecognizePrefixes(params string[] prefixes)
{
var orig = SourceMemberNameTransformer;
SourceMemberNameTransformer = val => prefixes.Aggregate(orig(val), PrefixFunc);
}
public void RecognizePostfixes(params string[] postfixes)
{
var orig = SourceMemberNameTransformer;
SourceMemberNameTransformer = val => postfixes.Aggregate(orig(val), PostfixFunc);
}
public void RecognizeAlias(string original, string alias)
{
var orig = SourceMemberNameTransformer;
SourceMemberNameTransformer = val => AliasFunc(orig(val), original, alias);
}
public void RecognizeDestinationPrefixes(params string[] prefixes)
{
var orig = DestinationMemberNameTransformer;
DestinationMemberNameTransformer = val => prefixes.Aggregate(orig(val), PrefixFunc);
}
public void RecognizeDestinationPostfixes(params string[] postfixes)
{
var orig = DestinationMemberNameTransformer;
DestinationMemberNameTransformer = val => postfixes.Aggregate(orig(val), PostfixFunc);
}
private static Type GetFormatterType(IValueFormatter formatter, ResolutionContext context)
{
return formatter is DeferredInstantiatedFormatter ? ((DeferredInstantiatedFormatter)formatter).GetFormatterType(context) : formatter.GetType();
}
private static bool CheckTypeSpecificSkipList(IFormatterConfiguration valueFormatter, Type formatterType)
{
if (valueFormatter == null)
{
return true;
}
return !valueFormatter.GetFormatterTypesToSkip().Contains(formatterType);
}
private static bool CheckPropertyMapSkipList(ResolutionContext context, Type formatterType)
{
if (context.PropertyMap == null)
return true;
return !context.PropertyMap.FormattersToSkipContains(formatterType);
}
private Func<ResolutionContext, IValueFormatter> BuildCtor(Type type)
{
return context =>
{
if (context.Options.ServiceCtor != null)
{
var obj = context.Options.ServiceCtor(type);
if (obj != null)
return (IValueFormatter)obj;
}
return (IValueFormatter)_formatterCtor(type);
};
}
}
internal interface IFormatterCtorConfigurator
{
void ConstructFormatterBy(Type formatterType, Func<IValueFormatter> instantiator);
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:40 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext.draw.engine
{
#region SvgExporter
/// <inheritdocs />
/// <summary>
/// <p>A utility class for exporting a <see cref="Ext.draw.Surface">Surface</see> to a string
/// that may be saved or used for processing on the server.</p>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class SvgExporter : Ext.Base
{
/// <summary>
/// Defaults to: <c>"Ext.Base"</c>
/// </summary>
[JsProperty(Name="$className")]
private static JsString @className{get;set;}
/// <summary>
/// Defaults to: <c>{}</c>
/// </summary>
private static JsObject configMap{get;set;}
/// <summary>
/// Defaults to: <c>[]</c>
/// </summary>
private static JsArray initConfigList{get;set;}
/// <summary>
/// Defaults to: <c>{}</c>
/// </summary>
private static JsObject initConfigMap{get;set;}
/// <summary>
/// Defaults to: <c>true</c>
/// </summary>
private static bool isInstance{get;set;}
/// <summary>
/// Get the reference to the current class from which this object was instantiated. Unlike statics,
/// this.self is scope-dependent and it's meant to be used for dynamic inheritance. See statics
/// for a detailed comparison
/// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.Cat', {
/// statics: {
/// speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
/// },
/// constructor: function() {
/// alert(this.self.speciesName); // dependent on 'this'
/// },
/// clone: function() {
/// return new this.self();
/// }
/// });
/// <see cref="Ext.ExtContext.define">Ext.define</see>('My.SnowLeopard', {
/// extend: 'My.Cat',
/// statics: {
/// speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
/// }
/// });
/// var cat = new My.Cat(); // alerts 'Cat'
/// var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
/// var clone = snowLeopard.clone();
/// alert(<see cref="Ext.ExtContext.getClassName">Ext.getClassName</see>(clone)); // alerts 'My.SnowLeopard'
/// </code>
/// </summary>
protected static Class self{get;set;}
/// <summary>
/// Call the original method that was previously overridden with override
/// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.Cat', {
/// constructor: function() {
/// alert("I'm a cat!");
/// }
/// });
/// My.Cat.override({
/// constructor: function() {
/// alert("I'm going to be a cat!");
/// this.callOverridden();
/// alert("Meeeeoooowwww");
/// }
/// });
/// var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
/// // alerts "I'm a cat!"
/// // alerts "Meeeeoooowwww"
/// </code>
/// <p>This method has been <strong>deprecated</strong> </p>
/// <p>as of 4.1. Use <see cref="Ext.Base.callParent">callParent</see> instead.</p>
/// </summary>
/// <param name="args"><p>The arguments, either an array or the <c>arguments</c> object
/// from the current method, for example: <c>this.callOverridden(arguments)</c></p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>Returns the result of calling the overridden method</p>
/// </div>
/// </returns>
protected static object callOverridden(object args=null){return null;}
/// <summary>
/// Call the "parent" method of the current method. That is the method previously
/// overridden by derivation or by an override (see Ext.define).
/// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.Base', {
/// constructor: function (x) {
/// this.x = x;
/// },
/// statics: {
/// method: function (x) {
/// return x;
/// }
/// }
/// });
/// <see cref="Ext.ExtContext.define">Ext.define</see>('My.Derived', {
/// extend: 'My.Base',
/// constructor: function () {
/// this.callParent([21]);
/// }
/// });
/// var obj = new My.Derived();
/// alert(obj.x); // alerts 21
/// </code>
/// This can be used with an override as follows:
/// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.DerivedOverride', {
/// override: 'My.Derived',
/// constructor: function (x) {
/// this.callParent([x*2]); // calls original My.Derived constructor
/// }
/// });
/// var obj = new My.Derived();
/// alert(obj.x); // now alerts 42
/// </code>
/// This also works with static methods.
/// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.Derived2', {
/// extend: 'My.Base',
/// statics: {
/// method: function (x) {
/// return this.callParent([x*2]); // calls My.Base.method
/// }
/// }
/// });
/// alert(My.Base.method(10); // alerts 10
/// alert(My.Derived2.method(10); // alerts 20
/// </code>
/// Lastly, it also works with overridden static methods.
/// <code> <see cref="Ext.ExtContext.define">Ext.define</see>('My.Derived2Override', {
/// override: 'My.Derived2',
/// statics: {
/// method: function (x) {
/// return this.callParent([x*2]); // calls My.Derived2.method
/// }
/// }
/// });
/// alert(My.Derived2.method(10); // now alerts 40
/// </code>
/// </summary>
/// <param name="args"><p>The arguments, either an array or the <c>arguments</c> object
/// from the current method, for example: <c>this.callParent(arguments)</c></p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see></span><div><p>Returns the result of calling the parent method</p>
/// </div>
/// </returns>
protected static object callParent(object args=null){return null;}
/// <summary>
/// </summary>
private static void configClass(){}
/// <summary>
/// Overrides: <see cref="Ext.AbstractComponent.destroy">Ext.AbstractComponent.destroy</see>, <see cref="Ext.AbstractPlugin.destroy">Ext.AbstractPlugin.destroy</see>, <see cref="Ext.layout.Layout.destroy">Ext.layout.Layout.destroy</see>
/// </summary>
private static void destroy(){}
/// <summary>
/// Exports the passed surface to a SVG string representation
/// </summary>
/// <param name="surface"><p>The surface to export</p>
/// </param>
/// <param name="config"><p>Any configuration for the export. Currently this is
/// unused but may provide more options in the future</p>
/// </param>
/// <returns>
/// <span><see cref="String">String</see></span><div><p>The SVG as a string</p>
/// </div>
/// </returns>
public static JsString generate(Surface surface, object config=null){return null;}
/// <summary>
/// Parameters<li><span>name</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="name">
/// </param>
private static void getConfig(object name){}
/// <summary>
/// Returns the initial configuration passed to constructor when instantiating
/// this class.
/// </summary>
/// <param name="name"><p>Name of the config option to return.</p>
/// </param>
/// <returns>
/// <span><see cref="Object">Object</see>/Mixed</span><div><p>The full config object or a single config value
/// when <c>name</c> parameter specified.</p>
/// </div>
/// </returns>
public static object getInitialConfig(object name=null){return null;}
/// <summary>
/// Parameters<li><span>config</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="config">
/// </param>
private static void hasConfig(object config){}
/// <summary>
/// Initialize configuration for this class. a typical example:
/// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.awesome.Class', {
/// // The default config
/// config: {
/// name: 'Awesome',
/// isAwesome: true
/// },
/// constructor: function(config) {
/// this.initConfig(config);
/// }
/// });
/// var awesome = new My.awesome.Class({
/// name: 'Super Awesome'
/// });
/// alert(awesome.getName()); // 'Super Awesome'
/// </code>
/// </summary>
/// <param name="config">
/// </param>
/// <returns>
/// <span><see cref="Ext.Base">Ext.Base</see></span><div><p>this</p>
/// </div>
/// </returns>
protected static Ext.Base initConfig(object config){return null;}
/// <summary>
/// Parameters<li><span>names</span> : <see cref="Object">Object</see><div>
/// </div></li><li><span>callback</span> : <see cref="Object">Object</see><div>
/// </div></li><li><span>scope</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="names">
/// </param>
/// <param name="callback">
/// </param>
/// <param name="scope">
/// </param>
private static void onConfigUpdate(object names, object callback, object scope){}
/// <summary>
/// Parameters<li><span>config</span> : <see cref="Object">Object</see><div>
/// </div></li><li><span>applyIfNotSet</span> : <see cref="Object">Object</see><div>
/// </div></li>
/// </summary>
/// <param name="config">
/// </param>
/// <param name="applyIfNotSet">
/// </param>
private static void setConfig(object config, object applyIfNotSet){}
/// <summary>
/// Get the reference to the class from which this object was instantiated. Note that unlike self,
/// this.statics() is scope-independent and it always returns the class from which it was called, regardless of what
/// this points to during run-time
/// <code><see cref="Ext.ExtContext.define">Ext.define</see>('My.Cat', {
/// statics: {
/// totalCreated: 0,
/// speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
/// },
/// constructor: function() {
/// var statics = this.statics();
/// alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to
/// // equivalent to: My.Cat.speciesName
/// alert(this.self.speciesName); // dependent on 'this'
/// statics.totalCreated++;
/// },
/// clone: function() {
/// var cloned = new this.self; // dependent on 'this'
/// cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName
/// return cloned;
/// }
/// });
/// <see cref="Ext.ExtContext.define">Ext.define</see>('My.SnowLeopard', {
/// extend: 'My.Cat',
/// statics: {
/// speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
/// },
/// constructor: function() {
/// this.callParent();
/// }
/// });
/// var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'
/// var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
/// var clone = snowLeopard.clone();
/// alert(<see cref="Ext.ExtContext.getClassName">Ext.getClassName</see>(clone)); // alerts 'My.SnowLeopard'
/// alert(clone.groupName); // alerts 'Cat'
/// alert(My.Cat.totalCreated); // alerts 3
/// </code>
/// </summary>
/// <returns>
/// <span><see cref="Ext.Class">Ext.Class</see></span><div>
/// </div>
/// </returns>
protected static Class statics(){return null;}
public SvgExporter(SvgExporterConfig config){}
public SvgExporter(){}
public SvgExporter(params object[] args){}
}
#endregion
#region SvgExporterConfig
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class SvgExporterConfig : Ext.BaseConfig
{
public SvgExporterConfig(params object[] args){}
}
#endregion
#region SvgExporterEvents
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class SvgExporterEvents : Ext.BaseEvents
{
public SvgExporterEvents(params object[] args){}
}
#endregion
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Xml.Linq;
namespace DocumentFormat.OpenXml.Linq
{
/// <summary>
/// Declares XNamespace and XName fields for the xmlns:c15="http://schemas.microsoft.com/office/drawing/2012/chart" namespace.
/// </summary>
public static class C15
{
/// <summary>
/// Defines the XML namespace associated with the c15 prefix.
/// </summary>
public static readonly XNamespace c15 = "http://schemas.microsoft.com/office/drawing/2012/chart";
/// <summary>
/// Represents the c15:autoCat XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.val" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: AutoGeneneratedCategories.</description></item>
/// </list>
/// </remarks>
public static readonly XName autoCat = c15 + "autoCat";
/// <summary>
/// Represents the c15:bubble3D XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="categoryFilterException" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.val" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Bubble3D.</description></item>
/// </list>
/// </remarks>
public static readonly XName bubble3D = c15 + "bubble3D";
/// <summary>
/// Represents the c15:cat XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="filteredCategoryTitle" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="C.multiLvlStrRef" />, <see cref="C.numLit" />, <see cref="C.numRef" />, <see cref="C.strLit" />, <see cref="C.strRef" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: AxisDataSourceType.</description></item>
/// </list>
/// </remarks>
public static readonly XName cat = c15 + "cat";
/// <summary>
/// Represents the c15:categoryFilterException XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="categoryFilterExceptions" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="bubble3D" />, <see cref="dLbl" />, <see cref="explosion" />, <see cref="invertIfNegative" />, <see cref="marker" />, <see cref="spPr" />, <see cref="sqref" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: CategoryFilterException.</description></item>
/// </list>
/// </remarks>
public static readonly XName categoryFilterException = c15 + "categoryFilterException";
/// <summary>
/// Represents the c15:categoryFilterExceptions XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="categoryFilterException" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: CategoryFilterExceptions.</description></item>
/// </list>
/// </remarks>
public static readonly XName categoryFilterExceptions = c15 + "categoryFilterExceptions";
/// <summary>
/// Represents the c15:datalabelsRange XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="dlblRangeCache" />, <see cref="f" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DataLabelsRange.</description></item>
/// </list>
/// </remarks>
public static readonly XName datalabelsRange = c15 + "datalabelsRange";
/// <summary>
/// Represents the c15:dLbl XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="categoryFilterException" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="C.delete" />, <see cref="C.dLblPos" />, <see cref="C.extLst" />, <see cref="C.idx" />, <see cref="C.layout" />, <see cref="C.numFmt" />, <see cref="C.separator" />, <see cref="C.showBubbleSize" />, <see cref="C.showCatName" />, <see cref="C.showLegendKey" />, <see cref="C.showPercent" />, <see cref="C.showSerName" />, <see cref="C.showVal" />, <see cref="C.spPr" />, <see cref="C.tx" />, <see cref="C.txPr" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DataLabel.</description></item>
/// </list>
/// </remarks>
public static readonly XName dLbl = c15 + "dLbl";
/// <summary>
/// Represents the c15:dlblFieldTable XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="dlblFTEntry" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DataLabelFieldTable.</description></item>
/// </list>
/// </remarks>
public static readonly XName dlblFieldTable = c15 + "dlblFieldTable";
/// <summary>
/// Represents the c15:dlblFieldTableCache XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="dlblFTEntry" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="C.extLst" />, <see cref="C.pt" />, <see cref="C.ptCount" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DataLabelFieldTableCache.</description></item>
/// </list>
/// </remarks>
public static readonly XName dlblFieldTableCache = c15 + "dlblFieldTableCache";
/// <summary>
/// Represents the c15:dlblFTEntry XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="dlblFieldTable" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="dlblFieldTableCache" />, <see cref="f" />, <see cref="txfldGUID" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DataLabelFieldTableEntry.</description></item>
/// </list>
/// </remarks>
public static readonly XName dlblFTEntry = c15 + "dlblFTEntry";
/// <summary>
/// Represents the c15:dlblRangeCache XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="datalabelsRange" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="C.extLst" />, <see cref="C.pt" />, <see cref="C.ptCount" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: DataLabelsRangeChache.</description></item>
/// </list>
/// </remarks>
public static readonly XName dlblRangeCache = c15 + "dlblRangeCache";
/// <summary>
/// Represents the c15:explosion XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="categoryFilterException" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.val" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Explosion.</description></item>
/// </list>
/// </remarks>
public static readonly XName explosion = c15 + "explosion";
/// <summary>
/// Represents the c15:f XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="datalabelsRange" />, <see cref="dlblFTEntry" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Formula.</description></item>
/// </list>
/// </remarks>
public static readonly XName f = c15 + "f";
/// <summary>
/// Represents the c15:filteredAreaSeries XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="ser" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FilteredAreaSeries.</description></item>
/// </list>
/// </remarks>
public static readonly XName filteredAreaSeries = c15 + "filteredAreaSeries";
/// <summary>
/// Represents the c15:filteredBarSeries XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="ser" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FilteredBarSeries.</description></item>
/// </list>
/// </remarks>
public static readonly XName filteredBarSeries = c15 + "filteredBarSeries";
/// <summary>
/// Represents the c15:filteredBubbleSeries XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="ser" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FilteredBubbleSeries.</description></item>
/// </list>
/// </remarks>
public static readonly XName filteredBubbleSeries = c15 + "filteredBubbleSeries";
/// <summary>
/// Represents the c15:filteredCategoryTitle XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="cat" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FilteredCategoryTitle.</description></item>
/// </list>
/// </remarks>
public static readonly XName filteredCategoryTitle = c15 + "filteredCategoryTitle";
/// <summary>
/// Represents the c15:filteredLineSeries XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="ser" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FilteredLineSeriesExtension.</description></item>
/// </list>
/// </remarks>
public static readonly XName filteredLineSeries = c15 + "filteredLineSeries";
/// <summary>
/// Represents the c15:filteredPieSeries XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="ser" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FilteredPieSeries.</description></item>
/// </list>
/// </remarks>
public static readonly XName filteredPieSeries = c15 + "filteredPieSeries";
/// <summary>
/// Represents the c15:filteredRadarSeries XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="ser" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FilteredRadarSeries.</description></item>
/// </list>
/// </remarks>
public static readonly XName filteredRadarSeries = c15 + "filteredRadarSeries";
/// <summary>
/// Represents the c15:filteredScatterSeries XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="ser" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FilteredScatterSeries.</description></item>
/// </list>
/// </remarks>
public static readonly XName filteredScatterSeries = c15 + "filteredScatterSeries";
/// <summary>
/// Represents the c15:filteredSeriesTitle XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="tx" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FilteredSeriesTitle.</description></item>
/// </list>
/// </remarks>
public static readonly XName filteredSeriesTitle = c15 + "filteredSeriesTitle";
/// <summary>
/// Represents the c15:filteredSurfaceSeries XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="ser" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FilteredSurfaceSeries.</description></item>
/// </list>
/// </remarks>
public static readonly XName filteredSurfaceSeries = c15 + "filteredSurfaceSeries";
/// <summary>
/// Represents the c15:formulaRef XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="sqref" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FormulaReference.</description></item>
/// </list>
/// </remarks>
public static readonly XName formulaRef = c15 + "formulaRef";
/// <summary>
/// Represents the c15:fullRef XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="sqref" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: FullReference.</description></item>
/// </list>
/// </remarks>
public static readonly XName fullRef = c15 + "fullRef";
/// <summary>
/// Represents the c15:invertIfNegative XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="categoryFilterException" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.val" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: InvertIfNegativeBoolean.</description></item>
/// </list>
/// </remarks>
public static readonly XName invertIfNegative = c15 + "invertIfNegative";
/// <summary>
/// Represents the c15:layout XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="C.extLst" />, <see cref="C.manualLayout" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Layout.</description></item>
/// </list>
/// </remarks>
public static readonly XName layout = c15 + "layout";
/// <summary>
/// Represents the c15:leaderLines XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="C.spPr" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: LeaderLines.</description></item>
/// </list>
/// </remarks>
public static readonly XName leaderLines = c15 + "leaderLines";
/// <summary>
/// Represents the c15:levelRef XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="sqref" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: LevelReference.</description></item>
/// </list>
/// </remarks>
public static readonly XName levelRef = c15 + "levelRef";
/// <summary>
/// Represents the c15:marker XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="categoryFilterException" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="C.extLst" />, <see cref="C.size" />, <see cref="C.spPr" />, <see cref="C.symbol" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: Marker.</description></item>
/// </list>
/// </remarks>
public static readonly XName marker = c15 + "marker";
/// <summary>
/// Represents the c15:numFmt XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.formatCode" />, <see cref="NoNamespace.sourceLinked" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: NumberingFormat.</description></item>
/// </list>
/// </remarks>
public static readonly XName numFmt = c15 + "numFmt";
/// <summary>
/// Represents the c15:pivotSource XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="C.extLst" />, <see cref="C.fmtId" />, <see cref="C.name" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: PivotSource.</description></item>
/// </list>
/// </remarks>
public static readonly XName pivotSource = c15 + "pivotSource";
/// <summary>
/// Represents the c15:ser XML elements.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="filteredAreaSeries" />, <see cref="filteredBarSeries" />, <see cref="filteredBubbleSeries" />, <see cref="filteredLineSeries" />, <see cref="filteredPieSeries" />, <see cref="filteredRadarSeries" />, <see cref="filteredScatterSeries" />, <see cref="filteredSurfaceSeries" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="C.bubble3D" />, <see cref="C.bubbleSize" />, <see cref="C.cat" />, <see cref="C.dLbls" />, <see cref="C.dPt" />, <see cref="C.errBars" />, <see cref="C.explosion" />, <see cref="C.extLst" />, <see cref="C.idx" />, <see cref="C.invertIfNegative" />, <see cref="C.marker" />, <see cref="C.order" />, <see cref="C.pictureOptions" />, <see cref="C.shape" />, <see cref="C.smooth" />, <see cref="C.spPr" />, <see cref="C.trendline" />, <see cref="C.tx" />, <see cref="C.val" />, <see cref="C.xVal" />, <see cref="C.yVal" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: AreaChartSeries, BarChartSeries, BubbleChartSeries, LineChartSeries, PieChartSeries, RadarChartSeries, ScatterChartSeries, SurfaceChartSeries.</description></item>
/// </list>
/// </remarks>
public static readonly XName ser = c15 + "ser";
/// <summary>
/// Represents the c15:showDataLabelsRange XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.val" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ShowDataLabelsRange.</description></item>
/// </list>
/// </remarks>
public static readonly XName showDataLabelsRange = c15 + "showDataLabelsRange";
/// <summary>
/// Represents the c15:showLeaderLines XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.val" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ShowLeaderLines.</description></item>
/// </list>
/// </remarks>
public static readonly XName showLeaderLines = c15 + "showLeaderLines";
/// <summary>
/// Represents the c15:spPr XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />, <see cref="categoryFilterException" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="A.blipFill" />, <see cref="A.custGeom" />, <see cref="A.effectDag" />, <see cref="A.effectLst" />, <see cref="A.extLst" />, <see cref="A.gradFill" />, <see cref="A.grpFill" />, <see cref="A.ln" />, <see cref="A.noFill" />, <see cref="A.pattFill" />, <see cref="A.prstGeom" />, <see cref="A.scene3d" />, <see cref="A.solidFill" />, <see cref="A.sp3d" />, <see cref="A.xfrm" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.bwMode" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ShapeProperties.</description></item>
/// </list>
/// </remarks>
public static readonly XName spPr = c15 + "spPr";
/// <summary>
/// Represents the c15:sqref XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="categoryFilterException" />, <see cref="formulaRef" />, <see cref="fullRef" />, <see cref="levelRef" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: SequenceOfReferences.</description></item>
/// </list>
/// </remarks>
public static readonly XName sqref = c15 + "sqref";
/// <summary>
/// Represents the c15:tx XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />, <see cref="filteredSeriesTitle" />.</description></item>
/// <item><description>has the following child XML elements: <see cref="C.rich" />, <see cref="C.strLit" />, <see cref="C.strRef" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ChartText.</description></item>
/// </list>
/// </remarks>
public static readonly XName tx = c15 + "tx";
/// <summary>
/// Represents the c15:txfldGUID XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="dlblFTEntry" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: TextFieldGuid.</description></item>
/// </list>
/// </remarks>
public static readonly XName txfldGUID = c15 + "txfldGUID";
/// <summary>
/// Represents the c15:xForSave XML element.
/// </summary>
/// <remarks>
/// <para>As an XML element, it:</para>
/// <list type="bullet">
/// <item><description>has the following parent XML elements: <see cref="A.graphicData" />, <see cref="C.ext" />.</description></item>
/// <item><description>has the following XML attributes: <see cref="NoNamespace.val" />.</description></item>
/// <item><description>corresponds to the following strongly-typed classes: ExceptionForSave.</description></item>
/// </list>
/// </remarks>
public static readonly XName xForSave = c15 + "xForSave";
}
}
| |
//
// AggressiveRefletionReader.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
//
// 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.
//
namespace Mono.Cecil {
using System;
using Mono.Cecil.Metadata;
using Mono.Cecil.Signatures;
internal sealed class AggressiveReflectionReader : ReflectionReader {
public AggressiveReflectionReader (ModuleDefinition module) : base (module)
{
}
public override void VisitTypeDefinitionCollection (TypeDefinitionCollection types)
{
base.VisitTypeDefinitionCollection (types);
ReadGenericParameterConstraints ();
ReadClassLayoutInfos ();
ReadFieldLayoutInfos ();
ReadPInvokeInfos ();
ReadProperties ();
ReadEvents ();
ReadSemantics ();
ReadInterfaces ();
ReadOverrides ();
ReadSecurityDeclarations ();
ReadCustomAttributes ();
ReadConstants ();
ReadExternTypes ();
ReadMarshalSpecs ();
ReadInitialValues ();
m_events = null;
m_properties = null;
m_parameters = null;
}
void ReadGenericParameterConstraints ()
{
if (!m_tHeap.HasTable (GenericParamConstraintTable.RId))
return;
GenericParamConstraintTable gpcTable = m_tableReader.GetGenericParamConstraintTable ();
for (int i = 0; i < gpcTable.Rows.Count; i++) {
GenericParamConstraintRow gpcRow = gpcTable [i];
GenericParameter gp = GetGenericParameterAt (gpcRow.Owner);
gp.Constraints.Add (GetTypeDefOrRef (gpcRow.Constraint, new GenericContext (gp.Owner)));
}
}
void ReadClassLayoutInfos ()
{
if (!m_tHeap.HasTable (ClassLayoutTable.RId))
return;
ClassLayoutTable clTable = m_tableReader.GetClassLayoutTable ();
for (int i = 0; i < clTable.Rows.Count; i++) {
ClassLayoutRow clRow = clTable [i];
TypeDefinition type = GetTypeDefAt (clRow.Parent);
type.PackingSize = clRow.PackingSize;
type.ClassSize = clRow.ClassSize;
}
}
void ReadFieldLayoutInfos ()
{
if (!m_tHeap.HasTable (FieldLayoutTable.RId))
return;
FieldLayoutTable flTable = m_tableReader.GetFieldLayoutTable ();
for (int i = 0; i < flTable.Rows.Count; i++) {
FieldLayoutRow flRow = flTable [i];
FieldDefinition field = GetFieldDefAt (flRow.Field);
field.Offset = flRow.Offset;
}
}
void ReadPInvokeInfos ()
{
if (!m_tHeap.HasTable (ImplMapTable.RId))
return;
ImplMapTable imTable = m_tableReader.GetImplMapTable ();
for (int i = 0; i < imTable.Rows.Count; i++) {
ImplMapRow imRow = imTable [i];
if (imRow.MemberForwarded.TokenType == TokenType.Method) { // should always be true
MethodDefinition meth = GetMethodDefAt (imRow.MemberForwarded.RID);
meth.PInvokeInfo = new PInvokeInfo (
meth, imRow.MappingFlags, MetadataRoot.Streams.StringsHeap [imRow.ImportName],
Module.ModuleReferences [(int) imRow.ImportScope - 1]);
}
}
}
void ReadProperties ()
{
if (!m_tHeap.HasTable (PropertyTable.RId))
return;
PropertyTable propsTable = m_tableReader.GetPropertyTable ();
PropertyMapTable pmapTable = m_tableReader.GetPropertyMapTable ();
m_properties = new PropertyDefinition [propsTable.Rows.Count];
for (int i = 0; i < pmapTable.Rows.Count; i++) {
PropertyMapRow pmapRow = pmapTable [i];
if (pmapRow.Parent == 0)
continue;
TypeDefinition owner = GetTypeDefAt (pmapRow.Parent);
GenericContext context = new GenericContext (owner);
int start = (int) pmapRow.PropertyList, last = propsTable.Rows.Count + 1, end;
if (i < pmapTable.Rows.Count - 1)
end = (int) pmapTable [i + 1].PropertyList;
else
end = last;
if (end > last)
end = last;
for (int j = start; j < end; j++) {
PropertyRow prow = propsTable [j - 1];
PropertySig psig = m_sigReader.GetPropSig (prow.Type);
PropertyDefinition pdef = new PropertyDefinition (
m_root.Streams.StringsHeap [prow.Name],
GetTypeRefFromSig (psig.Type, context),
prow.Flags);
pdef.MetadataToken = MetadataToken.FromMetadataRow (TokenType.Property, j - 1);
pdef.PropertyType = GetModifierType (psig.CustomMods, pdef.PropertyType);
if (!IsDeleted (pdef))
owner.Properties.Add (pdef);
m_properties [j - 1] = pdef;
}
}
}
void ReadEvents ()
{
if (!m_tHeap.HasTable (EventTable.RId))
return;
EventTable evtTable = m_tableReader.GetEventTable ();
EventMapTable emapTable = m_tableReader.GetEventMapTable ();
m_events = new EventDefinition [evtTable.Rows.Count];
for (int i = 0; i < emapTable.Rows.Count; i++) {
EventMapRow emapRow = emapTable [i];
if (emapRow.Parent == 0)
continue;
TypeDefinition owner = GetTypeDefAt (emapRow.Parent);
GenericContext context = new GenericContext (owner);
int start = (int) emapRow.EventList, last = evtTable.Rows.Count + 1, end;
if (i < (emapTable.Rows.Count - 1))
end = (int) emapTable [i + 1].EventList;
else
end = last;
if (end > last)
end = last;
for (int j = start; j < end; j++) {
EventRow erow = evtTable [j - 1];
EventDefinition edef = new EventDefinition (
m_root.Streams.StringsHeap [erow.Name],
GetTypeDefOrRef (erow.EventType, context), erow.EventFlags);
edef.MetadataToken = MetadataToken.FromMetadataRow (TokenType.Event, j - 1);
if (!IsDeleted (edef))
owner.Events.Add (edef);
m_events [j - 1] = edef;
}
}
}
void ReadSemantics ()
{
if (!m_tHeap.HasTable (MethodSemanticsTable.RId))
return;
MethodSemanticsTable semTable = m_tableReader.GetMethodSemanticsTable ();
for (int i = 0; i < semTable.Rows.Count; i++) {
MethodSemanticsRow semRow = semTable [i];
MethodDefinition semMeth = GetMethodDefAt (semRow.Method);
semMeth.SemanticsAttributes = semRow.Semantics;
switch (semRow.Association.TokenType) {
case TokenType.Event :
EventDefinition evt = GetEventDefAt (semRow.Association.RID);
if ((semRow.Semantics & MethodSemanticsAttributes.AddOn) != 0)
evt.AddMethod = semMeth;
else if ((semRow.Semantics & MethodSemanticsAttributes.Fire) != 0)
evt.InvokeMethod = semMeth;
else if ((semRow.Semantics & MethodSemanticsAttributes.RemoveOn) != 0)
evt.RemoveMethod = semMeth;
break;
case TokenType.Property :
PropertyDefinition prop = GetPropertyDefAt (semRow.Association.RID);
if ((semRow.Semantics & MethodSemanticsAttributes.Getter) != 0)
prop.GetMethod = semMeth;
else if ((semRow.Semantics & MethodSemanticsAttributes.Setter) != 0)
prop.SetMethod = semMeth;
break;
}
}
}
void ReadInterfaces ()
{
if (!m_tHeap.HasTable (InterfaceImplTable.RId))
return;
InterfaceImplTable intfsTable = m_tableReader.GetInterfaceImplTable ();
for (int i = 0; i < intfsTable.Rows.Count; i++) {
InterfaceImplRow intfsRow = intfsTable [i];
TypeDefinition owner = GetTypeDefAt (intfsRow.Class);
owner.Interfaces.Add (GetTypeDefOrRef (intfsRow.Interface, new GenericContext (owner)));
}
}
void ReadOverrides ()
{
if (!m_tHeap.HasTable (MethodImplTable.RId))
return;
MethodImplTable implTable = m_tableReader.GetMethodImplTable ();
for (int i = 0; i < implTable.Rows.Count; i++) {
MethodImplRow implRow = implTable [i];
if (implRow.MethodBody.TokenType == TokenType.Method) {
MethodDefinition owner = GetMethodDefAt (implRow.MethodBody.RID);
switch (implRow.MethodDeclaration.TokenType) {
case TokenType.Method :
owner.Overrides.Add (
GetMethodDefAt (implRow.MethodDeclaration.RID));
break;
case TokenType.MemberRef :
owner.Overrides.Add (
(MethodReference) GetMemberRefAt (
implRow.MethodDeclaration.RID, new GenericContext (owner)));
break;
}
}
}
}
void ReadSecurityDeclarations ()
{
if (!m_tHeap.HasTable (DeclSecurityTable.RId))
return;
DeclSecurityTable dsTable = m_tableReader.GetDeclSecurityTable ();
for (int i = 0; i < dsTable.Rows.Count; i++) {
DeclSecurityRow dsRow = dsTable [i];
SecurityDeclaration dec = BuildSecurityDeclaration (dsRow);
if (dsRow.Parent.RID == 0)
continue;
IHasSecurity owner = null;
switch (dsRow.Parent.TokenType) {
case TokenType.Assembly :
owner = this.Module.Assembly;
break;
case TokenType.TypeDef :
owner = GetTypeDefAt (dsRow.Parent.RID);
break;
case TokenType.Method :
owner = GetMethodDefAt (dsRow.Parent.RID);
break;
}
owner.SecurityDeclarations.Add (dec);
}
}
void ReadCustomAttributes ()
{
if (!m_tHeap.HasTable (CustomAttributeTable.RId))
return;
CustomAttributeTable caTable = m_tableReader.GetCustomAttributeTable ();
for (int i = 0; i < caTable.Rows.Count; i++) {
CustomAttributeRow caRow = caTable [i];
MethodReference ctor;
if (caRow.Type.RID == 0)
continue;
if (caRow.Type.TokenType == TokenType.Method)
ctor = GetMethodDefAt (caRow.Type.RID);
else
ctor = GetMemberRefAt (caRow.Type.RID, new GenericContext ()) as MethodReference;
CustomAttrib ca = m_sigReader.GetCustomAttrib (caRow.Value, ctor);
CustomAttribute cattr = BuildCustomAttribute (ctor, m_root.Streams.BlobHeap.Read (caRow.Value), ca);
if (caRow.Parent.RID == 0)
continue;
ICustomAttributeProvider owner = null;
switch (caRow.Parent.TokenType) {
case TokenType.Assembly :
owner = this.Module.Assembly;
break;
case TokenType.Module :
owner = this.Module;
break;
case TokenType.TypeDef :
owner = GetTypeDefAt (caRow.Parent.RID);
break;
case TokenType.TypeRef :
owner = GetTypeRefAt (caRow.Parent.RID);
break;
case TokenType.Field :
owner = GetFieldDefAt (caRow.Parent.RID);
break;
case TokenType.Method :
owner = GetMethodDefAt (caRow.Parent.RID);
break;
case TokenType.Property :
owner = GetPropertyDefAt (caRow.Parent.RID);
break;
case TokenType.Event :
owner = GetEventDefAt (caRow.Parent.RID);
break;
case TokenType.Param :
owner = GetParamDefAt (caRow.Parent.RID);
break;
case TokenType.GenericParam :
owner = GetGenericParameterAt (caRow.Parent.RID);
break;
default :
//TODO: support other ?
break;
}
if (owner != null)
owner.CustomAttributes.Add (cattr);
}
}
void ReadConstants ()
{
if (!m_tHeap.HasTable (ConstantTable.RId))
return;
ConstantTable csTable = m_tableReader.GetConstantTable ();
for (int i = 0; i < csTable.Rows.Count; i++) {
ConstantRow csRow = csTable [i];
object constant = GetConstant (csRow.Value, csRow.Type);
IHasConstant owner = null;
switch (csRow.Parent.TokenType) {
case TokenType.Field :
owner = GetFieldDefAt (csRow.Parent.RID);
break;
case TokenType.Property :
owner = GetPropertyDefAt (csRow.Parent.RID);
break;
case TokenType.Param :
owner = GetParamDefAt (csRow.Parent.RID);
break;
}
owner.Constant = constant;
}
}
void ReadExternTypes ()
{
base.VisitExternTypeCollection (Module.ExternTypes);
}
void ReadMarshalSpecs ()
{
if (!m_tHeap.HasTable (FieldMarshalTable.RId))
return;
FieldMarshalTable fmTable = m_tableReader.GetFieldMarshalTable ();
for (int i = 0; i < fmTable.Rows.Count; i++) {
FieldMarshalRow fmRow = fmTable [i];
if (fmRow.Parent.RID == 0)
continue;
IHasMarshalSpec owner = null;
switch (fmRow.Parent.TokenType) {
case TokenType.Field:
owner = GetFieldDefAt (fmRow.Parent.RID);
break;
case TokenType.Param:
owner = GetParamDefAt (fmRow.Parent.RID);
break;
}
owner.MarshalSpec = BuildMarshalDesc (
m_sigReader.GetMarshalSig (fmRow.NativeType), owner);
}
}
void ReadInitialValues ()
{
if (!m_tHeap.HasTable (FieldRVATable.RId))
return;
FieldRVATable frTable = m_tableReader.GetFieldRVATable ();
for (int i = 0; i < frTable.Rows.Count; i++) {
FieldRVARow frRow = frTable [i];
FieldDefinition field = GetFieldDefAt (frRow.Field);
field.RVA = frRow.RVA;
SetInitialValue (field);
}
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Redis/
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2013 ServiceStack.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using ServiceStack.CacheAccess;
using ServiceStack.DataAccess;
using ServiceStack.DesignPatterns.Model;
using ServiceStack.Redis.Generic;
using ServiceStack.Redis.Pipeline;
#if WINDOWS_PHONE
using ServiceStack.Text.WP;
#endif
namespace ServiceStack.Redis
{
public interface IRedisClient
: IBasicPersistenceProvider, ICacheClient
{
//Basic Redis Connection operations
long Db { get; set; }
long DbSize { get; }
Dictionary<string, string> Info { get; }
DateTime LastSave { get; }
string Host { get; }
int Port { get; }
int ConnectTimeout { get; set; }
int RetryTimeout { get; set; }
int RetryCount { get; set; }
int SendTimeout { get; set; }
string Password { get; set; }
bool HadExceptions { get; }
void Save();
void SaveAsync();
void Shutdown();
void RewriteAppendOnlyFileAsync();
void FlushDb();
//Basic Redis Connection Info
string this[string key] { get; set; }
List<string> GetAllKeys();
void SetEntry(string key, string value);
void SetEntry(string key, string value, TimeSpan expireIn);
bool SetEntryIfNotExists(string key, string value);
void SetAll(IEnumerable<string> keys, IEnumerable<string> values);
void SetAll(Dictionary<string, string> map);
string GetValue(string key);
string GetAndSetEntry(string key, string value);
List<string> GetValues(List<string> keys);
List<T> GetValues<T>(List<string> keys);
Dictionary<string, string> GetValuesMap(List<string> keys);
Dictionary<string, T> GetValuesMap<T>(List<string> keys);
long AppendToValue(string key, string value);
void RenameKey(string fromName, string toName);
string GetSubstring(string key, int fromIndex, int toIndex);
//store POCOs as hash
T GetFromHash<T>(object id);
void StoreAsHash<T>(T entity);
object StoreObject(object entity);
bool ContainsKey(string key);
bool RemoveEntry(params string[] args);
long IncrementValue(string key);
long IncrementValueBy(string key, int count);
long IncrementValueBy(string key, long count);
double IncrementValueBy(string key, double count);
long DecrementValue(string key);
long DecrementValueBy(string key, int count);
List<string> SearchKeys(string pattern);
RedisKeyType GetEntryType(string key);
string GetRandomKey();
bool ExpireEntryIn(string key, TimeSpan expireIn);
bool ExpireEntryAt(string key, DateTime expireAt);
TimeSpan GetTimeToLive(string key);
List<string> GetSortedEntryValues(string key, int startingFrom, int endingAt);
//Store entities without registering entity ids
void WriteAll<TEntity>(IEnumerable<TEntity> entities);
/// <summary>
/// Returns a high-level typed client API
/// Shorter Alias is As<T>();
/// </summary>
/// <typeparam name="T"></typeparam>
IRedisTypedClient<T> GetTypedClient<T>();
/// <summary>
/// Returns a high-level typed client API
/// </summary>
/// <typeparam name="T"></typeparam>
IRedisTypedClient<T> As<T>();
IHasNamed<IRedisList> Lists { get; set; }
IHasNamed<IRedisSet> Sets { get; set; }
IHasNamed<IRedisSortedSet> SortedSets { get; set; }
IHasNamed<IRedisHash> Hashes { get; set; }
IRedisTransaction CreateTransaction();
IRedisPipeline CreatePipeline();
IDisposable AcquireLock(string key);
IDisposable AcquireLock(string key, TimeSpan timeOut);
#region Redis pubsub
void Watch(params string[] keys);
void UnWatch();
IRedisSubscription CreateSubscription();
long PublishMessage(string toChannel, string message);
#endregion
#region Set operations
HashSet<string> GetAllItemsFromSet(string setId);
void AddItemToSet(string setId, string item);
void AddRangeToSet(string setId, List<string> items);
void RemoveItemFromSet(string setId, string item);
string PopItemFromSet(string setId);
void MoveBetweenSets(string fromSetId, string toSetId, string item);
long GetSetCount(string setId);
bool SetContainsItem(string setId, string item);
HashSet<string> GetIntersectFromSets(params string[] setIds);
void StoreIntersectFromSets(string intoSetId, params string[] setIds);
HashSet<string> GetUnionFromSets(params string[] setIds);
void StoreUnionFromSets(string intoSetId, params string[] setIds);
HashSet<string> GetDifferencesFromSet(string fromSetId, params string[] withSetIds);
void StoreDifferencesFromSet(string intoSetId, string fromSetId, params string[] withSetIds);
string GetRandomItemFromSet(string setId);
#endregion
#region List operations
List<string> GetAllItemsFromList(string listId);
List<string> GetRangeFromList(string listId, int startingFrom, int endingAt);
List<string> GetRangeFromSortedList(string listId, int startingFrom, int endingAt);
List<string> GetSortedItemsFromList(string listId, SortOptions sortOptions);
void AddItemToList(string listId, string value);
void AddRangeToList(string listId, List<string> values);
void PrependItemToList(string listId, string value);
void PrependRangeToList(string listId, List<string> values);
void RemoveAllFromList(string listId);
string RemoveStartFromList(string listId);
string BlockingRemoveStartFromList(string listId, TimeSpan? timeOut);
ItemRef BlockingRemoveStartFromLists(string []listIds, TimeSpan? timeOut);
string RemoveEndFromList(string listId);
void TrimList(string listId, int keepStartingFrom, int keepEndingAt);
long RemoveItemFromList(string listId, string value);
long RemoveItemFromList(string listId, string value, int noOfMatches);
long GetListCount(string listId);
string GetItemFromList(string listId, int listIndex);
void SetItemInList(string listId, int listIndex, string value);
//Queue operations
void EnqueueItemOnList(string listId, string value);
string DequeueItemFromList(string listId);
string BlockingDequeueItemFromList(string listId, TimeSpan? timeOut);
ItemRef BlockingDequeueItemFromLists(string []listIds, TimeSpan? timeOut);
//Stack operations
void PushItemToList(string listId, string value);
string PopItemFromList(string listId);
string BlockingPopItemFromList(string listId, TimeSpan? timeOut);
ItemRef BlockingPopItemFromLists(string []listIds, TimeSpan? timeOut);
string PopAndPushItemBetweenLists(string fromListId, string toListId);
string BlockingPopAndPushItemBetweenLists(string fromListId, string toListId, TimeSpan? timeOut);
#endregion
#region Sorted Set operations
bool AddItemToSortedSet(string setId, string value);
bool AddItemToSortedSet(string setId, string value, double score);
bool AddRangeToSortedSet(string setId, List<string> values, double score);
bool AddRangeToSortedSet(string setId, List<string> values, long score);
bool RemoveItemFromSortedSet(string setId, string value);
string PopItemWithLowestScoreFromSortedSet(string setId);
string PopItemWithHighestScoreFromSortedSet(string setId);
bool SortedSetContainsItem(string setId, string value);
double IncrementItemInSortedSet(string setId, string value, double incrementBy);
double IncrementItemInSortedSet(string setId, string value, long incrementBy);
long GetItemIndexInSortedSet(string setId, string value);
long GetItemIndexInSortedSetDesc(string setId, string value);
List<string> GetAllItemsFromSortedSet(string setId);
List<string> GetAllItemsFromSortedSetDesc(string setId);
List<string> GetRangeFromSortedSet(string setId, int fromRank, int toRank);
List<string> GetRangeFromSortedSetDesc(string setId, int fromRank, int toRank);
IDictionary<string, double> GetAllWithScoresFromSortedSet(string setId);
IDictionary<string, double> GetRangeWithScoresFromSortedSet(string setId, int fromRank, int toRank);
IDictionary<string, double> GetRangeWithScoresFromSortedSetDesc(string setId, int fromRank, int toRank);
List<string> GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore);
List<string> GetRangeFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take);
List<string> GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore);
List<string> GetRangeFromSortedSetByLowestScore(string setId, long fromScore, long toScore);
List<string> GetRangeFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take);
List<string> GetRangeFromSortedSetByLowestScore(string setId, long fromScore, long toScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, long fromScore, long toScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, double fromScore, double toScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string setId, long fromScore, long toScore, int? skip, int? take);
List<string> GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore);
List<string> GetRangeFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take);
List<string> GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore);
List<string> GetRangeFromSortedSetByHighestScore(string setId, long fromScore, long toScore);
List<string> GetRangeFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take);
List<string> GetRangeFromSortedSetByHighestScore(string setId, long fromScore, long toScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, string fromStringScore, string toStringScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, long fromScore, long toScore);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, double fromScore, double toScore, int? skip, int? take);
IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string setId, long fromScore, long toScore, int? skip, int? take);
long RemoveRangeFromSortedSet(string setId, int minRank, int maxRank);
long RemoveRangeFromSortedSetByScore(string setId, double fromScore, double toScore);
long RemoveRangeFromSortedSetByScore(string setId, long fromScore, long toScore);
long GetSortedSetCount(string setId);
long GetSortedSetCount(string setId, string fromStringScore, string toStringScore);
long GetSortedSetCount(string setId, long fromScore, long toScore);
long GetSortedSetCount(string setId, double fromScore, double toScore);
double GetItemScoreInSortedSet(string setId, string value);
long StoreIntersectFromSortedSets(string intoSetId, params string[] setIds);
long StoreUnionFromSortedSets(string intoSetId, params string[] setIds);
#endregion
#region Hash operations
bool HashContainsEntry(string hashId, string key);
bool SetEntryInHash(string hashId, string key, string value);
bool SetEntryInHashIfNotExists(string hashId, string key, string value);
void SetRangeInHash(string hashId, IEnumerable<KeyValuePair<string, string>> keyValuePairs);
long IncrementValueInHash(string hashId, string key, int incrementBy);
double IncrementValueInHash(string hashId, string key, double incrementBy);
string GetValueFromHash(string hashId, string key);
List<string> GetValuesFromHash(string hashId, params string[] keys);
bool RemoveEntryFromHash(string hashId, string key);
long GetHashCount(string hashId);
List<string> GetHashKeys(string hashId);
List<string> GetHashValues(string hashId);
Dictionary<string, string> GetAllEntriesFromHash(string hashId);
#endregion
#region Eval/Lua operations
string ExecLuaAsString(string luaBody, params string[] args);
string ExecLuaAsString(string luaBody, string[] keys, string[] args);
string ExecLuaShaAsString(string sha1, params string[] args);
string ExecLuaShaAsString(string sha1, string[] keys, string[] args);
long ExecLuaAsInt(string luaBody, params string[] args);
long ExecLuaAsInt(string luaBody, string[] keys, string[] args);
long ExecLuaShaAsInt(string sha1, params string[] args);
long ExecLuaShaAsInt(string sha1, string[] keys, string[] args);
List<string> ExecLuaAsList(string luaBody, params string[] args);
List<string> ExecLuaAsList(string luaBody, string[] keys, string[] args);
List<string> ExecLuaShaAsList(string sha1, params string[] args);
List<string> ExecLuaShaAsList(string sha1, string[] keys, string[] args);
string CalculateSha1(string luaBody);
bool HasLuaScript(string sha1Ref);
Dictionary<string, bool> WhichLuaScriptsExists(params string[] sha1Refs);
void RemoveAllLuaScripts();
void KillRunningLuaScript();
string LoadLuaScript(string body);
#endregion
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// SP2 dummy table Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class GLFBUDGDataSet : EduHubDataSet<GLFBUDG>
{
/// <inheritdoc />
public override string Name { get { return "GLFBUDG"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal GLFBUDGDataSet(EduHubContext Context)
: base(Context)
{
Index_BKEY = new Lazy<Dictionary<string, IReadOnlyList<GLFBUDG>>>(() => this.ToGroupedDictionary(i => i.BKEY));
Index_TID = new Lazy<Dictionary<int, GLFBUDG>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="GLFBUDG" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="GLFBUDG" /> fields for each CSV column header</returns>
internal override Action<GLFBUDG, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<GLFBUDG, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "BKEY":
mapper[i] = (e, v) => e.BKEY = v;
break;
case "TRBATCH":
mapper[i] = (e, v) => e.TRBATCH = v == null ? (int?)null : int.Parse(v);
break;
case "TRAMT":
mapper[i] = (e, v) => e.TRAMT = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="GLFBUDG" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="GLFBUDG" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="GLFBUDG" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{GLFBUDG}"/> of entities</returns>
internal override IEnumerable<GLFBUDG> ApplyDeltaEntities(IEnumerable<GLFBUDG> Entities, List<GLFBUDG> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.BKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.BKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, IReadOnlyList<GLFBUDG>>> Index_BKEY;
private Lazy<Dictionary<int, GLFBUDG>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find GLFBUDG by BKEY field
/// </summary>
/// <param name="BKEY">BKEY value used to find GLFBUDG</param>
/// <returns>List of related GLFBUDG entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<GLFBUDG> FindByBKEY(string BKEY)
{
return Index_BKEY.Value[BKEY];
}
/// <summary>
/// Attempt to find GLFBUDG by BKEY field
/// </summary>
/// <param name="BKEY">BKEY value used to find GLFBUDG</param>
/// <param name="Value">List of related GLFBUDG entities</param>
/// <returns>True if the list of related GLFBUDG entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByBKEY(string BKEY, out IReadOnlyList<GLFBUDG> Value)
{
return Index_BKEY.Value.TryGetValue(BKEY, out Value);
}
/// <summary>
/// Attempt to find GLFBUDG by BKEY field
/// </summary>
/// <param name="BKEY">BKEY value used to find GLFBUDG</param>
/// <returns>List of related GLFBUDG entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<GLFBUDG> TryFindByBKEY(string BKEY)
{
IReadOnlyList<GLFBUDG> value;
if (Index_BKEY.Value.TryGetValue(BKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find GLFBUDG by TID field
/// </summary>
/// <param name="TID">TID value used to find GLFBUDG</param>
/// <returns>Related GLFBUDG entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public GLFBUDG FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find GLFBUDG by TID field
/// </summary>
/// <param name="TID">TID value used to find GLFBUDG</param>
/// <param name="Value">Related GLFBUDG entity</param>
/// <returns>True if the related GLFBUDG entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out GLFBUDG Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find GLFBUDG by TID field
/// </summary>
/// <param name="TID">TID value used to find GLFBUDG</param>
/// <returns>Related GLFBUDG entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public GLFBUDG TryFindByTID(int TID)
{
GLFBUDG value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a GLFBUDG table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GLFBUDG]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[GLFBUDG](
[TID] int IDENTITY NOT NULL,
[BKEY] varchar(15) NOT NULL,
[TRBATCH] int NULL,
[TRAMT] money NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [GLFBUDG_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE CLUSTERED INDEX [GLFBUDG_Index_BKEY] ON [dbo].[GLFBUDG]
(
[BKEY] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFBUDG]') AND name = N'GLFBUDG_Index_TID')
ALTER INDEX [GLFBUDG_Index_TID] ON [dbo].[GLFBUDG] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLFBUDG]') AND name = N'GLFBUDG_Index_TID')
ALTER INDEX [GLFBUDG_Index_TID] ON [dbo].[GLFBUDG] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="GLFBUDG"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="GLFBUDG"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<GLFBUDG> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[GLFBUDG] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the GLFBUDG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the GLFBUDG data set</returns>
public override EduHubDataSetDataReader<GLFBUDG> GetDataSetDataReader()
{
return new GLFBUDGDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the GLFBUDG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the GLFBUDG data set</returns>
public override EduHubDataSetDataReader<GLFBUDG> GetDataSetDataReader(List<GLFBUDG> Entities)
{
return new GLFBUDGDataReader(new EduHubDataSetLoadedReader<GLFBUDG>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class GLFBUDGDataReader : EduHubDataSetDataReader<GLFBUDG>
{
public GLFBUDGDataReader(IEduHubDataSetReader<GLFBUDG> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 7; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // BKEY
return Current.BKEY;
case 2: // TRBATCH
return Current.TRBATCH;
case 3: // TRAMT
return Current.TRAMT;
case 4: // LW_DATE
return Current.LW_DATE;
case 5: // LW_TIME
return Current.LW_TIME;
case 6: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // TRBATCH
return Current.TRBATCH == null;
case 3: // TRAMT
return Current.TRAMT == null;
case 4: // LW_DATE
return Current.LW_DATE == null;
case 5: // LW_TIME
return Current.LW_TIME == null;
case 6: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // BKEY
return "BKEY";
case 2: // TRBATCH
return "TRBATCH";
case 3: // TRAMT
return "TRAMT";
case 4: // LW_DATE
return "LW_DATE";
case 5: // LW_TIME
return "LW_TIME";
case 6: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "BKEY":
return 1;
case "TRBATCH":
return 2;
case "TRAMT":
return 3;
case "LW_DATE":
return 4;
case "LW_TIME":
return 5;
case "LW_USER":
return 6;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.WebSockets
{
public sealed partial class ClientWebSocket : WebSocket
{
private enum InternalState
{
Created = 0,
Connecting = 1,
Connected = 2,
Disposed = 3
}
private readonly ClientWebSocketOptions _options;
private WebSocketHandle _innerWebSocket; // may be mutable struct; do not make readonly
// NOTE: this is really an InternalState value, but Interlocked doesn't support
// operations on values of enum types.
private int _state;
public ClientWebSocket()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
WebSocketHandle.CheckPlatformSupport();
_state = (int)InternalState.Created;
_options = new ClientWebSocketOptions() { Proxy = DefaultWebProxy.Instance };
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
#region Properties
public ClientWebSocketOptions Options
{
get
{
return _options;
}
}
public override WebSocketCloseStatus? CloseStatus
{
get
{
if (WebSocketHandle.IsValid(_innerWebSocket))
{
return _innerWebSocket.CloseStatus;
}
return null;
}
}
public override string CloseStatusDescription
{
get
{
if (WebSocketHandle.IsValid(_innerWebSocket))
{
return _innerWebSocket.CloseStatusDescription;
}
return null;
}
}
public override string SubProtocol
{
get
{
if (WebSocketHandle.IsValid(_innerWebSocket))
{
return _innerWebSocket.SubProtocol;
}
return null;
}
}
public override WebSocketState State
{
get
{
// state == Connected or Disposed
if (WebSocketHandle.IsValid(_innerWebSocket))
{
return _innerWebSocket.State;
}
switch ((InternalState)_state)
{
case InternalState.Created:
return WebSocketState.None;
case InternalState.Connecting:
return WebSocketState.Connecting;
default: // We only get here if disposed before connecting
Debug.Assert((InternalState)_state == InternalState.Disposed);
return WebSocketState.Closed;
}
}
}
#endregion Properties
public Task ConnectAsync(Uri uri, CancellationToken cancellationToken)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
if (!uri.IsAbsoluteUri)
{
throw new ArgumentException(SR.net_uri_NotAbsolute, nameof(uri));
}
if (uri.Scheme != UriScheme.Ws && uri.Scheme != UriScheme.Wss)
{
throw new ArgumentException(SR.net_WebSockets_Scheme, nameof(uri));
}
// Check that we have not started already
var priorState = (InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connecting, (int)InternalState.Created);
if (priorState == InternalState.Disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
else if (priorState != InternalState.Created)
{
throw new InvalidOperationException(SR.net_WebSockets_AlreadyStarted);
}
_options.SetToReadOnly();
return ConnectAsyncCore(uri, cancellationToken);
}
private async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken)
{
_innerWebSocket = WebSocketHandle.Create();
try
{
// Change internal state to 'connected' to enable the other methods
if ((InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connected, (int)InternalState.Connecting) != InternalState.Connecting)
{
// Aborted/Disposed during connect.
throw new ObjectDisposedException(GetType().FullName);
}
await _innerWebSocket.ConnectAsyncCore(uri, cancellationToken, _options).ConfigureAwait(false);
}
catch (Exception ex)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, ex);
throw;
}
}
public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage,
CancellationToken cancellationToken)
{
ThrowIfNotConnected();
return _innerWebSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
}
public override ValueTask SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
{
ThrowIfNotConnected();
return _innerWebSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken);
}
public override Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer,
CancellationToken cancellationToken)
{
ThrowIfNotConnected();
return _innerWebSocket.ReceiveAsync(buffer, cancellationToken);
}
public override ValueTask<ValueWebSocketReceiveResult> ReceiveAsync(Memory<byte> buffer, CancellationToken cancellationToken)
{
ThrowIfNotConnected();
return _innerWebSocket.ReceiveAsync(buffer, cancellationToken);
}
public override Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription,
CancellationToken cancellationToken)
{
ThrowIfNotConnected();
return _innerWebSocket.CloseAsync(closeStatus, statusDescription, cancellationToken);
}
public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription,
CancellationToken cancellationToken)
{
ThrowIfNotConnected();
return _innerWebSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
}
public override void Abort()
{
if ((InternalState)_state == InternalState.Disposed)
{
return;
}
if (WebSocketHandle.IsValid(_innerWebSocket))
{
_innerWebSocket.Abort();
}
Dispose();
}
public override void Dispose()
{
var priorState = (InternalState)Interlocked.Exchange(ref _state, (int)InternalState.Disposed);
if (priorState == InternalState.Disposed)
{
// No cleanup required.
return;
}
if (WebSocketHandle.IsValid(_innerWebSocket))
{
_innerWebSocket.Dispose();
}
}
private void ThrowIfNotConnected()
{
if ((InternalState)_state == InternalState.Disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
else if ((InternalState)_state != InternalState.Connected)
{
throw new InvalidOperationException(SR.net_WebSockets_NotConnected);
}
}
/// <summary>Used as a sentinel to indicate that ClientWebSocket should use the system's default proxy.</summary>
internal sealed class DefaultWebProxy : IWebProxy
{
public static DefaultWebProxy Instance { get; } = new DefaultWebProxy();
public ICredentials Credentials { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public Uri GetProxy(Uri destination) => throw new NotSupportedException();
public bool IsBypassed(Uri host) => throw new NotSupportedException();
}
}
}
| |
// 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.Runtime;
using System.Runtime.InteropServices;
using System.ServiceModel;
namespace System.Collections.Generic
{
[ComVisible(false)]
public abstract class SynchronizedKeyedCollection<K, T> : SynchronizedCollection<T>
{
private const int defaultThreshold = 0;
private IEqualityComparer<K> _comparer;
private Dictionary<K, T> _dictionary;
private int _keyCount;
private int _threshold;
protected SynchronizedKeyedCollection()
{
_comparer = EqualityComparer<K>.Default;
_threshold = int.MaxValue;
}
protected SynchronizedKeyedCollection(object syncRoot)
: base(syncRoot)
{
_comparer = EqualityComparer<K>.Default;
_threshold = int.MaxValue;
}
protected SynchronizedKeyedCollection(object syncRoot, IEqualityComparer<K> comparer)
: base(syncRoot)
{
_comparer = comparer ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(comparer)));
_threshold = int.MaxValue;
}
protected SynchronizedKeyedCollection(object syncRoot, IEqualityComparer<K> comparer, int dictionaryCreationThreshold)
: base(syncRoot)
{
if (dictionaryCreationThreshold < -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(dictionaryCreationThreshold), dictionaryCreationThreshold,
SR.Format(SR.ValueMustBeInRange, -1, int.MaxValue)));
}
else if (dictionaryCreationThreshold == -1)
{
_threshold = int.MaxValue;
}
else
{
_threshold = dictionaryCreationThreshold;
}
_comparer = comparer ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(comparer)));
}
public T this[K key]
{
get
{
if (key == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(key)));
}
lock (SyncRoot)
{
if (_dictionary != null)
{
return _dictionary[key];
}
for (int i = 0; i < Items.Count; i++)
{
T item = Items[i];
if (_comparer.Equals(key, GetKeyForItem(item)))
{
return item;
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new KeyNotFoundException());
}
}
}
protected IDictionary<K, T> Dictionary
{
get { return _dictionary; }
}
private void AddKey(K key, T item)
{
if (_dictionary != null)
{
_dictionary.Add(key, item);
}
else if (_keyCount == _threshold)
{
CreateDictionary();
_dictionary.Add(key, item);
}
else
{
if (Contains(key))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.CannotAddTwoItemsWithTheSameKeyToSynchronizedKeyedCollection0));
}
_keyCount++;
}
}
protected void ChangeItemKey(T item, K newKey)
{
// check if the item exists in the collection
if (!ContainsItem(item))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.ItemDoesNotExistInSynchronizedKeyedCollection0));
}
K oldKey = GetKeyForItem(item);
if (!_comparer.Equals(newKey, oldKey))
{
if (newKey != null)
{
AddKey(newKey, item);
}
if (oldKey != null)
{
RemoveKey(oldKey);
}
}
}
protected override void ClearItems()
{
base.ClearItems();
if (_dictionary != null)
{
_dictionary.Clear();
}
_keyCount = 0;
}
public bool Contains(K key)
{
if (key == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(key)));
}
lock (SyncRoot)
{
if (_dictionary != null)
{
return _dictionary.ContainsKey(key);
}
if (key != null)
{
for (int i = 0; i < Items.Count; i++)
{
T item = Items[i];
if (_comparer.Equals(key, GetKeyForItem(item)))
{
return true;
}
}
}
return false;
}
}
private bool ContainsItem(T item)
{
K key;
if ((_dictionary == null) || ((key = GetKeyForItem(item)) == null))
{
return Items.Contains(item);
}
T itemInDict;
if (_dictionary.TryGetValue(key, out itemInDict))
{
return EqualityComparer<T>.Default.Equals(item, itemInDict);
}
return false;
}
private void CreateDictionary()
{
_dictionary = new Dictionary<K, T>(_comparer);
foreach (T item in Items)
{
K key = GetKeyForItem(item);
if (key != null)
{
_dictionary.Add(key, item);
}
}
}
protected abstract K GetKeyForItem(T item);
protected override void InsertItem(int index, T item)
{
K key = GetKeyForItem(item);
if (key != null)
{
AddKey(key, item);
}
base.InsertItem(index, item);
}
public bool Remove(K key)
{
if (key == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(key)));
}
lock (SyncRoot)
{
if (_dictionary != null)
{
if (_dictionary.ContainsKey(key))
{
return Remove(_dictionary[key]);
}
else
{
return false;
}
}
else
{
for (int i = 0; i < Items.Count; i++)
{
if (_comparer.Equals(key, GetKeyForItem(Items[i])))
{
RemoveItem(i);
return true;
}
}
return false;
}
}
}
protected override void RemoveItem(int index)
{
K key = GetKeyForItem(Items[index]);
if (key != null)
{
RemoveKey(key);
}
base.RemoveItem(index);
}
private void RemoveKey(K key)
{
if (!(key != null))
{
Fx.Assert("key shouldn't be null!");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(key));
}
if (_dictionary != null)
{
_dictionary.Remove(key);
}
else
{
_keyCount--;
}
}
protected override void SetItem(int index, T item)
{
K newKey = GetKeyForItem(item);
K oldKey = GetKeyForItem(Items[index]);
if (_comparer.Equals(newKey, oldKey))
{
if ((newKey != null) && (_dictionary != null))
{
_dictionary[newKey] = item;
}
}
else
{
if (newKey != null)
{
AddKey(newKey, item);
}
if (oldKey != null)
{
RemoveKey(oldKey);
}
}
base.SetItem(index, item);
}
}
}
| |
//
// Copyright 2020 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using Google.Solutions.Common.Diagnostics;
using Google.Solutions.IapDesktop.Application.Controls;
using Google.Solutions.IapDesktop.Application.ObjectModel;
using Google.Solutions.IapDesktop.Application.Services.Settings;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
namespace Google.Solutions.IapDesktop.Application.Views
{
[ComVisible(false)]
[SkipCodeCoverage("GUI plumbing")]
public partial class ToolWindow : DockContent
{
private readonly DockPanel panel;
private readonly DockState initialDockState;
private DockState lastDockState;
public ContextMenuStrip TabContextStrip => this.contextMenuStrip;
public bool IsClosed { get; private set; } = false;
public ToolWindow()
{
InitializeComponent();
AutoScaleMode = AutoScaleMode.Dpi;
}
public ToolWindow(
IServiceProvider serviceProvider,
DockState defaultDockState) : this()
{
this.panel = serviceProvider.GetService<IMainForm>().MainPanel;
var stateRepository = serviceProvider.GetService<ToolWindowStateRepository>();
this.lastDockState = defaultDockState;
// Read persisted window state.
var state = stateRepository.GetSetting(
GetType().Name, // Unique name of tool window
defaultDockState);
this.initialDockState = state.DockState.EnumValue;
// Save persisted window state.
this.Disposed += (sender, args) =>
{
//
// NB. At this point, it's too late to read this.DockState,
// so we have to rely on the value captured during previous
// state transitions.
//
try
{
if (
// If the window was closed, reset its saved state.
// Note that we're only interested in storing the
// location, not whether the window is visible or not.
this.IsClosed ||
lastDockState == DockState.Hidden ||
lastDockState == DockState.Unknown ||
// Ignore Document and Float as these are more complicated
// and not worth the trouble.
lastDockState == DockState.Document ||
lastDockState == DockState.Float)
{
// Ignore Hidden state as we only want to restore
// the dock location, not whether the window is
// shown or not.
state.DockState.Reset();
}
else
{
// Restore dock state on next run.
state.DockState.EnumValue = lastDockState;
}
stateRepository.SetSetting(state);
}
catch (Exception e)
{
ApplicationTraceSources.Default.TraceWarning(
"Saving tool window state failed: {0}", e.Message);
}
};
}
//---------------------------------------------------------------------
// Show/Hide.
//---------------------------------------------------------------------
public void CloseSafely()
{
if (this.HideOnClose)
{
Hide();
}
else
{
Close();
}
}
public virtual void ShowWindow(bool activate)
{
Debug.Assert(this.panel != null);
this.TabText = this.Text;
// NB. IsHidden indicates that the window is not shown at all,
// not even as auto-hide.
if (this.IsHidden)
{
// Show in default position.
Show(this.panel, this.initialDockState);
}
if (activate)
{
// If the window is in auto-hide mode, simply activating
// is not enough.
switch (this.VisibleState)
{
case DockState.DockTopAutoHide:
case DockState.DockBottomAutoHide:
case DockState.DockLeftAutoHide:
case DockState.DockRightAutoHide:
this.panel.ActiveAutoHideContent = this;
break;
}
// Move focus to window.
Activate();
//
// If an auto-hide window loses focus and closes, we fail to
// catch that event.
// To force an update, disregard the cached state and re-raise
// the UserVisibilityChanged event.
//
OnUserVisibilityChanged(true);
this.wasUserVisible = true;
}
}
public virtual void ShowWindow() => ShowWindow(true);
public bool IsAutoHide
{
get
{
switch (this.VisibleState)
{
case DockState.DockTopAutoHide:
case DockState.DockBottomAutoHide:
case DockState.DockLeftAutoHide:
case DockState.DockRightAutoHide:
return true;
default:
return false;
}
}
set
{
switch (this.VisibleState)
{
case DockState.DockTop:
case DockState.DockTopAutoHide:
this.DockState = DockState.DockTopAutoHide;
break;
case DockState.DockBottom:
case DockState.DockBottomAutoHide:
this.DockState = DockState.DockBottomAutoHide;
break;
case DockState.DockLeft:
case DockState.DockLeftAutoHide:
this.DockState = DockState.DockLeftAutoHide;
break;
case DockState.DockRight:
case DockState.DockRightAutoHide:
this.DockState = DockState.DockRightAutoHide;
break;
}
}
}
public bool IsDocked
{
get
{
switch (this.VisibleState)
{
case DockState.DockTop:
case DockState.DockBottom:
case DockState.DockLeft:
case DockState.DockRight:
return true;
default:
return false;
}
}
}
public bool IsDockable => this.IsDocked || this.IsAutoHide || this.IsFloat;
//---------------------------------------------------------------------
// Window events.
//---------------------------------------------------------------------
private void closeMenuItem_Click(object sender, System.EventArgs e)
{
this.CloseSafely();
}
private void ToolWindow_KeyUp(object sender, KeyEventArgs e)
{
if (this.DockState != DockState.Document && e.Shift && e.KeyCode == Keys.Escape)
{
CloseSafely();
}
}
//---------------------------------------------------------------------
// Track visibility.
//
// NB. The DockPanel library does not provide good properties or evens
// that would allow you to determine whether a window is effectively
// visible to the user or not.
//
// This table shows the value of key properties based on the window state:
//
//
// ---------------------------------------------------------------------------------------
// | | | | | Pane.ActiveContent
// | State | IsActivated | IsFloat | Visible/DockState | == this
// ---------------------------------------------------------------------------------------
// Float | Single pane | (any) | TRUE | Float | TRUE
// | Split pane, focus | FALSE | TRUE | Float | TRUE
// | Split pane, no focus| TRUE | TRUE | Float | TRUE
// | Background | FALSE | TRUE | Float | FALSE
// ---------------------------------------------------------------------------------------
// AutoHide | Single | (any) | FALSE | DockRightAutoHide | TRUE
// | Background | (any) | FALSE | DockRightAutoHide | TRUE
// ---------------------------------------------------------------------------------------
// Dock | Single pane | TRUE | FALSE | DockRight | TRUE
// | Split pane, focus | FALSE (!) | FALSE | DockRight | TRUE
// | Split pane, no focus| TRUE (!) | FALSE | DockRight | TRUE
// | Background | FALSE | FALSE | DockRight | FALSE
// -----------------------------------------------------------------------------------------
//
// IsHidden is TRUE during construction, and FALSE ever after.
// When docked and hidden, the size is reset to (0, 0)
//
protected bool IsInBackground =>
(this.IsFloat && this.Pane.ActiveContent != this) ||
(this.IsAutoHide && this.Size.Height == 0 && this.Size.Width == 0) ||
(this.IsDocked && this.Pane.ActiveContent != this);
protected bool IsUserVisible => !this.IsHidden && !IsInBackground;
private bool wasUserVisible = false;
private void RaiseUserVisibilityChanged()
{
// Only call OnUserVisibilityChanged if there really was a change.
if (this.IsUserVisible != this.wasUserVisible)
{
OnUserVisibilityChanged(this.IsUserVisible);
this.wasUserVisible = this.IsUserVisible;
}
}
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
this.lastDockState = this.DockState;
RaiseUserVisibilityChanged();
}
protected override void OnLeave(EventArgs e)
{
base.OnLeave(e);
this.lastDockState = this.DockState;
RaiseUserVisibilityChanged();
}
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
this.lastDockState = this.DockState;
RaiseUserVisibilityChanged();
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
this.IsClosed = false;
this.lastDockState = this.DockState;
RaiseUserVisibilityChanged();
}
protected override void OnClosed(EventArgs e)
{
// NB. This method might be invoked more than once if a disconnect
// event coincides (which is reasnably common when closing the app
// with active sessions).
base.OnClosed(e);
this.IsClosed = true;
}
protected virtual void OnUserVisibilityChanged(bool visible)
{
// Can be overriden in derived class.
}
}
}
| |
using System;
using System.Security.Cryptography;
using System.Text;
using LavaLeak.Diplomata.Dictionaries;
using LavaLeak.Diplomata.Helpers;
using LavaLeak.Diplomata.Models.Submodels;
using LavaLeak.Diplomata.Persistence;
using LavaLeak.Diplomata.Persistence.Models;
using UnityEngine;
namespace LavaLeak.Diplomata.Models
{
[Serializable]
public class Message : Data
{
// TODO: Replace with System.Guid.
[SerializeField]
private string uniqueId;
// TODO: Use only unique id.
public int id;
public bool isAChoice;
public bool disposable;
public int columnId;
public string imagePath = string.Empty;
public Condition[] conditions;
public LanguageDictionary[] content;
public AttachedContent[] attachedContent;
public LanguageDictionary[] screenplayNotes;
public AttributeDictionary[] attributes;
public Effect[] effects;
public AnimatorAttributeSetter[] animatorAttributesSetters;
public LanguageDictionary[] audioClipPath;
public string labelId;
[NonSerialized]
public bool alreadySpoked;
[NonSerialized]
public AudioClip audioClip;
[NonSerialized]
public Texture2D image;
[NonSerialized]
public Sprite sprite;
public Message() {}
public Message(Message msg, int id)
{
this.id = id;
isAChoice = msg.isAChoice;
disposable = msg.disposable;
columnId = msg.columnId;
imagePath = msg.imagePath;
labelId = msg.labelId;
conditions = ArrayHelper.Copy(msg.conditions);
content = ArrayHelper.Copy(msg.content);
attachedContent = ArrayHelper.Copy(msg.attachedContent);
screenplayNotes = ArrayHelper.Copy(msg.screenplayNotes);
attributes = ArrayHelper.Copy(msg.attributes);
effects = ArrayHelper.Copy(msg.effects);
animatorAttributesSetters = ArrayHelper.Copy(msg.animatorAttributesSetters);
audioClipPath = ArrayHelper.Copy(msg.audioClipPath);
uniqueId = SetUniqueId();
}
public Message(int id, string emitter, int columnId, string labelId, Options options)
{
conditions = new Condition[0];
content = new LanguageDictionary[0];
attachedContent = new AttachedContent[0];
attributes = new AttributeDictionary[0];
screenplayNotes = new LanguageDictionary[0];
effects = new Effect[0];
audioClipPath = new LanguageDictionary[0];
animatorAttributesSetters = new AnimatorAttributeSetter[0];
this.labelId = labelId;
foreach (string str in options.attributes)
{
attributes = ArrayHelper.Add(attributes, new AttributeDictionary(str));
}
foreach (Language lang in options.languages)
{
content = ArrayHelper.Add(content, new LanguageDictionary(lang.name, "[ Message content here ]"));
screenplayNotes = ArrayHelper.Add(screenplayNotes, new LanguageDictionary(lang.name, ""));
audioClipPath = ArrayHelper.Add(audioClipPath, new LanguageDictionary(lang.name, string.Empty));
}
this.id = id;
this.columnId = columnId;
uniqueId = SetUniqueId();
}
private string SetUniqueId()
{
MD5 md5Hash = MD5.Create();
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(
"Diplomata" + id + columnId +
UnityEngine.Random.Range(-2147483648, 2147483647)
));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
public string GetUniqueId()
{
return uniqueId;
}
public Sprite GetSprite(Vector2 pivot)
{
if (sprite == null)
{
image = (Texture2D) Resources.Load(imagePath);
sprite = Sprite.Create(image, new Rect(0, 0, image.width, image.height), pivot);
}
return sprite;
}
/// <summary>
/// Get all messages contents of the context.
/// </summary>
/// <param name="context">A context that is parent of the messages.</param>
/// <param name="language">The language of the contents.</param>
/// <returns>Return a string array with all contents.</returns>
public static string[] GetContents(Context context, string language)
{
var contents = new string[0];
if (context != null)
{
foreach (var column in context.columns)
{
foreach (var message in column.messages)
{
foreach (var content in message.content)
{
if (content.key == language) contents = ArrayHelper.Add(contents, content.value);
}
}
}
}
return contents;
}
/// <summary>
/// Get the message content.
/// </summary>
/// <param name="language">The language of the name.</param>
/// <returns>The name string.</returns>
public string GetContent(string language)
{
foreach (var langContent in content)
{
if (langContent.key == language) return langContent.value;
}
return string.Empty;
}
/// <summary>
/// Find a message by it unique id.
/// </summary>
/// <param name="array">A array of messages.</param>
/// <param name="uniqueId">The unique id (a string guid) of the message.</param>
/// <returns>The message if found, or null.</returns>
public static Message Find(Message[] array, string uniqueId)
{
return (Message) Helpers.Find.In(array).Where("uniqueId", uniqueId).Result;
}
/// <summary>
/// Find a message by it row id (it index).
/// </summary>
/// <param name="array">A array of messages.</param>
/// <param name="rowId">The row id (it index) of the message.</param>
/// <returns>The message if found, or null.</returns>
public static Message Find(Message[] array, int rowId)
{
return (Message) Helpers.Find.In(array).Where("id", rowId).Result;
}
public static Message[] ResetIDs(Message[] array)
{
Message[] temp = new Message[0];
for (int i = 0; i < array.Length + 1; i++)
{
Message msg = Find(array, i);
if (msg != null)
{
temp = ArrayHelper.Add(temp, msg);
}
}
for (int j = 0; j < temp.Length; j++)
{
if (temp[j].id == j + 1)
{
temp[j].id = j;
}
}
return temp;
}
public Effect AddCustomEffect()
{
effects = ArrayHelper.Add(effects, new Effect());
return effects[effects.Length - 1];
}
public override Persistent GetData()
{
var message = new MessagePersistent();
message.id = uniqueId;
message.alreadySpoked = alreadySpoked;
return message;
}
public override void SetData(Persistent persistentData)
{
uniqueId = ((MessagePersistent) persistentData).id;
alreadySpoked = ((MessagePersistent) persistentData).alreadySpoked;
}
}
}
| |
using System;
using System.IO;
using System.Diagnostics;
using Microsoft.Xna.Framework;
namespace CocosSharp
{
public class CCSprite : CCNode, ICCTexture
{
bool flipX;
bool flipY;
bool isTextureRectRotated;
bool opacityModifyRGB;
bool texQuadDirty;
bool halfTexelOffset;
CCPoint unflippedOffsetPositionFromCenter;
CCSize untrimmedSizeInPixels;
CCRect textureRectInPixels;
CCQuadCommand quadCommand;
#region Properties
// Static properties
public static bool DefaultHalfTexelOffset { get; set; }
public static float DefaultTexelToContentSizeRatio
{
set { DefaultTexelToContentSizeRatios = new CCSize(value, value); }
}
public static CCSize DefaultTexelToContentSizeRatios { get; set; }
// Instance properties
public int AtlasIndex { get ; internal set; }
internal CCTextureAtlas TextureAtlas { get; set; }
public bool HalfTexelOffset
{
get { return halfTexelOffset; }
set
{
if (halfTexelOffset != value)
{
halfTexelOffset = value;
texQuadDirty = true;
}
}
}
public bool IsAntialiased
{
get { return Texture.IsAntialiased; }
set { Texture.IsAntialiased = value; }
}
public override bool IsColorModifiedByOpacity
{
get { return opacityModifyRGB; }
set
{
if (opacityModifyRGB != value)
{
opacityModifyRGB = value;
UpdateColor();
}
}
}
public bool IsTextureRectRotated
{
get { return isTextureRectRotated; }
set
{
if (isTextureRectRotated != value)
{
isTextureRectRotated = value;
texQuadDirty = true;
}
}
}
public bool FlipX
{
get { return flipX; }
set
{
if (flipX != value)
{
flipX = value;
texQuadDirty = true;
}
}
}
public bool FlipY
{
get { return flipY; }
set
{
if (flipY != value)
{
flipY = value;
texQuadDirty = true;
}
}
}
public override bool Visible
{
get
{
return base.Visible;
}
set
{
base.Visible = value;
texQuadDirty = true;
}
}
public override byte Opacity
{
get { return base.Opacity; }
set
{
base.Opacity = value;
UpdateColor();
}
}
public CCBlendFunc BlendFunc
{
get { return quadCommand.BlendType; }
set { quadCommand.BlendType = value; }
}
public override CCColor3B Color
{
get { return base.Color; }
set
{
base.Color = value;
UpdateColor();
}
}
public override CCSize ContentSize
{
get { return base.ContentSize; }
set
{
base.ContentSize = value;
texQuadDirty = true;
}
}
public CCRect TextureRectInPixels
{
get { return textureRectInPixels; }
set
{
if(textureRectInPixels != value)
{
textureRectInPixels = value;
if(ContentSize == CCSize.Zero)
ContentSize = textureRectInPixels.Size / DefaultTexelToContentSizeRatios;
texQuadDirty = true;
}
}
}
public CCSpriteFrame SpriteFrame
{
get
{
return new CCSpriteFrame(
ContentSize,
Texture,
TextureRectInPixels,
UntrimmedSizeInPixels,
IsTextureRectRotated,
unflippedOffsetPositionFromCenter
);
}
set
{
if (value != null)
{
CCTexture2D newTexture = value.Texture;
// update texture before updating texture rect
if (newTexture != Texture)
{
Texture = newTexture;
}
// update rect
IsTextureRectRotated = value.IsRotated;
textureRectInPixels = value.TextureRectInPixels;
unflippedOffsetPositionFromCenter = value.OffsetInPixels;
UntrimmedSizeInPixels = value.OriginalSizeInPixels;
ContentSize = UntrimmedSizeInPixels / DefaultTexelToContentSizeRatios;
texQuadDirty = true;
}
}
}
public CCTexture2D Texture
{
get { return quadCommand.Texture; }
set
{
if (Texture != value)
{
quadCommand.Texture = value;
if(TextureRectInPixels == CCRect.Zero)
{
CCSize texSize = value.ContentSizeInPixels;
TextureRectInPixels = new CCRect(0.0f, 0.0f, texSize.Width, texSize.Height);
}
if(ContentSize == CCSize.Zero)
ContentSize = textureRectInPixels.Size / DefaultTexelToContentSizeRatios;
UpdateBlendFunc();
}
}
}
protected internal CCSize UntrimmedSizeInPixels
{
get
{
if(untrimmedSizeInPixels == CCSize.Zero)
return TextureRectInPixels.Size;
return untrimmedSizeInPixels;
}
set
{
if (untrimmedSizeInPixels != value)
{
untrimmedSizeInPixels = value;
texQuadDirty = true;
}
}
}
protected internal CCV3F_C4B_T2F_Quad Quad
{
get
{
if(texQuadDirty)
UpdateSpriteTextureQuads();
return quadCommand.Quads[0];
}
}
#endregion Properties
#region Constructors
static CCSprite()
{
DefaultTexelToContentSizeRatios = CCSize.One;
}
public CCSprite()
{
quadCommand = new CCQuadCommand(1);
IsTextureRectRotated = false;
HalfTexelOffset = DefaultHalfTexelOffset;
opacityModifyRGB = true;
BlendFunc = CCBlendFunc.AlphaBlend;
texQuadDirty = true;
}
public CCSprite(CCTexture2D texture=null, CCRect? texRectInPixels=null, bool rotated=false) : this()
{
InitWithTexture(texture, texRectInPixels, rotated);
}
public CCSprite(CCSpriteFrame spriteFrame) : this(spriteFrame.ContentSize, spriteFrame)
{
}
public CCSprite(CCSize contentSize, CCSpriteFrame spriteFrame) : this()
{
ContentSize = contentSize;
InitWithSpriteFrame(spriteFrame);
}
public CCSprite(string fileName, CCRect? texRectInPixels=null) : this()
{
InitWithFile(fileName, texRectInPixels);
}
void InitWithTexture(CCTexture2D texture, CCRect? texRectInPixels=null, bool rotated=false)
{
IsTextureRectRotated = rotated;
CCSize texSize = (texture != null) ? texture.ContentSizeInPixels : CCSize.Zero;
textureRectInPixels = texRectInPixels ?? new CCRect(0.0f, 0.0f, texSize.Width, texSize.Height);
opacityModifyRGB = true;
BlendFunc = CCBlendFunc.AlphaBlend;
AnchorPoint = CCPoint.AnchorMiddle;
Texture = texture;
// If content size not initialized, assume worldspace dimensions match texture dimensions
if(ContentSize == CCSize.Zero)
ContentSize = textureRectInPixels.Size / CCSprite.DefaultTexelToContentSizeRatios;
texQuadDirty = true;
}
void InitWithSpriteFrame(CCSpriteFrame spriteFrame)
{
opacityModifyRGB = true;
BlendFunc = CCBlendFunc.AlphaBlend;
AnchorPoint = CCPoint.AnchorMiddle;
SpriteFrame = spriteFrame;
}
void InitWithFile(string fileName, CCRect? rectInPoints=null)
{
Debug.Assert(!String.IsNullOrEmpty(fileName), "Invalid filename for sprite");
// Try sprite frame cache first
CCSpriteFrame frame = CCSpriteFrameCache.SharedSpriteFrameCache[fileName];
if (frame != null)
{
InitWithSpriteFrame(frame);
}
else
{
// If frame doesn't exist, try texture cache
CCTexture2D texture = CCTextureCache.SharedTextureCache.AddImage(fileName);
if (texture != null)
{
InitWithTexture(texture, rectInPoints);
}
}
}
#endregion Constructors
protected override void VisitRenderer(ref CCAffineTransform worldTransform)
{
if(texQuadDirty)
UpdateSpriteTextureQuads();
quadCommand.GlobalDepth = worldTransform.Tz;
quadCommand.WorldTransform = worldTransform;
Renderer.AddCommand(quadCommand);
}
public bool IsSpriteFrameDisplayed(CCSpriteFrame frame)
{
CCRect r = frame.TextureRectInPixels;
return (
CCRect.Equal(ref r, ref textureRectInPixels) &&
frame.Texture.Name == Texture.Name
);
}
public void SetSpriteFrameWithAnimationName(string animationName, int frameIndex)
{
Debug.Assert(!String.IsNullOrEmpty(animationName),
"CCSprite#setDisplayFrameWithAnimationName. animationName must not be NULL");
CCAnimation a = CCAnimationCache.SharedAnimationCache[animationName];
Debug.Assert(a != null, "CCSprite#setDisplayFrameWithAnimationName: Frame not found");
var frame = (CCAnimationFrame)a.Frames[frameIndex];
Debug.Assert(frame != null, "CCSprite#setDisplayFrame. Invalid frame");
SpriteFrame = frame.SpriteFrame;
}
#region Color managment
#region Texture management
public void ReplaceTexture(CCTexture2D texture, CCRect textureRectInPixels)
{
Texture = texture;
TextureRectInPixels = textureRectInPixels;
}
public void MaximizeTextureRect()
{
if(Texture != null)
{
CCSize texSize = Texture.ContentSizeInPixels;
TextureRectInPixels = new CCRect(0.0f, 0.0f, texSize.Width, texSize.Height);
}
}
#endregion Texture management
public override void UpdateColor()
{
quadCommand.RequestUpdateQuads(UpdateColorCallback);
}
void UpdateColorCallback(ref CCV3F_C4B_T2F_Quad[] quads)
{
var color4 = new CCColor4B(DisplayedColor.R, DisplayedColor.G, DisplayedColor.B, DisplayedOpacity);
if(opacityModifyRGB)
{
color4.R = (byte)(color4.R * DisplayedOpacity / 255.0f);
color4.G = (byte)(color4.G * DisplayedOpacity / 255.0f);
color4.B = (byte)(color4.B * DisplayedOpacity / 255.0f);
}
quads[0].BottomLeft.Colors = color4;
quads[0].BottomRight.Colors = color4;
quads[0].TopLeft.Colors = color4;
quads[0].TopRight.Colors = color4;
}
protected void UpdateBlendFunc()
{
// it's possible to have an untextured sprite
if (Texture == null || !Texture.HasPremultipliedAlpha)
{
BlendFunc = CCBlendFunc.NonPremultiplied;
IsColorModifiedByOpacity = false;
}
else
{
BlendFunc = CCBlendFunc.AlphaBlend;
IsColorModifiedByOpacity = true;
}
}
#endregion Color managment
#region Updating quads
void UpdateSpriteTextureQuads()
{
quadCommand.RequestUpdateQuads(UpdateSpriteTextureQuadsCallback);
texQuadDirty = false;
}
void UpdateSpriteTextureQuadsCallback(ref CCV3F_C4B_T2F_Quad[] quads)
{
if (!Visible)
{
quads[0].BottomRight.Vertices = quads[0].TopLeft.Vertices
= quads[0].TopRight.Vertices = quads[0].BottomLeft.Vertices = CCVertex3F.Zero;
}
else
{
CCPoint relativeOffset = unflippedOffsetPositionFromCenter;
if (flipX)
{
relativeOffset.X = -relativeOffset.X;
}
if (flipY)
{
relativeOffset.Y = -relativeOffset.Y;
}
CCPoint centerPoint = UntrimmedSizeInPixels.Center + relativeOffset;
CCPoint subRectOrigin;
subRectOrigin.X = centerPoint.X - textureRectInPixels.Size.Width / 2.0f;
subRectOrigin.Y = centerPoint.Y - textureRectInPixels.Size.Height / 2.0f;
CCRect subRectRatio = CCRect.Zero;
if (UntrimmedSizeInPixels.Width > 0 && UntrimmedSizeInPixels.Height > 0)
{
subRectRatio = new CCRect(
subRectOrigin.X / UntrimmedSizeInPixels.Width,
subRectOrigin.Y / UntrimmedSizeInPixels.Height,
textureRectInPixels.Size.Width / UntrimmedSizeInPixels.Width,
textureRectInPixels.Size.Height / UntrimmedSizeInPixels.Height);
}
// Atlas: Vertex
float x1 = subRectRatio.Origin.X * ContentSize.Width;
float y1 = subRectRatio.Origin.Y * ContentSize.Height;
float x2 = x1 + (subRectRatio.Size.Width * ContentSize.Width);
float y2 = y1 + (subRectRatio.Size.Height * ContentSize.Height);
// Don't set z-value: The node's transform will be set to include z offset
quads[0].BottomLeft.Vertices = new CCVertex3F(x1, y1, 0);
quads[0].BottomRight.Vertices = new CCVertex3F(x2, y1, 0);
quads[0].TopLeft.Vertices = new CCVertex3F(x1, y2, 0);
quads[0].TopRight.Vertices = new CCVertex3F(x2, y2, 0);
if (Texture == null)
{
return;
}
float atlasWidth = Texture.PixelsWide;
float atlasHeight = Texture.PixelsHigh;
float left, right, top, bottom;
float offsetW = HalfTexelOffset ? 0.5f / atlasWidth : 0.0f;
float offsetH = HalfTexelOffset ? 0.5f / atlasHeight : 0.0f;
if (IsTextureRectRotated)
{
left = textureRectInPixels.Origin.X / atlasWidth + offsetW;
right = (textureRectInPixels.Origin.X + textureRectInPixels.Size.Height) / atlasWidth - offsetW;
top = textureRectInPixels.Origin.Y / atlasHeight + offsetH;
bottom = (textureRectInPixels.Origin.Y + textureRectInPixels.Size.Width) / atlasHeight - offsetH;
if (flipX)
{
CCMacros.CCSwap(ref top, ref bottom);
}
if (flipY)
{
CCMacros.CCSwap(ref left, ref right);
}
quads[0].BottomLeft.TexCoords.U = left;
quads[0].BottomLeft.TexCoords.V = top;
quads[0].BottomRight.TexCoords.U = left;
quads[0].BottomRight.TexCoords.V = bottom;
quads[0].TopLeft.TexCoords.U = right;
quads[0].TopLeft.TexCoords.V = top;
quads[0].TopRight.TexCoords.U = right;
quads[0].TopRight.TexCoords.V = bottom;
}
else
{
left = textureRectInPixels.Origin.X / atlasWidth + offsetW;
right = (textureRectInPixels.Origin.X + textureRectInPixels.Size.Width) / atlasWidth - offsetW;
top = textureRectInPixels.Origin.Y / atlasHeight + offsetH;
bottom = (textureRectInPixels.Origin.Y + textureRectInPixels.Size.Height) / atlasHeight - offsetH;
if (flipX)
{
CCMacros.CCSwap(ref left, ref right);
}
if (flipY)
{
CCMacros.CCSwap(ref top, ref bottom);
}
quads[0].BottomLeft.TexCoords.U = left;
quads[0].BottomLeft.TexCoords.V = bottom;
quads[0].BottomRight.TexCoords.U = right;
quads[0].BottomRight.TexCoords.V = bottom;
quads[0].TopLeft.TexCoords.U = left;
quads[0].TopLeft.TexCoords.V = top;
quads[0].TopRight.TexCoords.U = right;
quads[0].TopRight.TexCoords.V = top;
}
}
}
public void UpdateLocalTransformedSpriteTextureQuads()
{
if(texQuadDirty)
UpdateSpriteTextureQuads();
quadCommand.RequestUpdateQuads(UpdateLocalTransformedSpriteTextureQuadsCallback);
}
void UpdateLocalTransformedSpriteTextureQuadsCallback(ref CCV3F_C4B_T2F_Quad[] quads)
{
if(AtlasIndex == CCMacros.CCSpriteIndexNotInitialized)
return;
CCV3F_C4B_T2F_Quad transformedQuad = quads[0];
AffineLocalTransform.Transform(ref transformedQuad);
if(TextureAtlas != null && TextureAtlas.TotalQuads > AtlasIndex)
TextureAtlas.UpdateQuad(ref transformedQuad, AtlasIndex);
}
#endregion Updating texture quads
#region Child management
public override void ReorderChild(CCNode child, int zOrder)
{
Debug.Assert(child != null);
Debug.Assert(Children.Contains(child));
if (zOrder == child.ZOrder)
{
return;
}
base.ReorderChild(child, zOrder);
}
#endregion Child management
}
}
| |
#region Usings
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
#endregion
namespace AT.MIN
{
public static class Tools
{
#region Public Methods
#region IsNumericType
/// <summary>
/// Determines whether the specified value is of numeric type.
/// </summary>
/// <param name="o">The object to check.</param>
/// <returns>
/// <c>true</c> if o is a numeric type; otherwise, <c>false</c>.
/// </returns>
public static bool IsNumericType( object o )
{
return ( o is byte ||
o is sbyte ||
o is short ||
o is ushort ||
o is int ||
o is uint ||
o is long ||
o is ulong ||
o is float ||
o is double ||
o is decimal );
}
#endregion
#region IsPositive
/// <summary>
/// Determines whether the specified value is positive.
/// </summary>
/// <param name="Value">The value.</param>
/// <param name="ZeroIsPositive">if set to <c>true</c> treats 0 as positive.</param>
/// <returns>
/// <c>true</c> if the specified value is positive; otherwise, <c>false</c>.
/// </returns>
public static bool IsPositive( object Value, bool ZeroIsPositive )
{
switch ( Type.GetTypeCode( Value.GetType() ) )
{
case TypeCode.SByte:
return ( ZeroIsPositive ? (sbyte)Value >= 0 : (sbyte)Value > 0 );
case TypeCode.Int16:
return ( ZeroIsPositive ? (short)Value >= 0 : (short)Value > 0 );
case TypeCode.Int32:
return ( ZeroIsPositive ? (int)Value >= 0 : (int)Value > 0 );
case TypeCode.Int64:
return ( ZeroIsPositive ? (long)Value >= 0 : (long)Value > 0 );
case TypeCode.Single:
return ( ZeroIsPositive ? (float)Value >= 0 : (float)Value > 0 );
case TypeCode.Double:
return ( ZeroIsPositive ? (double)Value >= 0 : (double)Value > 0 );
case TypeCode.Decimal:
return ( ZeroIsPositive ? (decimal)Value >= 0 : (decimal)Value > 0 );
case TypeCode.Byte:
return ( ZeroIsPositive ? true : (byte)Value > 0 );
case TypeCode.UInt16:
return ( ZeroIsPositive ? true : (ushort)Value > 0 );
case TypeCode.UInt32:
return ( ZeroIsPositive ? true : (uint)Value > 0 );
case TypeCode.UInt64:
return ( ZeroIsPositive ? true : (ulong)Value > 0 );
case TypeCode.Char:
return ( ZeroIsPositive ? true : (char)Value != '\0' );
default:
return false;
}
}
#endregion
#region ToUnsigned
/// <summary>
/// Converts the specified values boxed type to its correpsonding unsigned
/// type.
/// </summary>
/// <param name="Value">The value.</param>
/// <returns>A boxed numeric object whos type is unsigned.</returns>
public static object ToUnsigned( object Value )
{
switch ( Type.GetTypeCode( Value.GetType() ) )
{
case TypeCode.SByte:
return (byte)( (sbyte)Value );
case TypeCode.Int16:
return (ushort)( (short)Value );
case TypeCode.Int32:
return (uint)( (int)Value );
case TypeCode.Int64:
return (ulong)( (long)Value );
case TypeCode.Byte:
return Value;
case TypeCode.UInt16:
return Value;
case TypeCode.UInt32:
return Value;
case TypeCode.UInt64:
return Value;
case TypeCode.Single:
return (UInt32)( (float)Value );
case TypeCode.Double:
return (ulong)( (double)Value );
case TypeCode.Decimal:
return (ulong)( (decimal)Value );
default:
return null;
}
}
#endregion
#region ToInteger
/// <summary>
/// Converts the specified values boxed type to its correpsonding integer
/// type.
/// </summary>
/// <param name="Value">The value.</param>
/// <returns>A boxed numeric object whos type is an integer type.</returns>
public static object ToInteger( object Value, bool Round )
{
switch ( Type.GetTypeCode( Value.GetType() ) )
{
case TypeCode.SByte:
return Value;
case TypeCode.Int16:
return Value;
case TypeCode.Int32:
return Value;
case TypeCode.Int64:
return Value;
case TypeCode.Byte:
return Value;
case TypeCode.UInt16:
return Value;
case TypeCode.UInt32:
return Value;
case TypeCode.UInt64:
return Value;
case TypeCode.Single:
return ( Round ? (int)Math.Round( (float)Value ) : (int)( (float)Value ) );
case TypeCode.Double:
return ( Round ? (long)Math.Round( (double)Value ) : (long)( (double)Value ) );
case TypeCode.Decimal:
return ( Round ? Math.Round( (decimal)Value ) : (decimal)Value );
default:
return null;
}
}
#endregion
#region UnboxToLong
public static long UnboxToLong( object Value, bool Round )
{
switch ( Type.GetTypeCode( Value.GetType() ) )
{
case TypeCode.SByte:
return (long)( (sbyte)Value );
case TypeCode.Int16:
return (long)( (short)Value );
case TypeCode.Int32:
return (long)( (int)Value );
case TypeCode.Int64:
return (long)Value;
case TypeCode.Byte:
return (long)( (byte)Value );
case TypeCode.UInt16:
return (long)( (ushort)Value );
case TypeCode.UInt32:
return (long)( (uint)Value );
case TypeCode.UInt64:
return (long)( (ulong)Value );
case TypeCode.Single:
return ( Round ? (long)Math.Round( (float)Value ) : (long)( (float)Value ) );
case TypeCode.Double:
return ( Round ? (long)Math.Round( (double)Value ) : (long)( (double)Value ) );
case TypeCode.Decimal:
return ( Round ? (long)Math.Round( (decimal)Value ) : (long)( (decimal)Value ) );
default:
return 0;
}
}
#endregion
#region ReplaceMetaChars
/// <summary>
/// Replaces the string representations of meta chars with their corresponding
/// character values.
/// </summary>
/// <param name="input">The input.</param>
/// <returns>A string with all string meta chars are replaced</returns>
public static string ReplaceMetaChars( string input )
{
return Regex.Replace( input, @"(\\)(\d{3}|[^\d])?", new MatchEvaluator( ReplaceMetaCharsMatch ) );
}
private static string ReplaceMetaCharsMatch( Match m )
{
// convert octal quotes (like \040)
if ( m.Groups[2].Length == 3 )
return Convert.ToChar( Convert.ToByte( m.Groups[2].Value, 8 ) ).ToString();
else
{
// convert all other special meta characters
//TODO: \xhhh hex and possible dec !!
switch ( m.Groups[2].Value )
{
case "0": // null
return "\0";
case "a": // alert (beep)
return "\a";
case "b": // BS
return "\b";
case "f": // FF
return "\f";
case "v": // vertical tab
return "\v";
case "r": // CR
return "\r";
case "n": // LF
return "\n";
case "t": // Tab
return "\t";
default:
// if neither an octal quote nor a special meta character
// so just remove the backslash
return m.Groups[2].Value;
}
}
}
#endregion
#region printf
public static void printf( string Format, params object[] Parameters )
{
Console.Write( Tools.sprintf( Format, Parameters ) );
}
#endregion
#region fprintf
public static void fprintf( TextWriter Destination, string Format, params object[] Parameters )
{
Destination.Write( Tools.sprintf( Format, Parameters ) );
}
internal static Regex r = new Regex(@"\%(\d*\$)?([\'\#\-\+ ]*)(\d*)(?:\.(\d+))?([hl])?([dioxXucsfeEgGpn%])");
#endregion
#region sprintf
public static string sprintf( string Format, params object[] Parameters )
{
#region Variables
StringBuilder f = new StringBuilder();
//Regex r = new Regex( @"\%(\d*\$)?([\'\#\-\+ ]*)(\d*)(?:\.(\d+))?([hl])?([dioxXucsfeEgGpn%])" );
//"%[parameter][flags][width][.precision][length]type"
Match m = null;
string w = String.Empty;
int defaultParamIx = 0;
int paramIx;
object o = null;
bool flagLeft2Right = false;
bool flagAlternate = false;
bool flagPositiveSign = false;
bool flagPositiveSpace = false;
bool flagZeroPadding = false;
bool flagGroupThousands = false;
int fieldLength = 0;
int fieldPrecision = 0;
char shortLongIndicator = '\0';
char formatSpecifier = '\0';
char paddingCharacter = ' ';
#endregion
// find all format parameters in format string
f.Append( Format );
m = r.Match( f.ToString() );
while ( m.Success )
{
#region parameter index
paramIx = defaultParamIx;
if ( m.Groups[1] != null && m.Groups[1].Value.Length > 0 )
{
string val = m.Groups[1].Value.Substring( 0, m.Groups[1].Value.Length - 1 );
paramIx = Convert.ToInt32( val ) - 1;
};
#endregion
#region format flags
// extract format flags
flagAlternate = false;
flagLeft2Right = false;
flagPositiveSign = false;
flagPositiveSpace = false;
flagZeroPadding = false;
flagGroupThousands = false;
if ( m.Groups[2] != null && m.Groups[2].Value.Length > 0 )
{
string flags = m.Groups[2].Value;
flagAlternate = ( flags.IndexOf( '#' ) >= 0 );
flagLeft2Right = ( flags.IndexOf( '-' ) >= 0 );
flagPositiveSign = ( flags.IndexOf( '+' ) >= 0 );
flagPositiveSpace = ( flags.IndexOf( ' ' ) >= 0 );
flagGroupThousands = ( flags.IndexOf( '\'' ) >= 0 );
// positive + indicator overrides a
// positive space character
if ( flagPositiveSign && flagPositiveSpace )
flagPositiveSpace = false;
}
#endregion
#region field length
// extract field length and
// pading character
paddingCharacter = ' ';
fieldLength = int.MinValue;
if ( m.Groups[3] != null && m.Groups[3].Value.Length > 0 )
{
fieldLength = Convert.ToInt32( m.Groups[3].Value );
flagZeroPadding = ( m.Groups[3].Value[0] == '0' );
}
#endregion
if ( flagZeroPadding )
paddingCharacter = '0';
// left2right allignment overrides zero padding
if ( flagLeft2Right && flagZeroPadding )
{
flagZeroPadding = false;
paddingCharacter = ' ';
}
#region field precision
// extract field precision
fieldPrecision = int.MinValue;
if ( m.Groups[4] != null && m.Groups[4].Value.Length > 0 )
fieldPrecision = Convert.ToInt32( m.Groups[4].Value );
#endregion
#region short / long indicator
// extract short / long indicator
shortLongIndicator = Char.MinValue;
if ( m.Groups[5] != null && m.Groups[5].Value.Length > 0 )
shortLongIndicator = m.Groups[5].Value[0];
#endregion
#region format specifier
// extract format
formatSpecifier = Char.MinValue;
if ( m.Groups[6] != null && m.Groups[6].Value.Length > 0 )
formatSpecifier = m.Groups[6].Value[0];
#endregion
// default precision is 6 digits if none is specified except
if ( fieldPrecision == int.MinValue &&
formatSpecifier != 's' &&
formatSpecifier != 'c' &&
Char.ToUpper( formatSpecifier ) != 'X' &&
formatSpecifier != 'o' )
fieldPrecision = 6;
#region get next value parameter
// get next value parameter and convert value parameter depending on short / long indicator
if ( Parameters == null || paramIx >= Parameters.Length )
o = null;
else
{
o = Parameters[paramIx];
if ( shortLongIndicator == 'h' )
{
if ( o is int )
o = (short)( (int)o );
else if ( o is long )
o = (short)( (long)o );
else if ( o is uint )
o = (ushort)( (uint)o );
else if ( o is ulong )
o = (ushort)( (ulong)o );
}
else if ( shortLongIndicator == 'l' )
{
if ( o is short )
o = (long)( (short)o );
else if ( o is int )
o = (long)( (int)o );
else if ( o is ushort )
o = (ulong)( (ushort)o );
else if ( o is uint )
o = (ulong)( (uint)o );
}
}
#endregion
// convert value parameters to a string depending on the formatSpecifier
w = String.Empty;
switch ( formatSpecifier )
{
#region % - character
case '%': // % character
w = "%";
break;
#endregion
#region d - integer
case 'd': // integer
w = FormatNumber( ( flagGroupThousands ? "n" : "d" ), flagAlternate,
fieldLength, int.MinValue, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o );
defaultParamIx++;
break;
#endregion
#region i - integer
case 'i': // integer
goto case 'd';
#endregion
#region o - octal integer
case 'o': // octal integer - no leading zero
w = FormatOct( "o", flagAlternate,
fieldLength, int.MinValue, flagLeft2Right,
paddingCharacter, o );
defaultParamIx++;
break;
#endregion
#region x - hex integer
case 'x': // hex integer - no leading zero
w = FormatHex( "x", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
paddingCharacter, o );
defaultParamIx++;
break;
#endregion
#region X - hex integer
case 'X': // same as x but with capital hex characters
w = FormatHex( "X", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
paddingCharacter, o );
defaultParamIx++;
break;
#endregion
#region u - unsigned integer
case 'u': // unsigned integer
w = FormatNumber( ( flagGroupThousands ? "n" : "d" ), flagAlternate,
fieldLength, int.MinValue, flagLeft2Right,
false, false,
paddingCharacter, ToUnsigned( o ) );
defaultParamIx++;
break;
#endregion
#region c - character
case 'c': // character
if ( IsNumericType( o ) )
w = Convert.ToChar( o ).ToString();
else if ( o is char )
w = ( (char)o ).ToString();
else if ( o is string && ( (string)o ).Length > 0 )
w = ( (string)o )[0].ToString();
defaultParamIx++;
break;
#endregion
#region s - string
case 's': // string
//string t = "{0" + ( fieldLength != int.MinValue ? "," + ( flagLeft2Right ? "-" : String.Empty ) + fieldLength.ToString() : String.Empty ) + ":s}";
w = o.ToString();
if ( fieldPrecision >= 0 )
w = w.Substring( 0, fieldPrecision );
if ( fieldLength != int.MinValue )
if ( flagLeft2Right )
w = w.PadRight( fieldLength, paddingCharacter );
else
w = w.PadLeft( fieldLength, paddingCharacter );
defaultParamIx++;
break;
#endregion
#region f - double number
case 'f': // double
w = FormatNumber( ( flagGroupThousands ? "n" : "f" ), flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o );
defaultParamIx++;
break;
#endregion
#region e - exponent number
case 'e': // double / exponent
w = FormatNumber( "e", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o );
defaultParamIx++;
break;
#endregion
#region E - exponent number
case 'E': // double / exponent
w = FormatNumber( "E", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o );
defaultParamIx++;
break;
#endregion
#region g - general number
case 'g': // double / exponent
w = FormatNumber( "g", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o );
defaultParamIx++;
break;
#endregion
#region G - general number
case 'G': // double / exponent
w = FormatNumber( "G", flagAlternate,
fieldLength, fieldPrecision, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, o );
defaultParamIx++;
break;
#endregion
#region p - pointer
case 'p': // pointer
if ( o is IntPtr )
#if XBOX || SILVERLIGHT
w = ( (IntPtr)o ).ToString();
#else
w = "0x" + ( (IntPtr)o ).ToString( "x" );
#endif
defaultParamIx++;
break;
#endregion
#region n - number of processed chars so far
case 'n': // number of characters so far
w = FormatNumber( "d", flagAlternate,
fieldLength, int.MinValue, flagLeft2Right,
flagPositiveSign, flagPositiveSpace,
paddingCharacter, m.Index );
break;
#endregion
default:
w = String.Empty;
defaultParamIx++;
break;
}
// replace format parameter with parameter value
// and start searching for the next format parameter
// AFTER the position of the current inserted value
// to prohibit recursive matches if the value also
// includes a format specifier
f.Remove( m.Index, m.Length );
f.Insert( m.Index, w );
m = r.Match( f.ToString(), m.Index + w.Length );
}
return f.ToString();
}
#endregion
#endregion
#region Private Methods
#region FormatOCT
private static string FormatOct( string NativeFormat, bool Alternate,
int FieldLength, int FieldPrecision,
bool Left2Right,
char Padding, object Value )
{
string w = String.Empty;
string lengthFormat = "{0" + ( FieldLength != int.MinValue ?
"," + ( Left2Right ?
"-" :
String.Empty ) + FieldLength.ToString() :
String.Empty ) + "}";
if ( IsNumericType( Value ) )
{
w = Convert.ToString( UnboxToLong( Value, true ), 8 );
if ( Left2Right || Padding == ' ' )
{
if ( Alternate && w != "0" )
w = "0" + w;
w = String.Format( lengthFormat, w );
}
else
{
if ( FieldLength != int.MinValue )
w = w.PadLeft( FieldLength - ( Alternate && w != "0" ? 1 : 0 ), Padding );
if ( Alternate && w != "0" )
w = "0" + w;
}
}
return w;
}
#endregion
#region FormatHEX
private static string FormatHex( string NativeFormat, bool Alternate,
int FieldLength, int FieldPrecision,
bool Left2Right,
char Padding, object Value )
{
string w = String.Empty;
string lengthFormat = "{0" + ( FieldLength != int.MinValue ?
"," + ( Left2Right ?
"-" :
String.Empty ) + FieldLength.ToString() :
String.Empty ) + "}";
string numberFormat = "{0:" + NativeFormat + ( FieldPrecision != int.MinValue ?
FieldPrecision.ToString() :
String.Empty ) + "}";
if ( IsNumericType( Value ) )
{
w = String.Format( numberFormat, Value );
if ( Left2Right || Padding == ' ' )
{
if ( Alternate )
w = ( NativeFormat == "x" ? "0x" : "0X" ) + w;
w = String.Format( lengthFormat, w );
}
else
{
if ( FieldLength != int.MinValue )
w = w.PadLeft( FieldLength - ( Alternate ? 2 : 0 ), Padding );
if ( Alternate )
w = ( NativeFormat == "x" ? "0x" : "0X" ) + w;
}
}
return w;
}
#endregion
#region FormatNumber
private static string FormatNumber( string NativeFormat, bool Alternate,
int FieldLength, int FieldPrecision,
bool Left2Right,
bool PositiveSign, bool PositiveSpace,
char Padding, object Value )
{
string w = String.Empty;
string lengthFormat = "{0" + ( FieldLength != int.MinValue ?
"," + ( Left2Right ?
"-" :
String.Empty ) + FieldLength.ToString() :
String.Empty ) + "}";
string numberFormat = "{0:" + NativeFormat + ( FieldPrecision != int.MinValue ?
FieldPrecision.ToString() :
"0" ) + "}";
if ( IsNumericType( Value ) )
{
w = String.Format(CultureInfo.InvariantCulture, numberFormat, Value );
if ( Left2Right || Padding == ' ' )
{
if ( IsPositive( Value, true ) )
w = ( PositiveSign ?
"+" : ( PositiveSpace ? " " : String.Empty ) ) + w;
w = String.Format( lengthFormat, w );
}
else
{
if ( w.StartsWith( "-" ) )
w = w.Substring( 1 );
if ( FieldLength != int.MinValue )
w = w.PadLeft( FieldLength - 1, Padding );
if ( IsPositive( Value, true ) )
w = ( PositiveSign ?
"+" : ( PositiveSpace ?
" " : ( FieldLength != int.MinValue ?
Padding.ToString() : String.Empty ) ) ) + w;
else
w = "-" + w;
}
}
return w;
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace NuGetPe
{
public static class PathResolver
{
/// <summary>
/// Returns a collection of files from the source that matches the wildcard.
/// </summary>
/// <param name="source">The collection of files to match.</param>
/// <param name="getPath">Function that returns the path to filter a package file </param>
/// <param name="wildcards">The wildcard to apply to match the path with.</param>
/// <returns></returns>
public static IEnumerable<T> GetMatches<T>(IEnumerable<T> source, Func<T, string> getPath,
IEnumerable<string> wildcards) where T : IPackageFile
{
IEnumerable<Regex> filters = wildcards.Select(WildcardToRegex);
return source.Where(item =>
{
string path = getPath(item);
return filters.Any(f => f.IsMatch(path));
});
}
/// <summary>
/// Removes files from the source that match any wildcard.
/// </summary>
public static void FilterPackageFiles<T>(ICollection<T> source, Func<T, string> getPath,
IEnumerable<string> wildcards) where T : IPackageFile
{
var matchedFiles = new HashSet<T>(GetMatches(source, getPath, wildcards));
source.RemoveAll(matchedFiles.Contains);
}
public static string NormalizeWildcard(string basePath, string wildcard)
{
basePath = NormalizeBasePath(basePath, ref wildcard);
return Path.Combine(basePath, wildcard);
}
private static Regex WildcardToRegex(string wildcard)
{
return new Regex('^'
+ Regex.Escape(wildcard)
.Replace(@"\*\*\\", ".*")
//For recursive wildcards \**\, include the current directory.
.Replace(@"\*\*", ".*")
// For recursive wildcards that don't end in a slash e.g. **.txt would be treated as a .txt file at any depth
.Replace(@"\*", @"[^\\]*(\\)?")
// For non recursive searches, limit it any character that is not a directory separator
.Replace(@"\?", ".") // ? translates to a single any character
+ '$', RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
}
internal static IEnumerable<PackageFileBase> ResolveSearchPattern(string basePath, string searchPath, string targetPath)
{
if (!searchPath.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase))
{
// If we aren't dealing with network paths, trim the leading slash.
searchPath = searchPath.TrimStart(Path.DirectorySeparatorChar);
}
bool searchDirectory = false;
// If the searchPath ends with \ or /, we treat searchPath as a directory,
// and will include everything under it, recursively
if (IsDirectoryPath(searchPath))
{
searchPath = searchPath + "**" + Path.DirectorySeparatorChar + "*";
searchDirectory = true;
}
basePath = NormalizeBasePath(basePath, ref searchPath);
string basePathToEnumerate = GetPathToEnumerateFrom(basePath, searchPath);
// Append the basePath to searchPattern and get the search regex. We need to do this because the search regex is matched from line start.
Regex searchRegex = WildcardToRegex(Path.Combine(basePath, searchPath));
// This is a hack to prevent enumerating over the entire directory tree if the only wildcard characters are the ones in the file name.
// If the path portion of the search path does not contain any wildcard characters only iterate over the TopDirectory.
SearchOption searchOption = SearchOption.AllDirectories;
// (a) Path is not recursive search
bool isRecursiveSearch = searchPath.IndexOf("**", StringComparison.OrdinalIgnoreCase) != -1;
// (b) Path does not have any wildcards.
bool isWildcardPath = Path.GetDirectoryName(searchPath).Contains('*');
if (!isRecursiveSearch && !isWildcardPath)
{
searchOption = SearchOption.TopDirectoryOnly;
}
// Starting from the base path, enumerate over all files and match it using the wildcard expression provided by the user.
IEnumerable<string> files = Directory.EnumerateFiles(basePathToEnumerate, "*.*", searchOption);
IEnumerable<PackageFileBase> matchedFiles =
from file in files
where searchRegex.IsMatch(file)
let targetPathInPackage = ResolvePackagePath(basePathToEnumerate, searchPath, file, targetPath)
select new PhysicalPackageFile(isTempFile: false, originalPath: file, targetPath: targetPathInPackage);
if (searchDirectory && IsEmptyDirectory(basePathToEnumerate))
{
matchedFiles = matchedFiles.Concat(new[] { new EmptyFolderFile(targetPath ?? String.Empty) });
}
return matchedFiles;
}
internal static string GetPathToEnumerateFrom(string basePath, string searchPath)
{
string basePathToEnumerate;
int wildcardIndex = searchPath.IndexOf('*');
if (wildcardIndex == -1)
{
// For paths without wildcard, we could either have base relative paths (such as lib\foo.dll) or paths outside the base path
// (such as basePath: C:\packages and searchPath: D:\packages\foo.dll)
// In this case, Path.Combine would pick up the right root to enumerate from.
string searchRoot = Path.GetDirectoryName(searchPath);
basePathToEnumerate = Path.Combine(basePath, searchRoot);
}
else
{
// If not, find the first directory separator and use the path to the left of it as the base path to enumerate from.
int directorySeparatoryIndex = searchPath.LastIndexOf(Path.DirectorySeparatorChar, wildcardIndex);
if (directorySeparatoryIndex == -1)
{
// We're looking at a path like "NuGet*.dll", NuGet*\bin\release\*.dll
// In this case, the basePath would continue to be the path to begin enumeration from.
basePathToEnumerate = basePath;
}
else
{
string nonWildcardPortion = searchPath.Substring(0, directorySeparatoryIndex);
basePathToEnumerate = Path.Combine(basePath, nonWildcardPortion);
}
}
return basePathToEnumerate;
}
/// <summary>
/// Determins the path of the file inside a package.
/// For recursive wildcard paths, we preserve the path portion beginning with the wildcard.
/// For non-recursive wildcard paths, we use the file name from the actual file path on disk.
/// </summary>
internal static string ResolvePackagePath(string searchDirectory, string searchPattern, string fullPath,
string targetPath)
{
string packagePath;
bool isDirectorySearch = IsDirectoryPath(searchPattern);
bool isWildcardSearch = IsWildcardSearch(searchPattern);
bool isRecursiveWildcardSearch = isWildcardSearch &&
searchPattern.IndexOf("**", StringComparison.OrdinalIgnoreCase) != -1;
if ((isRecursiveWildcardSearch || isDirectorySearch) && fullPath.StartsWith(searchDirectory, StringComparison.OrdinalIgnoreCase))
{
// The search pattern is recursive. Preserve the non-wildcard portion of the path.
// e.g. Search: X:\foo\**\*.cs results in SearchDirectory: X:\foo and a file path of X:\foo\bar\biz\boz.cs
// Truncating X:\foo\ would result in the package path.
packagePath = fullPath.Substring(searchDirectory.Length).TrimStart(Path.DirectorySeparatorChar);
}
else if (!isWildcardSearch &&
Path.GetExtension(searchPattern).Equals(Path.GetExtension(targetPath),
StringComparison.OrdinalIgnoreCase))
{
// If the search does not contain wild cards, and the target path shares the same extension, copy it
// e.g. <file src="ie\css\style.css" target="Content\css\ie.css" /> --> Content\css\ie.css
return targetPath;
}
else
{
packagePath = Path.GetFileName(fullPath);
}
return Path.Combine(targetPath ?? String.Empty, packagePath);
}
internal static string NormalizeBasePath(string basePath, ref string searchPath)
{
const string relativePath = @"..\";
// If no base path is provided, use the current directory.
basePath = String.IsNullOrEmpty(basePath) ? @".\" : basePath;
// If the search path is relative, transfer the ..\ portion to the base path.
// This needs to be done because the base path determines the root for our enumeration.
while (searchPath.StartsWith(relativePath, StringComparison.OrdinalIgnoreCase))
{
basePath = Path.Combine(basePath, relativePath);
searchPath = searchPath.Substring(relativePath.Length);
}
return Path.GetFullPath(basePath);
}
/// <summary>
/// Returns true if the path contains any wildcard characters.
/// </summary>
internal static bool IsWildcardSearch(string filter)
{
return filter.IndexOf('*') != -1;
}
internal static bool IsDirectoryPath(string path)
{
return path != null && path.Length > 1 && path[path.Length - 1] == Path.DirectorySeparatorChar;
}
private static bool IsEmptyDirectory(string directory)
{
return !Directory.EnumerateFileSystemEntries(directory).Any();
}
}
}
| |
//! \file ArcABM.cs
//! \date Tue Aug 04 23:40:47 2015
//! \brief LiLiM/Le.Chocolat multi-frame compressed bitmaps.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using GameRes.Utility;
namespace GameRes.Formats.Lilim
{
internal class AbmArchive : ArcFile
{
public readonly AbmImageData FrameInfo;
public AbmArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, AbmImageData info)
: base (arc, impl, dir)
{
FrameInfo = info;
}
}
internal class AbmImageData : ImageMetaData
{
public int Mode;
public uint BaseOffset;
public uint FrameOffset;
public AbmImageData Clone ()
{
return this.MemberwiseClone() as AbmImageData;
}
}
internal class AbmEntry : PackedEntry
{
public int Index;
}
[Export(typeof(ArchiveFormat))]
public class AbmOpener : ArchiveFormat
{
public override string Tag { get { return "ABM"; } }
public override string Description { get { return "LiLiM/Le.Chocolat multi-frame bitmap"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanCreate { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
if ('B' != file.View.ReadByte (0) || 'M' != file.View.ReadByte (1))
return null;
int type = file.View.ReadSByte (0x1C);
if (type != 1 && type != 2)
return null;
int count = file.View.ReadInt16 (0x3A);
if (!IsSaneCount (count))
return null;
uint width = file.View.ReadUInt32 (0x12);
uint height = file.View.ReadUInt32 (0x16);
int pixel_size = 2 == type ? 4 : 3;
uint bitmap_data_size = width*height*(uint)pixel_size;
var dir = new List<Entry> (count);
long next_offset = file.View.ReadUInt32 (0x42);
uint current_offset = 0x46;
string base_name = Path.GetFileNameWithoutExtension (file.Name);
for (int i = 0; i < count; ++i)
{
var entry = new AbmEntry {
Name = string.Format ("{0}#{1:D4}.tga", base_name, i),
Type = "image",
Offset = next_offset,
Index = i,
};
if (i + 1 != count)
{
next_offset = file.View.ReadUInt32 (current_offset);
current_offset += 4;
}
else
next_offset = file.MaxOffset;
if (next_offset <= entry.Offset)
return null;
entry.Size = (uint)(next_offset - entry.Offset);
if (!entry.CheckPlacement (file.MaxOffset))
return null;
entry.UnpackedSize = 0x12 + bitmap_data_size;
dir.Add (entry);
}
var image_info = new AbmImageData
{
Width = (uint)width,
Height = (uint)height,
BPP = pixel_size * 8,
Mode = type,
BaseOffset = (uint)dir[0].Offset,
};
return new AbmArchive (file, this, dir, image_info);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var abm = arc as AbmArchive;
var frame = entry as AbmEntry;
if (null == abm || null == frame)
return arc.File.CreateStream (entry.Offset, entry.Size);
var frame_info = abm.FrameInfo;
if (frame.Index != 0)
{
frame_info = frame_info.Clone();
frame_info.FrameOffset = (uint)frame.Offset;
}
using (var input = arc.File.CreateStream (0, (uint)arc.File.MaxOffset))
using (var reader = new AbmReader (input, frame_info))
{
// emulate TGA image
var header = new byte[0x12];
header[2] = 2;
LittleEndian.Pack ((ushort)frame_info.Width, header, 0xC);
LittleEndian.Pack ((ushort)frame_info.Height, header, 0xE);
header[0x10] = (byte)reader.BPP;
header[0x11] = 0x20;
var pixels = reader.Unpack();
return new PrefixStream (header, new MemoryStream (pixels));
}
}
}
internal sealed class AbmReader : IDisposable
{
BinaryReader m_input;
byte[] m_output;
AbmImageData m_info;
int m_bpp;
public byte[] Data { get { return m_output; } }
public int BPP { get { return m_bpp; } }
public AbmReader (Stream file, AbmImageData info)
{
m_info = info;
if (2 == m_info.Mode)
{
m_bpp = 32;
file.Position = m_info.BaseOffset;
using (var base_frame = new ArcView.Reader (file))
m_output = UnpackV2 (base_frame);
}
else if (1 == m_info.Mode || 32 == m_info.Mode || 24 == m_info.Mode)
{
if (1 == m_info.Mode)
m_bpp = 24;
else
m_bpp = m_info.Mode;
int total_length = (int)(m_info.Width * m_info.Height * m_bpp / 8);
m_output = new byte[total_length];
file.Position = m_info.BaseOffset;
if (1 == m_info.Mode)
{
if (total_length != file.Read (m_output, 0, (total_length)))
throw new EndOfStreamException();
}
else
{
using (var base_frame = new ArcView.Reader (file))
{
if (24 == m_bpp)
UnpackStream24 (base_frame, m_output, total_length);
else
UnpackStream32 (base_frame, m_output, total_length);
}
}
}
else
throw new NotImplementedException();
if (0 != m_info.FrameOffset)
{
m_input = new ArcView.Reader (file);
}
}
int frame_x;
int frame_y;
int frame_w;
int frame_h;
public byte[] Unpack ()
{
if (null == m_input)
return m_output;
m_input.BaseStream.Position = m_info.FrameOffset;
if (1 == m_info.Mode)
return UnpackStream24 (m_input, m_output, m_output.Length);
if (2 == m_info.Mode)
{
var frame = UnpackV2 (m_input);
CopyFrame (frame);
return m_output;
}
throw new NotImplementedException();
}
byte[] UnpackV2 (BinaryReader input)
{
frame_x = input.ReadInt32();
frame_y = input.ReadInt32();
frame_w = input.ReadInt32();
frame_h = input.ReadInt32();
if (frame_x < 0 || frame_y < 0 || frame_w <= 0 || frame_h <= 0)
throw new InvalidFormatException();
int total_length = frame_w * frame_h * m_bpp / 8;
byte[] output = new byte[total_length];
input.ReadByte(); // position number
return UnpackStream32 (input, output, total_length);
}
byte[] UnpackStream24 (BinaryReader input, byte[] output, int total_length)
{
int dst = 0;
while (dst < total_length)
{
int v = input.ReadByte();
if (0 == v)
{
int count = input.ReadByte();
if (0 == count)
continue;
dst += count;
}
else if (0xff == v)
{
int count = input.ReadByte();
if (0 == count)
continue;
count = Math.Min (count, total_length-dst);
input.Read (output, dst, count);
dst += count;
}
else
{
output[dst++] = input.ReadByte();
}
}
return output;
}
byte[] UnpackStream32 (BinaryReader input, byte[] output, int total_length)
{
int dst = 0;
int component = 0;
while (dst < total_length)
{
byte v = input.ReadByte();
if (0 == v)
{
int count = input.ReadByte();
if (0 == count)
continue;
for (int i = 0; i < count; ++i)
{
++dst;
if (++component == 3)
{
++dst;
component = 0;
}
}
}
else if (0xff == v)
{
int count = input.ReadByte();
if (0 == count)
continue;
for (int i = 0; i < count && dst < total_length; ++i)
{
output[dst++] = input.ReadByte();
if (++component == 3)
{
output[dst++] = 0xff;
component = 0;
}
}
}
else
{
output[dst++] = input.ReadByte();
if (++component == 3)
{
output[dst++] = v;
component = 0;
}
}
}
return output;
}
void CopyFrame (byte[] frame)
{
if (frame_x >= m_info.Width || frame_y >= m_info.Height)
return;
int pixel_size = m_bpp / 8;
int line_size = Math.Min (frame_w, (int)m_info.Width-frame_x) * pixel_size;
int left = frame_x * pixel_size;
int bottom = Math.Min (frame_y+frame_h, (int)m_info.Height);
int stride = (int)m_info.Width * pixel_size;
int src = 0;
for (int y = frame_y; y < bottom; ++y)
{
int dst = stride * y + left;
Buffer.BlockCopy (frame, src, m_output, dst, line_size);
src += frame_w * pixel_size;
}
}
#region IDisposable Members
bool m_disposed = false;
public void Dispose ()
{
if (!m_disposed)
{
if (m_input != null)
m_input.Dispose();
m_disposed = true;
GC.SuppressFinalize (this);
}
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using IndexFileNameFilter = Lucene.Net.Index.IndexFileNameFilter;
// Used only for WRITE_LOCK_NAME in deprecated create=true case:
using IndexWriter = Lucene.Net.Index.IndexWriter;
namespace Lucene.Net.Store
{
/// <summary> Straightforward implementation of {@link Directory} as a directory of files.
/// Locking implementation is by default the {@link SimpleFSLockFactory}, but
/// can be changed either by passing in a {@link LockFactory} instance to
/// <code>getDirectory</code>, or specifying the LockFactory class by setting
/// <code>Lucene.Net.Store.FSDirectoryLockFactoryClass</code> Java system
/// property, or by calling {@link #setLockFactory} after creating
/// the Directory.
/// <p>Directories are cached, so that, for a given canonical
/// path, the same FSDirectory instance will always be
/// returned by <code>getDirectory</code>. This permits
/// synchronization on directories.</p>
///
/// </summary>
/// <seealso cref="Directory">
/// </seealso>
public class FSDirectory : Directory
{
/// <summary>This cache of directories ensures that there is a unique Directory
/// instance per path, so that synchronization on the Directory can be used to
/// synchronize access between readers and writers. We use
/// refcounts to ensure when the last use of an FSDirectory
/// instance for a given canonical path is closed, we remove the
/// instance from the cache. See LUCENE-776
/// for some relevant discussion.
/// </summary>
private static readonly System.Collections.Hashtable DIRECTORIES = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
private static bool disableLocks = false;
// TODO: should this move up to the Directory base class? Also: should we
// make a per-instance (in addition to the static "default") version?
/// <summary> Set whether Lucene's use of lock files is disabled. By default,
/// lock files are enabled. They should only be disabled if the index
/// is on a read-only medium like a CD-ROM.
/// </summary>
public static void SetDisableLocks(bool doDisableLocks)
{
FSDirectory.disableLocks = doDisableLocks;
}
/// <summary> Returns whether Lucene's use of lock files is disabled.</summary>
/// <returns> true if locks are disabled, false if locks are enabled.
/// </returns>
public static bool GetDisableLocks()
{
return FSDirectory.disableLocks;
}
/// <summary> Directory specified by <code>Lucene.Net.lockDir</code>
/// or <code>java.io.tmpdir</code> system property.
/// </summary>
/// <deprecated> As of 2.1, <code>LOCK_DIR</code> is unused
/// because the write.lock is now stored by default in the
/// index directory. If you really want to store locks
/// elsewhere you can create your own {@link
/// SimpleFSLockFactory} (or {@link NativeFSLockFactory},
/// etc.) passing in your preferred lock directory. Then,
/// pass this <code>LockFactory</code> instance to one of
/// the <code>getDirectory</code> methods that take a
/// <code>lockFactory</code> (for example, {@link #GetDirectory(String, LockFactory)}).
/// </deprecated>
//Deprecated. As of 2.1, LOCK_DIR is unused because the write.lock is now stored by default in the index directory.
//If you really want to store locks elsewhere you can create your own SimpleFSLockFactory (or NativeFSLockFactory, etc.) passing in your preferred lock directory.
//Then, pass this LockFactory instance to one of the getDirectory methods that take a lockFactory (for example, getDirectory(String, LockFactory)).
//public static readonly System.String LOCK_DIR = SupportClass.AppSettings.Get("Lucene.Net.lockDir", System.IO.Path.GetTempPath());
/// <summary>The default class which implements filesystem-based directories. </summary>
private static System.Type IMPL;
private static System.Security.Cryptography.HashAlgorithm DIGESTER;
/// <summary>A buffer optionally used in renameTo method </summary>
private byte[] buffer = null;
/// <summary>Returns the directory instance for the named location.</summary>
/// <param name="path">the path to the directory.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
public static FSDirectory GetDirectory(System.String path)
{
return GetDirectory(new System.IO.FileInfo(path), null);
}
/// <summary>Returns the directory instance for the named location.</summary>
/// <param name="path">the path to the directory.
/// </param>
/// <param name="lockFactory">instance of {@link LockFactory} providing the
/// locking implementation.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
public static FSDirectory GetDirectory(System.String path, LockFactory lockFactory)
{
return GetDirectory(new System.IO.FileInfo(path), lockFactory);
}
/// <summary>Returns the directory instance for the named location.</summary>
/// <param name="file">the path to the directory.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
public static FSDirectory GetDirectory(System.IO.FileInfo file)
{
return GetDirectory(file, null);
}
/// <summary>Returns the directory instance for the named location.</summary>
/// <param name="file">the path to the directory.
/// </param>
/// <param name="lockFactory">instance of {@link LockFactory} providing the
/// locking implementation.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
public static FSDirectory GetDirectory(System.IO.FileInfo file, LockFactory lockFactory)
{
file = new System.IO.FileInfo(file.FullName);
bool tmpBool;
if (System.IO.File.Exists(file.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(file.FullName);
if (tmpBool && !System.IO.Directory.Exists(file.FullName))
throw new System.IO.IOException(file + " not a directory");
bool tmpBool2;
if (System.IO.File.Exists(file.FullName))
tmpBool2 = true;
else
tmpBool2 = System.IO.Directory.Exists(file.FullName);
if (!tmpBool2)
{
try
{
System.IO.Directory.CreateDirectory(file.FullName);
}
catch
{
throw new System.IO.IOException("Cannot create directory: " + file);
}
}
FSDirectory dir;
lock (DIRECTORIES.SyncRoot)
{
dir = (FSDirectory) DIRECTORIES[file.FullName];
if (dir == null)
{
try
{
dir = (FSDirectory) System.Activator.CreateInstance(IMPL);
}
catch (System.Exception e)
{
throw new System.SystemException("cannot load FSDirectory class: " + e.ToString(), e);
}
dir.Init(file, lockFactory);
DIRECTORIES[file.FullName] = dir;
}
else
{
// Catch the case where a Directory is pulled from the cache, but has a
// different LockFactory instance.
if (lockFactory != null && lockFactory != dir.GetLockFactory())
{
throw new System.IO.IOException("Directory was previously created with a different LockFactory instance; please pass null as the lockFactory instance and use setLockFactory to change it");
}
}
}
lock (dir)
{
dir.refCount++;
}
return dir;
}
/// <summary>Returns the directory instance for the named location.
///
/// </summary>
/// <deprecated> Use IndexWriter's create flag, instead, to
/// create a new index.
///
/// </deprecated>
/// <param name="path">the path to the directory.
/// </param>
/// <param name="create">if true, create, or erase any existing contents.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
public static FSDirectory GetDirectory(System.String path, bool create)
{
return GetDirectory(new System.IO.FileInfo(path), create);
}
/// <summary>Returns the directory instance for the named location.
///
/// </summary>
/// <deprecated> Use IndexWriter's create flag, instead, to
/// create a new index.
///
/// </deprecated>
/// <param name="file">the path to the directory.
/// </param>
/// <param name="create">if true, create, or erase any existing contents.
/// </param>
/// <returns> the FSDirectory for the named file.
/// </returns>
public static FSDirectory GetDirectory(System.IO.FileInfo file, bool create)
{
FSDirectory dir = GetDirectory(file, null);
// This is now deprecated (creation should only be done
// by IndexWriter):
if (create)
{
dir.Create();
}
return dir;
}
private void Create()
{
bool tmpBool;
if (System.IO.File.Exists(directory.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(directory.FullName);
if (tmpBool)
{
System.String[] files = SupportClass.FileSupport.GetLuceneIndexFiles(directory.FullName, IndexFileNameFilter.GetFilter());
if (files == null)
throw new System.IO.IOException("cannot read directory " + directory.FullName + ": list() returned null");
for (int i = 0; i < files.Length; i++)
{
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, files[i]));
bool tmpBool2;
if (System.IO.File.Exists(file.FullName))
{
System.IO.File.Delete(file.FullName);
tmpBool2 = true;
}
else if (System.IO.Directory.Exists(file.FullName))
{
System.IO.Directory.Delete(file.FullName);
tmpBool2 = true;
}
else
tmpBool2 = false;
if (!tmpBool2)
throw new System.IO.IOException("Cannot delete " + file);
}
}
lockFactory.ClearLock(IndexWriter.WRITE_LOCK_NAME);
}
private System.IO.FileInfo directory = null;
private int refCount;
public FSDirectory()
{
}
// permit subclassing
private void Init(System.IO.FileInfo path, LockFactory lockFactory)
{
// Set up lockFactory with cascaded defaults: if an instance was passed in,
// use that; else if locks are disabled, use NoLockFactory; else if the
// system property Lucene.Net.Store.FSDirectoryLockFactoryClass is set,
// instantiate that; else, use SimpleFSLockFactory:
directory = path;
bool doClearLockID = false;
if (lockFactory == null)
{
if (disableLocks)
{
// Locks are disabled:
lockFactory = NoLockFactory.GetNoLockFactory();
}
else
{
System.String lockClassName = SupportClass.AppSettings.Get("Lucene.Net.Store.FSDirectoryLockFactoryClass", "");
if (lockClassName != null && !lockClassName.Equals(""))
{
System.Type c;
try
{
c = System.Type.GetType(lockClassName);
}
catch (System.Exception)
{
throw new System.IO.IOException("unable to find LockClass " + lockClassName);
}
try
{
lockFactory = (LockFactory) System.Activator.CreateInstance(c, true);
}
catch (System.UnauthorizedAccessException)
{
throw new System.IO.IOException("IllegalAccessException when instantiating LockClass " + lockClassName);
}
catch (System.InvalidCastException)
{
throw new System.IO.IOException("unable to cast LockClass " + lockClassName + " instance to a LockFactory");
}
catch (System.Exception ex)
{
throw new System.IO.IOException("InstantiationException when instantiating LockClass " + lockClassName + "\nDetails:" + ex.Message);
}
if (lockFactory is NativeFSLockFactory)
{
((NativeFSLockFactory) lockFactory).SetLockDir(path);
}
else if (lockFactory is SimpleFSLockFactory)
{
((SimpleFSLockFactory) lockFactory).SetLockDir(path);
}
}
else
{
// Our default lock is SimpleFSLockFactory;
// default lockDir is our index directory:
lockFactory = new SimpleFSLockFactory(path);
doClearLockID = true;
}
}
}
SetLockFactory(lockFactory);
if (doClearLockID)
{
// Clear the prefix because write.lock will be
// stored in our directory:
lockFactory.SetLockPrefix(null);
}
}
/// <summary>Returns an array of strings, one for each Lucene index file in the directory. </summary>
public override System.String[] List()
{
EnsureOpen();
return SupportClass.FileSupport.GetLuceneIndexFiles(directory.FullName, IndexFileNameFilter.GetFilter());
}
/// <summary>Returns true iff a file with the given name exists. </summary>
public override bool FileExists(System.String name)
{
EnsureOpen();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
bool tmpBool;
if (System.IO.File.Exists(file.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(file.FullName);
return tmpBool;
}
/// <summary>Returns the time the named file was last modified. </summary>
public override long FileModified(System.String name)
{
EnsureOpen();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
return (file.LastWriteTime.Ticks);
}
/// <summary>Returns the time the named file was last modified. </summary>
public static long FileModified(System.IO.FileInfo directory, System.String name)
{
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
return (file.LastWriteTime.Ticks);
}
/// <summary>Set the modified time of an existing file to now. </summary>
public override void TouchFile(System.String name)
{
EnsureOpen();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
file.LastWriteTime = System.DateTime.Now;
}
/// <summary>Returns the length in bytes of a file in the directory. </summary>
public override long FileLength(System.String name)
{
EnsureOpen();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
return file.Exists ? file.Length : 0;
}
/// <summary>Removes an existing file in the directory. </summary>
public override void DeleteFile(System.String name)
{
EnsureOpen();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
bool tmpBool;
if (System.IO.File.Exists(file.FullName))
{
try
{
System.IO.File.Delete(file.FullName);
}
catch (System.UnauthorizedAccessException e)
{
throw new System.IO.IOException(e.Message, e);
}
tmpBool = true;
}
else if (System.IO.Directory.Exists(file.FullName))
{
System.IO.Directory.Delete(file.FullName);
tmpBool = true;
}
else
tmpBool = false;
if (!tmpBool)
throw new System.IO.IOException("Cannot delete " + file);
}
/// <summary>Renames an existing file in the directory.
/// Warning: This is not atomic.
/// </summary>
/// <deprecated>
/// </deprecated>
public override void RenameFile(System.String from, System.String to)
{
lock (this)
{
EnsureOpen();
System.IO.FileInfo old = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, from));
System.IO.FileInfo nu = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, to));
/* This is not atomic. If the program crashes between the call to
delete() and the call to renameTo() then we're screwed, but I've
been unable to figure out how else to do this... */
bool tmpBool;
if (System.IO.File.Exists(nu.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(nu.FullName);
if (tmpBool)
{
bool tmpBool2;
if (System.IO.File.Exists(nu.FullName))
{
System.IO.File.Delete(nu.FullName);
tmpBool2 = true;
}
else if (System.IO.Directory.Exists(nu.FullName))
{
System.IO.Directory.Delete(nu.FullName);
tmpBool2 = true;
}
else
tmpBool2 = false;
if (!tmpBool2)
throw new System.IO.IOException("Cannot delete " + nu);
}
// Rename the old file to the new one. Unfortunately, the renameTo()
// method does not work reliably under some JVMs. Therefore, if the
// rename fails, we manually rename by copying the old file to the new one
try
{
old.MoveTo(nu.FullName);
}
catch
{
System.IO.Stream in_Renamed = null;
System.IO.Stream out_Renamed = null;
try
{
in_Renamed = new System.IO.FileStream(old.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
out_Renamed = new System.IO.FileStream(nu.FullName, System.IO.FileMode.Create);
// see if the buffer needs to be initialized. Initialization is
// only done on-demand since many VM's will never run into the renameTo
// bug and hence shouldn't waste 1K of mem for no reason.
if (buffer == null)
{
buffer = new byte[1024];
}
int len;
while ((len = in_Renamed.Read(buffer, 0, buffer.Length)) >= 0)
{
out_Renamed.Write(buffer, 0, len);
}
// delete the old file.
bool tmpBool3;
if (System.IO.File.Exists(old.FullName))
{
System.IO.File.Delete(old.FullName);
tmpBool3 = true;
}
else if (System.IO.Directory.Exists(old.FullName))
{
System.IO.Directory.Delete(old.FullName);
tmpBool3 = true;
}
else
tmpBool3 = false;
bool generatedAux = tmpBool3;
}
catch (System.IO.IOException ioe)
{
System.IO.IOException newExc = new System.IO.IOException("Cannot rename " + old + " to " + nu, ioe);
throw newExc;
}
finally
{
try
{
if (in_Renamed != null)
{
try
{
in_Renamed.Close();
}
catch (System.IO.IOException e)
{
throw new System.SystemException("Cannot close input stream: " + e.ToString(), e);
}
}
}
finally
{
if (out_Renamed != null)
{
try
{
out_Renamed.Close();
}
catch (System.IO.IOException e)
{
throw new System.SystemException("Cannot close output stream: " + e.ToString(), e);
}
}
}
}
}
}
}
/// <summary>Creates a new, empty file in the directory with the given name.
/// Returns a stream writing this file.
/// </summary>
public override IndexOutput CreateOutput(System.String name)
{
EnsureOpen();
System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
bool tmpBool;
if (System.IO.File.Exists(file.FullName))
tmpBool = true;
else
tmpBool = System.IO.Directory.Exists(file.FullName);
bool tmpBool2;
if (System.IO.File.Exists(file.FullName))
{
System.IO.File.Delete(file.FullName);
tmpBool2 = true;
}
else if (System.IO.Directory.Exists(file.FullName))
{
System.IO.Directory.Delete(file.FullName);
tmpBool2 = true;
}
else
tmpBool2 = false;
if (tmpBool && !tmpBool2)
// delete existing, if any
throw new System.IO.IOException("Cannot overwrite: " + file);
return new FSIndexOutput(file);
}
public override void Sync(string name)
{
EnsureOpen();
string fullName = System.IO.Path.Combine(directory.FullName, name);
bool success = false;
int retryCount = 0;
UnauthorizedAccessException exc = null;
while (!success && retryCount < 5)
{
retryCount++;
System.IO.FileStream file = null;
try
{
try
{
file = new System.IO.FileStream(fullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
//TODO
// {{dougsale-2.4}}:
//
// in Lucene (Java):
// file.getFD().sync();
// file is a java.io.RandomAccessFile
// getFD() returns java.io.FileDescriptor
// sync() documentation states: "Force all system buffers to synchronize with the underlying device."
//
// what they try to do here is get ahold of the underlying file descriptor
// for the given file name and make sure all (downstream) associated system buffers are
// flushed to disk
//
// how do i do that in .Net? flushing the created stream might inadvertently do it, or it
// may do nothing at all. I can find references to the file HANDLE, but it's not really
// a type, simply an int pointer.
//
// where is FSDirectory.Sync(string name) called from - if this isn't a new feature but rather a refactor, maybe
// i can snip the old code from where it was re-factored...
SupportClass.FileStream.Sync(file);
success = true;
}
finally
{
if (file != null)
file.Close();
}
}
catch (UnauthorizedAccessException e)
{
exc = e;
System.Threading.Thread.Sleep(5);
}
}
if (!success)
// throw original exception
throw exc;
}
// Inherit javadoc
public override IndexInput OpenInput(System.String name)
{
EnsureOpen();
return OpenInput(name, BufferedIndexInput.BUFFER_SIZE);
}
// Inherit javadoc
public override IndexInput OpenInput(System.String name, int bufferSize)
{
EnsureOpen();
return new FSIndexInput(new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name)), bufferSize);
}
/// <summary> So we can do some byte-to-hexchar conversion below</summary>
private static readonly char[] HEX_DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public override System.String GetLockID()
{
EnsureOpen();
System.String dirName; // name to be hashed
try
{
dirName = directory.FullName;
}
catch (System.IO.IOException e)
{
throw new System.SystemException(e.ToString(), e);
}
byte[] digest;
lock (DIGESTER)
{
digest = DIGESTER.ComputeHash(System.Text.Encoding.UTF8.GetBytes(dirName));
}
System.Text.StringBuilder buf = new System.Text.StringBuilder();
buf.Append("lucene-");
for (int i = 0; i < digest.Length; i++)
{
int b = digest[i];
buf.Append(HEX_DIGITS[(b >> 4) & 0xf]);
buf.Append(HEX_DIGITS[b & 0xf]);
}
return buf.ToString();
}
/// <summary>Closes the store to future operations. </summary>
public override void Close()
{
lock (this)
{
if (isOpen && --refCount <= 0)
{
isOpen = false;
lock (DIRECTORIES.SyncRoot)
{
DIRECTORIES.Remove(directory.FullName);
}
}
}
}
public virtual System.IO.FileInfo GetFile()
{
EnsureOpen();
return directory;
}
/// <summary>For debug output. </summary>
public override System.String ToString()
{
return this.GetType().FullName + "@" + directory;
}
public /*protected internal*/ class FSIndexInput : BufferedIndexInput, System.ICloneable
{
protected internal class Descriptor : System.IO.BinaryReader
{
// remember if the file is open, so that we don't try to close it
// more than once
protected internal volatile bool isOpen;
internal long position;
internal long length;
public Descriptor(FSIndexInput enclosingInstance, System.IO.FileInfo file, System.IO.FileAccess mode)
: base(new System.IO.FileStream(file.FullName, System.IO.FileMode.Open, mode, System.IO.FileShare.ReadWrite))
{
isOpen = true;
length = file.Length;
}
public override void Close()
{
if (isOpen)
{
isOpen = false;
base.Close();
}
}
~Descriptor()
{
try
{
Close();
}
finally
{
}
}
}
protected internal Descriptor file;
internal bool isClone;
public bool isClone_ForNUnitTest
{
get { return isClone; }
}
public FSIndexInput(System.IO.FileInfo path) : this(path, BufferedIndexInput.BUFFER_SIZE)
{
}
public FSIndexInput(System.IO.FileInfo path, int bufferSize) : base(bufferSize)
{
UnauthorizedAccessException ex = null;
for (int i = 0; i < 10; i++)
{
try
{
file = new Descriptor(this, path, System.IO.FileAccess.Read);
return;
}
catch (UnauthorizedAccessException e)
{
ex = e;
System.Threading.Thread.Sleep(100);
GC.Collect();
}
}
throw ex;
}
/// <summary>IndexInput methods </summary>
protected internal override void ReadInternal(byte[] b, int offset, int len)
{
lock (file)
{
long position = GetFilePointer();
if (position != file.position)
{
file.BaseStream.Seek(position, System.IO.SeekOrigin.Begin);
file.position = position;
}
int total = 0;
do
{
int i = file.Read(b, offset + total, len - total);
if (i <= 0)
throw new System.IO.IOException("read past EOF");
file.position += i;
total += i;
}
while (total < len);
}
}
public override void Close()
{
// only close the file if this is not a clone
if (!isClone)
file.Close();
System.GC.SuppressFinalize(this);
}
protected internal override void SeekInternal(long position)
{
}
public override long Length()
{
return file.length;
}
public override object Clone()
{
FSIndexInput clone = (FSIndexInput) base.Clone();
clone.isClone = true;
return clone;
}
/// <summary>Method used for testing. Returns true if the underlying
/// file descriptor is valid.
/// </summary>
public virtual bool IsFDValid()
{
return (file.BaseStream != null);
}
}
protected internal class FSIndexOutput : BufferedIndexOutput
{
internal System.IO.BinaryWriter file = null;
// remember if the file is open, so that we don't try to close it
// more than once
private volatile bool isOpen;
public FSIndexOutput(System.IO.FileInfo path)
{
UnauthorizedAccessException ex = null;
for (int i = 0; i < 10; i++)
{
try
{
file = new System.IO.BinaryWriter(new System.IO.FileStream(path.FullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite));
isOpen = true;
return;
}
catch (UnauthorizedAccessException e)
{
ex = e;
System.Threading.Thread.Sleep(100);
GC.Collect();
}
}
throw ex;
}
/// <summary>output methods: </summary>
public override void FlushBuffer(byte[] b, int offset, int size)
{
file.Write(b, offset, size);
// {{dougsale-2.4.0}}
// When writing frequently with small amounts of data, the data isn't flushed to disk.
// Thus, attempting to read the data soon after this method is invoked leads to
// BufferedIndexInput.Refill() throwing an IOException for reading past EOF.
// Test\Index\TestDoc.cs demonstrates such a situation.
// Forcing a flush here prevents said issue.
file.Flush();
}
public override void Close()
{
// only close the file if it has not been closed yet
if (isOpen)
{
base.Close();
file.Close();
isOpen = false;
System.GC.SuppressFinalize(this);
}
}
/// <summary>Random-access methods </summary>
public override void Seek(long pos)
{
base.Seek(pos);
file.BaseStream.Seek(pos, System.IO.SeekOrigin.Begin);
}
public override long Length()
{
return file.BaseStream.Length;
}
public override void SetLength(long length)
{
System.IO.FileStream fs = (System.IO.FileStream)file.BaseStream;
fs.SetLength(length);
}
}
static FSDirectory()
{
{
try
{
System.String name = SupportClass.AppSettings.Get("Lucene.Net.FSDirectory.class", typeof(FSDirectory).FullName);
IMPL = System.Type.GetType(name);
}
catch (System.Security.SecurityException)
{
try
{
IMPL = System.Type.GetType(typeof(FSDirectory).FullName);
}
catch (System.Exception e)
{
throw new System.SystemException("cannot load default FSDirectory class: " + e.ToString(), e);
}
}
catch (System.Exception e)
{
throw new System.SystemException("cannot load FSDirectory class: " + e.ToString(), e);
}
}
{
try
{
DIGESTER = SupportClass.Cryptography.GetHashAlgorithm();
}
catch (System.Exception e)
{
throw new System.SystemException(e.ToString(), e);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.DirectoryServices.Protocols
{
using System;
using System.Globalization;
using System.Threading;
using System.Collections;
using System.Diagnostics;
internal class LdapPartialResultsProcessor
{
private ArrayList _resultList = null;
private ManualResetEvent _workThreadWaitHandle = null;
private bool _workToDo = false;
private int _currentIndex = 0;
internal LdapPartialResultsProcessor(ManualResetEvent eventHandle)
{
_resultList = new ArrayList();
_workThreadWaitHandle = eventHandle;
}
public void Add(LdapPartialAsyncResult asyncResult)
{
lock (this)
{
_resultList.Add(asyncResult);
if (!_workToDo)
{
// need to wake up the workthread if it is not running already
_workThreadWaitHandle.Set();
_workToDo = true;
}
}
}
public void Remove(LdapPartialAsyncResult asyncResult)
{
// called by Abort operation
lock (this)
{
if (!_resultList.Contains(asyncResult))
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult));
// remove this async operation from the list
_resultList.Remove(asyncResult);
}
}
public void RetrievingSearchResults()
{
int count = 0;
int i = 0;
LdapPartialAsyncResult asyncResult = null;
AsyncCallback tmpCallback = null;
lock (this)
{
count = _resultList.Count;
if (count == 0)
{
// no asynchronous operation pending, begin to wait
_workThreadWaitHandle.Reset();
_workToDo = false;
return;
}
// might have work to do
while (true)
{
if (_currentIndex >= count)
{
// some element is moved after last iteration
_currentIndex = 0;
}
asyncResult = (LdapPartialAsyncResult)_resultList[_currentIndex];
i++;
_currentIndex++;
// have work to do
if (asyncResult.resultStatus != ResultsStatus.Done)
break;
if (i >= count)
{
// all the operations are done just waiting for the user to pick up the results
_workToDo = false;
_workThreadWaitHandle.Reset();
return;
}
}
// try to get the results availabe for this asynchronous operation
GetResultsHelper(asyncResult);
// if we are done with the asynchronous search, we need to fire callback and signal the waitable object
if (asyncResult.resultStatus == ResultsStatus.Done)
{
asyncResult.manualResetEvent.Set();
asyncResult.completed = true;
if (asyncResult.callback != null)
{
tmpCallback = asyncResult.callback;
}
}
else if (asyncResult.callback != null && asyncResult.partialCallback)
{
// if user specify callback to be called even when partial results become available
if (asyncResult.response != null && (asyncResult.response.Entries.Count > 0 || asyncResult.response.References.Count > 0))
{
tmpCallback = asyncResult.callback;
}
}
}
if (tmpCallback != null)
tmpCallback((IAsyncResult)asyncResult);
}
private void GetResultsHelper(LdapPartialAsyncResult asyncResult)
{
LdapConnection con = asyncResult.con;
IntPtr ldapResult = (IntPtr)0;
IntPtr entryMessage = (IntPtr)0;
ResultAll resultType = ResultAll.LDAP_MSG_RECEIVED;
if (asyncResult.resultStatus == ResultsStatus.CompleteResult)
resultType = ResultAll.LDAP_MSG_POLLINGALL;
try
{
SearchResponse response = (SearchResponse)con.ConstructResponse(asyncResult.messageID, LdapOperation.LdapSearch, resultType, asyncResult.requestTimeout, false);
// this should only happen in the polling thread case
if (response == null)
{
// only when request time out has not yet expiered
if ((asyncResult.startTime.Ticks + asyncResult.requestTimeout.Ticks) > DateTime.Now.Ticks)
{
// this is expected, just the client does not have the result yet
return;
}
else
{
// time out, now we need to throw proper exception
throw new LdapException((int)LdapError.TimeOut, LdapErrorMappings.MapResultCode((int)LdapError.TimeOut));
}
}
if (asyncResult.response != null)
AddResult(asyncResult.response, response);
else
asyncResult.response = response;
// if search is done, set the flag
if (response.searchDone)
asyncResult.resultStatus = ResultsStatus.Done;
}
catch (Exception e)
{
if (e is DirectoryOperationException)
{
SearchResponse response = (SearchResponse)(((DirectoryOperationException)e).Response);
if (asyncResult.response != null)
AddResult(asyncResult.response, response);
else
asyncResult.response = response;
// set the response back to the exception so it holds all the results up to now
((DirectoryOperationException)e).response = asyncResult.response;
}
else if (e is LdapException)
{
LdapException ldapE = (LdapException)e;
LdapError errorCode = (LdapError)ldapE.ErrorCode;
if (asyncResult.response != null)
{
// add previous retrieved entries if available
if (asyncResult.response.Entries != null)
{
for (int i = 0; i < asyncResult.response.Entries.Count; i++)
{
ldapE.results.Add(asyncResult.response.Entries[i]);
}
}
// add previous retrieved references if available
if (asyncResult.response.References != null)
{
for (int i = 0; i < asyncResult.response.References.Count; i++)
{
ldapE.results.Add(asyncResult.response.References[i]);
}
}
}
}
// exception occurs, this operation is done.
asyncResult.exception = e;
asyncResult.resultStatus = ResultsStatus.Done;
// need to abandon this request
Wldap32.ldap_abandon(con.ldapHandle, asyncResult.messageID);
}
}
public void NeedCompleteResult(LdapPartialAsyncResult asyncResult)
{
lock (this)
{
if (_resultList.Contains(asyncResult))
{
// we don't need partial results anymore, polling for complete results
if (asyncResult.resultStatus == ResultsStatus.PartialResult)
asyncResult.resultStatus = ResultsStatus.CompleteResult;
}
else
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult));
}
}
public PartialResultsCollection GetPartialResults(LdapPartialAsyncResult asyncResult)
{
lock (this)
{
if (!_resultList.Contains(asyncResult))
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult));
if (asyncResult.exception != null)
{
// remove this async operation
// the async operation basically failed, we won't do it any more, so throw exception to the user and remove it from the list
_resultList.Remove(asyncResult);
throw asyncResult.exception;
}
PartialResultsCollection collection = new PartialResultsCollection();
if (asyncResult.response != null)
{
if (asyncResult.response.Entries != null)
{
for (int i = 0; i < asyncResult.response.Entries.Count; i++)
collection.Add(asyncResult.response.Entries[i]);
asyncResult.response.Entries.Clear();
}
if (asyncResult.response.References != null)
{
for (int i = 0; i < asyncResult.response.References.Count; i++)
collection.Add(asyncResult.response.References[i]);
asyncResult.response.References.Clear();
}
}
return collection;
}
}
public DirectoryResponse GetCompleteResult(LdapPartialAsyncResult asyncResult)
{
lock (this)
{
if (!_resultList.Contains(asyncResult))
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult));
Debug.Assert(asyncResult.resultStatus == ResultsStatus.Done);
_resultList.Remove(asyncResult);
if (asyncResult.exception != null)
{
throw asyncResult.exception;
}
else
{
return asyncResult.response;
}
}
}
private void AddResult(SearchResponse partialResults, SearchResponse newResult)
{
if (newResult == null)
return;
if (newResult.Entries != null)
{
for (int i = 0; i < newResult.Entries.Count; i++)
{
partialResults.Entries.Add(newResult.Entries[i]);
}
}
if (newResult.References != null)
{
for (int i = 0; i < newResult.References.Count; i++)
{
partialResults.References.Add(newResult.References[i]);
}
}
}
}
internal class PartialResultsRetriever
{
private ManualResetEvent _workThreadWaitHandle = null;
private Thread _oThread = null;
private LdapPartialResultsProcessor _processor = null;
internal PartialResultsRetriever(ManualResetEvent eventHandle, LdapPartialResultsProcessor processor)
{
_workThreadWaitHandle = eventHandle;
_processor = processor;
_oThread = new Thread(new ThreadStart(ThreadRoutine));
_oThread.IsBackground = true;
// start the thread
_oThread.Start();
}
private void ThreadRoutine()
{
while (true)
{
// make sure there is work to do
_workThreadWaitHandle.WaitOne();
// do the real work
try
{
_processor.RetrievingSearchResults();
}
catch (Exception e)
{
// we catch the exception here as we don't really want our worker thread to die because it
// encounter certain exception when processing a single async operation.
Debug.WriteLine(e.Message);
}
// Voluntarily gives up the CPU time
Thread.Sleep(250);
}
}
}
}
| |
// <copyright file=DistanceMethods.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:58 PM</date>
using HciLab.Utilities.Mathematics.Core;
using System;
namespace HciLab.Utilities.Mathematics.Geometry3D
{
/// <summary>
/// Provides various distance computation methods.
/// </summary>
public sealed class DistanceMethods
{
public enum DistanceOrientation : short
{
XAxis = 0,
YAxis = 1,
ZAxis = 2
};
#region Point-Point
/// <summary>
/// Calculates the squared distance between two points.
/// </summary>
/// <param name="point1">A <see cref="Vector3"/> instance.</param>
/// <param name="point2">A <see cref="Vector3"/> instance.</param>
/// <returns>The squared distance between between two points.</returns>
public static double SquaredDistance(Vector3 point1, Vector3 point2)
{
Vector3 delta = point2 - point1;
return delta.GetLengthSquared();
}
/// <summary>
/// Calculates the distance between two points.
/// </summary>
/// <param name="point1">A <see cref="Vector3"/> instance.</param>
/// <param name="point2">A <see cref="Vector3"/> instance.</param>
/// <returns>The distance between between two points.</returns>
public static double Distance(Vector3 point1, Vector3 point2)
{
return System.Math.Sqrt(SquaredDistance(point1, point2));
}
public static double Distance(Vector3 point1, Vector3 point2, DistanceOrientation pOrientation)
{
if (pOrientation == DistanceOrientation.XAxis)
return point2.X - point1.X;
else if (pOrientation == DistanceOrientation.YAxis)
return point2.Y - point1.Y;
else if (pOrientation == DistanceOrientation.ZAxis)
return point2.Z - point1.Z;
throw new Exception();
}
#endregion
#region Point-OBB
/// <summary>
/// Calculates the squared distance between a point and a solid oriented box.
/// </summary>
/// <param name="point">A <see cref="Vector3"/> instance.</param>
/// <param name="obb">An <see cref="OrientedBox"/> instance.</param>
/// <param name="closestPoint">The closest point in box coordinates.</param>
/// <returns>The squared distance between a point and a solid oriented box.</returns>
/// <remarks>
/// Treating the oriented box as solid means that any point inside the box has
/// distance zero from the box.
/// </remarks>
public static double SquaredDistancePointSolidOrientedBox(Vector3 point, OrientedBox obb, out Vector3 closestPoint)
{
Vector3 diff = point - obb.Center;
Vector3 closest = new Vector3(
Vector3.DotProduct(diff, obb.Axis1),
Vector3.DotProduct(diff, obb.Axis2),
Vector3.DotProduct(diff, obb.Axis3));
double sqrDist = 0.0f;
double delta = 0.0f;
if (closest.X < -obb.Extent1)
{
delta = closest.X + obb.Extent1;
sqrDist += delta*delta;
closest.X = -obb.Extent1;
}
else if (closest.X > obb.Extent1)
{
delta = closest.X - obb.Extent1;
sqrDist += delta*delta;
closest.X = obb.Extent1;
}
if (closest.Y < -obb.Extent2)
{
delta = closest.Y + obb.Extent2;
sqrDist += delta*delta;
closest.Y = -obb.Extent2;
}
else if (closest.Y > obb.Extent2)
{
delta = closest.Y - obb.Extent2;
sqrDist += delta*delta;
closest.Y = obb.Extent2;
}
if (closest.Z < -obb.Extent3)
{
delta = closest.Z + obb.Extent3;
sqrDist += delta*delta;
closest.Z = -obb.Extent3;
}
else if (closest.Z > obb.Extent3)
{
delta = closest.Z - obb.Extent3;
sqrDist += delta*delta;
closest.Z = obb.Extent3;
}
closestPoint = closest;
return sqrDist;
}
/// <summary>
/// Calculates the squared distance between a point and a solid oriented box.
/// </summary>
/// <param name="point">A <see cref="Vector3"/> instance.</param>
/// <param name="obb">An <see cref="OrientedBox"/> instance.</param>
/// <returns>The squared distance between a point and a solid oriented box.</returns>
/// <remarks>
/// Treating the oriented box as solid means that any point inside the box has
/// distance zero from the box.
/// </remarks>
public static double SquaredDistance(Vector3 point, OrientedBox obb)
{
Vector3 temp;
return SquaredDistancePointSolidOrientedBox(point, obb, out temp);
}
/// <summary>
/// Calculates the distance between a point and a solid oriented box.
/// </summary>
/// <param name="point">A <see cref="Vector3"/> instance.</param>
/// <param name="obb">An <see cref="OrientedBox"/> instance.</param>
/// <returns>The distance between a point and a solid oriented box.</returns>
/// <remarks>
/// Treating the oriented box as solid means that any point inside the box has
/// distance zero from the box.
/// </remarks>
public static double Distance(Vector3 point, OrientedBox obb)
{
return (double)System.Math.Sqrt(SquaredDistance(point, obb));
}
#endregion
#region Point-Plane
/// <summary>
/// Calculates the distance between a point and a plane.
/// </summary>
/// <param name="point">A <see cref="Vector3"/> instance.</param>
/// <param name="plane">A <see cref="Plane"/> instance.</param>
/// <returns>The distance between a point and a plane.</returns>
/// <remarks>
/// <p>
/// A positive return value means teh point is on the positive side of the plane.
/// A negative return value means teh point is on the negative side of the plane.
/// A zero return value means the point is on the plane.
/// </p>
/// <p>
/// The absolute value of the return value is the true distance only when the plane normal is
/// a unit length vector.
/// </p>
/// </remarks>
public static double Distance(Vector3 point, Plane plane)
{
return Vector3.DotProduct(plane.Normal, point) + plane.Constant;
}
#endregion
#region Private Constructor
private DistanceMethods()
{
}
#endregion
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Contoso.Core.TaxonomyPickerWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Extensions.Logging;
using NBitcoin;
using NBitcoin.Networks;
using NBitcoin.Protocol;
using NLog.Extensions.Logging;
using Stratis.Bitcoin.Builder.Feature;
using Stratis.Bitcoin.Configuration.Logging;
using Stratis.Bitcoin.Configuration.Settings;
using Stratis.Bitcoin.Utilities;
namespace Stratis.Bitcoin.Configuration
{
internal static class NormalizeDirectorySeparatorExt
{
/// <summary>
/// Fixes incorrect directory separator characters in path (if any)
/// </summary>
public static string NormalizeDirectorySeparator(this string path)
{
// Replace incorrect with correct
return path.Replace((Path.DirectorySeparatorChar == '/') ? '\\' : '/', Path.DirectorySeparatorChar);
}
}
/// <summary>
/// Node configuration complied from both the application command line arguments and the configuration file.
/// </summary>
public class NodeSettings : IDisposable
{
/// <summary>Version of the protocol the current implementation supports.</summary>
public const ProtocolVersion SupportedProtocolVersion = ProtocolVersion.SENDHEADERS_VERSION;
/// <summary>Factory to create instance logger.</summary>
public ILoggerFactory LoggerFactory { get; private set; }
/// <summary>Instance logger.</summary>
public ILogger Logger { get; private set; }
/// <summary>Configuration related to logging.</summary>
public LogSettings Log { get; private set; }
/// <summary>List of paths to important files and folders.</summary>
public DataFolder DataFolder { get; private set; }
/// <summary>Path to the data directory. This value is read-only and is set in the constructor's args.</summary>
public string DataDir { get; private set; }
/// <summary>Path to the root data directory. This value is read-only and is set in the constructor's args.</summary>
public string DataDirRoot { get; private set; }
/// <summary>Path to the configuration file. This value is read-only and is set in the constructor's args.</summary>
public string ConfigurationFile { get; private set; }
/// <summary>Combined command line arguments and configuration file settings.</summary>
public TextFileConfiguration ConfigReader { get; private set; }
/// <summary>Supported protocol version.</summary>
public ProtocolVersion ProtocolVersion { get; private set; }
/// <summary>Lowest supported protocol version.</summary>
public ProtocolVersion? MinProtocolVersion { get; set; }
/// <summary>Specification of the network the node runs on - regtest/testnet/mainnet.</summary>
public Network Network { get; private set; }
/// <summary>The node's user agent.</summary>
public string Agent { get; private set; }
/// <summary>Minimum transaction fee for network.</summary>
public FeeRate MinTxFeeRate { get; private set; }
/// <summary>Fall back transaction fee for network.</summary>
public FeeRate FallbackTxFeeRate { get; private set; }
/// <summary>Minimum relay transaction fee for network.</summary>
public FeeRate MinRelayTxFeeRate { get; private set; }
/// <summary>
/// Initializes a new instance of the object.
/// </summary>
/// <param name="network">The network the node runs on - regtest/testnet/mainnet.</param>
/// <param name="protocolVersion">Supported protocol version for which to create the configuration.</param>
/// <param name="agent">The nodes user agent that will be shared with peers.</param>
/// <param name="args">The command-line arguments.</param>
/// <param name="networksSelector">A selector class that delayed load a network for either - regtest/testnet/mainnet.</param>
/// <exception cref="ConfigurationException">Thrown in case of any problems with the configuration file or command line arguments.</exception>
/// <remarks>
/// Processing depends on whether a configuration file is passed via the command line.
/// There are two main scenarios here:
/// - The configuration file is passed via the command line. In this case we need
/// to read it earlier so that it can provide defaults for "testnet" and "regtest".
/// - Alternatively, if the file name is not supplied then a network-specific file
/// name would be determined. In this case we first need to determine the network.
/// </remarks>
public NodeSettings(Network network = null, ProtocolVersion protocolVersion = SupportedProtocolVersion,
string agent = "StratisNode", string[] args = null, NetworksSelector networksSelector = null)
{
// Create the default logger factory and logger.
var loggerFactory = new ExtendedLoggerFactory();
this.LoggerFactory = loggerFactory;
this.LoggerFactory.AddConsoleWithFilters();
this.LoggerFactory.AddNLog();
this.Logger = this.LoggerFactory.CreateLogger(typeof(NodeSettings).FullName);
// Record arguments.
this.Network = network;
this.ProtocolVersion = protocolVersion;
this.Agent = agent;
this.ConfigReader = new TextFileConfiguration(args ?? new string[] { });
// Log arguments.
this.Logger.LogDebug("Arguments: network='{0}', protocolVersion='{1}', agent='{2}', args='{3}'.",
this.Network == null ? "(None)" : this.Network.Name,
this.ProtocolVersion,
this.Agent,
args == null ? "(None)" : string.Join(" ", args));
// By default, we look for a file named '<network>.conf' in the network's data directory,
// but both the data directory and the configuration file path may be changed using the -datadir and -conf command-line arguments.
this.ConfigurationFile = this.ConfigReader.GetOrDefault<string>("conf", null, this.Logger)?.NormalizeDirectorySeparator();
this.DataDir = this.ConfigReader.GetOrDefault<string>("datadir", null, this.Logger)?.NormalizeDirectorySeparator();
this.DataDirRoot = this.ConfigReader.GetOrDefault<string>("datadirroot", "StratisNode", this.Logger);
// If the configuration file is relative then assume it is relative to the data folder and combine the paths.
if (this.DataDir != null && this.ConfigurationFile != null)
{
bool isRelativePath = Path.GetFullPath(this.ConfigurationFile).Length > this.ConfigurationFile.Length;
if (isRelativePath)
this.ConfigurationFile = Path.Combine(this.DataDir, this.ConfigurationFile);
}
// If the configuration file has been specified on the command line then read it now
// so that it can provide the defaults for testnet and regtest.
if (this.ConfigurationFile != null)
{
// If the configuration file was specified on the command line then it must exist.
if (!File.Exists(this.ConfigurationFile))
throw new ConfigurationException($"Configuration file does not exist at {this.ConfigurationFile}.");
// Sets the ConfigReader based on the arguments and the configuration file if it exists.
this.ReadConfigurationFile();
}
// If the network is not known then derive it from the command line arguments.
if (this.Network == null)
{
if (networksSelector == null)
throw new ConfigurationException("Network or NetworkSelector not provided.");
// Find out if we need to run on testnet or regtest from the config file.
bool testNet = this.ConfigReader.GetOrDefault<bool>("testnet", false, this.Logger);
bool regTest = this.ConfigReader.GetOrDefault<bool>("regtest", false, this.Logger);
if (testNet && regTest)
throw new ConfigurationException("Invalid combination of regtest and testnet.");
this.Network = testNet ? networksSelector.Testnet() : regTest ? networksSelector.Regtest() : networksSelector.Mainnet();
this.Logger.LogDebug("Network set to '{0}'.", this.Network.Name);
}
// Ensure the network being used is registered and we have the correct Network object reference.
this.Network = NetworkRegistration.Register(this.Network);
// Set the full data directory path.
if (this.DataDir == null)
{
// Create the data directories if they don't exist.
this.DataDir = this.CreateDefaultDataDirectories(Path.Combine(this.DataDirRoot, this.Network.RootFolderName), this.Network);
}
else
{
// Combine the data directory with the network's root folder and name.
string directoryPath = Path.Combine(this.DataDir, this.Network.RootFolderName, this.Network.Name);
this.DataDir = Directory.CreateDirectory(directoryPath).FullName;
this.Logger.LogDebug("Data directory initialized with path {0}.", this.DataDir);
}
// Set the data folder.
this.DataFolder = new DataFolder(this.DataDir);
// Attempt to load NLog configuration from the DataFolder.
loggerFactory.LoadNLogConfiguration(this.DataFolder);
// Get the configuration file name for the network if it was not specified on the command line.
if (this.ConfigurationFile == null)
{
this.ConfigurationFile = Path.Combine(this.DataDir, this.Network.DefaultConfigFilename);
this.Logger.LogDebug("Configuration file set to '{0}'.", this.ConfigurationFile);
if (File.Exists(this.ConfigurationFile))
this.ReadConfigurationFile();
}
// Create the custom logger factory.
this.Log = new LogSettings();
this.Log.Load(this.ConfigReader);
this.LoggerFactory.AddFilters(this.Log, this.DataFolder);
this.LoggerFactory.ConfigureConsoleFilters(this.LoggerFactory.GetConsoleSettings(), this.Log);
// Load the configuration.
this.LoadConfiguration();
}
/// <summary>Determines whether to print help and exit.</summary>
public bool PrintHelpAndExit
{
get
{
return this.ConfigReader.GetOrDefault<bool>("help", false, this.Logger) ||
this.ConfigReader.GetOrDefault<bool>("-help", false, this.Logger);
}
}
/// <summary>
/// Initializes default configuration.
/// </summary>
/// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
/// <param name="protocolVersion">Supported protocol version for which to create the configuration.</param>
/// <returns>Default node configuration.</returns>
public static NodeSettings Default(Network network, ProtocolVersion protocolVersion = SupportedProtocolVersion)
{
return new NodeSettings(network, protocolVersion);
}
/// <summary>
/// Creates the configuration file if it does not exist.
/// </summary>
/// <param name="features">The features for which to include settings in the configuration file.</param>
public void CreateDefaultConfigurationFile(List<IFeatureRegistration> features)
{
// If the config file does not exist yet then create it now.
if (!File.Exists(this.ConfigurationFile))
{
this.Logger.LogDebug("Creating configuration file '{0}'.", this.ConfigurationFile);
var builder = new StringBuilder();
foreach (IFeatureRegistration featureRegistration in features)
{
MethodInfo getDefaultConfiguration = featureRegistration.FeatureType.GetMethod("BuildDefaultConfigurationFile", BindingFlags.Public | BindingFlags.Static);
if (getDefaultConfiguration != null)
{
getDefaultConfiguration.Invoke(null, new object[] { builder, this.Network });
builder.AppendLine();
}
}
File.WriteAllText(this.ConfigurationFile, builder.ToString());
this.ReadConfigurationFile();
this.LoadConfiguration();
}
}
/// <summary>
/// Reads the configuration file and merges it with the command line arguments.
/// </summary>
private void ReadConfigurationFile()
{
this.Logger.LogDebug("Reading configuration file '{0}'.", this.ConfigurationFile);
// Add the file configuration to the command-line configuration.
var fileConfig = new TextFileConfiguration(File.ReadAllText(this.ConfigurationFile));
fileConfig.MergeInto(this.ConfigReader);
}
/// <summary>
/// Loads the node settings from the application configuration.
/// </summary>
private void LoadConfiguration()
{
TextFileConfiguration config = this.ConfigReader;
this.MinTxFeeRate = new FeeRate(config.GetOrDefault("mintxfee", this.Network.MinTxFee, this.Logger));
this.FallbackTxFeeRate = new FeeRate(config.GetOrDefault("fallbackfee", this.Network.FallbackFee, this.Logger));
this.MinRelayTxFeeRate = new FeeRate(config.GetOrDefault("minrelaytxfee", this.Network.MinRelayTxFee, this.Logger));
}
/// <summary>
/// Creates default data directories respecting different operating system specifics.
/// </summary>
/// <param name="appName">Name of the node, which will be reflected in the name of the data directory.</param>
/// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
/// <returns>The top-level data directory path.</returns>
private string CreateDefaultDataDirectories(string appName, Network network)
{
string directoryPath;
// Directory paths are different between Windows or Linux/OSX systems.
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
string home = Environment.GetEnvironmentVariable("HOME");
if (!string.IsNullOrEmpty(home))
{
this.Logger.LogDebug("Using HOME environment variable for initializing application data.");
directoryPath = Path.Combine(home, "." + appName.ToLowerInvariant());
}
else
{
throw new DirectoryNotFoundException("Could not find HOME directory.");
}
}
else
{
string localAppData = Environment.GetEnvironmentVariable("APPDATA");
if (!string.IsNullOrEmpty(localAppData))
{
this.Logger.LogDebug("Using APPDATA environment variable for initializing application data.");
directoryPath = Path.Combine(localAppData, appName);
}
else
{
throw new DirectoryNotFoundException("Could not find APPDATA directory.");
}
}
// Create the data directories if they don't exist.
directoryPath = Path.Combine(directoryPath, network.Name);
Directory.CreateDirectory(directoryPath);
this.Logger.LogDebug("Data directory initialized with path {0}.", directoryPath);
return directoryPath;
}
/// <summary>
/// Displays command-line help.
/// </summary>
/// <param name="network">The network to extract values from.</param>
public static void PrintHelp(Network network)
{
Guard.NotNull(network, nameof(network));
NodeSettings defaults = Default(network: network);
string daemonName = Path.GetFileName(Assembly.GetEntryAssembly().Location);
var builder = new StringBuilder();
builder.AppendLine("Usage:");
builder.AppendLine($" dotnet run {daemonName} [arguments]");
builder.AppendLine();
builder.AppendLine("Command line arguments:");
builder.AppendLine();
builder.AppendLine($"-help/--help Show this help.");
builder.AppendLine($"-conf=<Path> Path to the configuration file. Defaults to {defaults.ConfigurationFile}.");
builder.AppendLine($"-datadir=<Path> Path to the data directory. Defaults to {defaults.DataDir}.");
builder.AppendLine($"-debug[=<string>] Set 'Debug' logging level. Specify what to log via e.g. '-debug=Stratis.Bitcoin.Miner,Stratis.Bitcoin.Wallet'.");
builder.AppendLine($"-loglevel=<string> Direct control over the logging level: '-loglevel=trace/debug/info/warn/error/fatal'.");
// Can be overridden in configuration file.
builder.AppendLine($"-testnet Use the testnet chain.");
builder.AppendLine($"-regtest Use the regtestnet chain.");
builder.AppendLine($"-mintxfee=<number> Minimum fee rate. Defaults to {network.MinTxFee}.");
builder.AppendLine($"-fallbackfee=<number> Fallback fee rate. Defaults to {network.FallbackFee}.");
builder.AppendLine($"-minrelaytxfee=<number> Minimum relay fee rate. Defaults to {network.MinRelayTxFee}.");
defaults.Logger.LogInformation(builder.ToString());
ConnectionManagerSettings.PrintHelp(network);
}
/// <summary>
/// Get the default configuration.
/// </summary>
/// <param name="builder">The string builder to add the settings to.</param>
/// <param name="network">The network to base the defaults off.</param>
public static void BuildDefaultConfigurationFile(StringBuilder builder, Network network)
{
builder.AppendLine("####Node Settings####");
builder.AppendLine($"#Test network. Defaults to 0.");
builder.AppendLine($"testnet={((network.IsTest() && !network.IsRegTest()) ? 1 : 0)}");
builder.AppendLine($"#Regression test network. Defaults to 0.");
builder.AppendLine($"regtest={(network.IsRegTest() ? 1 : 0)}");
builder.AppendLine($"#Minimum fee rate. Defaults to {network.MinTxFee}.");
builder.AppendLine($"#mintxfee={network.MinTxFee}");
builder.AppendLine($"#Fallback fee rate. Defaults to {network.FallbackFee}.");
builder.AppendLine($"#fallbackfee={network.FallbackFee}");
builder.AppendLine($"#Minimum relay fee rate. Defaults to {network.MinRelayTxFee}.");
builder.AppendLine($"#minrelaytxfee={network.MinRelayTxFee}");
builder.AppendLine();
ConnectionManagerSettings.BuildDefaultConfigurationFile(builder, network);
}
/// <inheritdoc />
public void Dispose()
{
this.LoggerFactory.Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.ControllerFeatureProviderControllers;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Controllers
{
public class ControllerFeatureProviderTest
{
[Fact]
public void UserDefinedClass_DerivedFromController_IsController()
{
// Arrange
var controllerType = typeof(StoreController).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
var discovered = Assert.Single(feature.Controllers);
Assert.Equal(controllerType, discovered);
}
[Fact]
public void UserDefinedClass_DerivedFromControllerBase_IsController()
{
// Arrange
var controllerType = typeof(ProductsController).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
var discovered = Assert.Single(feature.Controllers);
Assert.Equal(controllerType, discovered);
}
[Fact]
public void UserDefinedClass_DerivedFromControllerBaseWithoutSuffix_IsController()
{
// Arrange
var controllerType = typeof(Products).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
var discovered = Assert.Single(feature.Controllers);
Assert.Equal(controllerType, discovered);
}
[Fact]
public void FrameworkControllerClass_IsNotController()
{
// Arrange
var controllerType = typeof(Controller).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
Assert.Empty(feature.Controllers);
}
[Fact]
public void FrameworkBaseControllerClass_IsNotController()
{
// Arrange
var controllerType = typeof(ControllerBase).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
Assert.Empty(feature.Controllers);
}
[Fact]
public void UserDefinedControllerClass_IsNotController()
{
// Arrange
var controllerType = typeof(ControllerFeatureProviderControllers.Controller).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
Assert.Empty(feature.Controllers);
}
[Fact]
public void Interface_IsNotController()
{
// Arrange
var controllerType = typeof(ITestController).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
Assert.Empty(feature.Controllers);
}
[Fact]
public void ValueTypeClass_IsNotController()
{
// Arrange
var controllerType = typeof(int).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
Assert.Empty(feature.Controllers);
}
[Fact]
public void AbstractClass_IsNotController()
{
// Arrange
var controllerType = typeof(AbstractController).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
Assert.Empty(feature.Controllers);
}
[Fact]
public void DerivedAbstractClass_IsController()
{
// Arrange
var controllerType = typeof(DerivedAbstractController).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
var discovered = Assert.Single(feature.Controllers);
Assert.Equal(controllerType, discovered);
}
[Fact]
public void OpenGenericClass_IsNotController()
{
// Arrange
var controllerType = typeof(OpenGenericController<>).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
Assert.Empty(feature.Controllers);
}
[Fact]
public void WithoutSuffixOrAncestorWithController_IsNotController()
{
// Arrange
var controllerType = typeof(NoSuffixPoco).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
Assert.Empty(feature.Controllers);
}
[Fact]
public void ClosedGenericClass_IsController()
{
// Arrange
var controllerType = typeof(OpenGenericController<string>).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
var discovered = Assert.Single(feature.Controllers);
Assert.Equal(controllerType, discovered);
}
[Fact]
public void DerivedGenericClass_IsController()
{
// Arrange
var controllerType = typeof(DerivedGenericController).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
var discovered = Assert.Single(feature.Controllers);
Assert.Equal(controllerType, discovered);
}
[Fact]
public void Poco_WithNamingConvention_IsController()
{
// Arrange
var controllerType = typeof(PocoController).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
var discovered = Assert.Single(feature.Controllers);
Assert.Equal(controllerType, discovered);
}
[Fact]
public void NoControllerSuffix_IsController()
{
// Arrange
var controllerType = typeof(NoSuffix).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
var discovered = Assert.Single(feature.Controllers);
Assert.Equal(controllerType, discovered);
}
[Theory]
[InlineData(typeof(DescendantLevel1))]
[InlineData(typeof(DescendantLevel2))]
public void AncestorTypeHasControllerAttribute_IsController(Type type)
{
// Arrange
var manager = GetApplicationPartManager(type.GetTypeInfo());
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
var discovered = Assert.Single(feature.Controllers);
Assert.Equal(type.GetTypeInfo(), discovered);
}
[Fact]
public void AncestorTypeDoesNotHaveControllerAttribute_IsNotController()
{
// Arrange
var controllerType = typeof(NoSuffixNoControllerAttribute).GetTypeInfo();
var manager = GetApplicationPartManager(controllerType);
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
Assert.Empty(feature.Controllers);
}
[Fact]
public void GetFeature_OnlyRunsOnParts_ThatImplementIApplicationPartTypeProvider()
{
// Arrange
var otherPart = new Mock<ApplicationPart>();
otherPart
.As<IApplicationPartTypeProvider>()
.Setup(t => t.Types)
.Returns(new[] { typeof(PocoController).GetTypeInfo() });
var parts = new[] {
Mock.Of<ApplicationPart>(),
new TestApplicationPart(typeof(NoSuffix).GetTypeInfo()),
otherPart.Object
};
var feature = new ControllerFeature();
var expected = new List<TypeInfo>
{
typeof(NoSuffix).GetTypeInfo(),
typeof(PocoController).GetTypeInfo()
};
var provider = new ControllerFeatureProvider();
// Act
provider.PopulateFeature(parts, feature);
// Assert
Assert.Equal(expected, feature.Controllers.ToList());
}
[Fact]
public void GetFeature_DoesNotAddDuplicates_ToTheListOfControllers()
{
// Arrange
var otherPart = new Mock<ApplicationPart>();
otherPart
.As<IApplicationPartTypeProvider>()
.Setup(t => t.Types)
.Returns(new[] { typeof(PocoController).GetTypeInfo() });
var parts = new[] {
Mock.Of<ApplicationPart>(),
new TestApplicationPart(typeof(NoSuffix)),
otherPart.Object
};
var feature = new ControllerFeature();
var expected = new List<TypeInfo>
{
typeof(NoSuffix).GetTypeInfo(),
typeof(PocoController).GetTypeInfo()
};
var provider = new ControllerFeatureProvider();
provider.PopulateFeature(parts, feature);
// Act
provider.PopulateFeature(parts, feature);
// Assert
Assert.Equal(expected, feature.Controllers.ToList());
}
[Theory]
[InlineData(typeof(BaseNonControllerController))]
[InlineData(typeof(BaseNonControllerControllerChild))]
[InlineData(typeof(BasePocoNonControllerController))]
[InlineData(typeof(BasePocoNonControllerControllerChild))]
[InlineData(typeof(NonController))]
[InlineData(typeof(NonControllerChild))]
[InlineData(typeof(BaseNonControllerAttributeChildControllerControllerAttributeController))]
[InlineData(typeof(PersonModel))] // Verifies that POCO type hierarchies that don't derive from controller return false.
public void IsController_ReturnsFalse_IfTypeOrAncestorHasNonControllerAttribute(Type type)
{
// Arrange
var manager = GetApplicationPartManager(type.GetTypeInfo());
var feature = new ControllerFeature();
// Act
manager.PopulateFeature(feature);
// Assert
Assert.Empty(feature.Controllers);
}
private static ApplicationPartManager GetApplicationPartManager(params TypeInfo[] types)
{
var manager = new ApplicationPartManager();
manager.ApplicationParts.Add(new TestApplicationPart(types));
manager.FeatureProviders.Add(new ControllerFeatureProvider());
return manager;
}
}
}
// These controllers are used to test the ControllerFeatureProvider implementation
// which REQUIRES that they be public top-level classes. To avoid having to stub out the
// implementation of this class to test it, they are just top level classes. Don't reuse
// these outside this test - find a better way or use nested classes to keep the tests
// independent.
namespace Microsoft.AspNetCore.Mvc.ControllerFeatureProviderControllers
{
public abstract class AbstractController : Controller
{
}
public class DerivedAbstractController : AbstractController
{
}
public class StoreController : Controller
{
}
public class ProductsController : ControllerBase
{
}
public class Products : ControllerBase
{
}
[Controller]
public abstract class Controller
{
}
public abstract class NoControllerAttributeBaseController
{
}
public class NoSuffixNoControllerAttribute : NoControllerAttributeBaseController
{
}
public class OpenGenericController<T> : Controller
{
}
public class DerivedGenericController : OpenGenericController<string>
{
}
public interface ITestController
{
}
public class NoSuffix : Controller
{
}
public class NoSuffixPoco
{
}
public class PocoController
{
}
[Controller]
public class CustomBase
{
}
[Controller]
public abstract class CustomAbstractBaseController
{
}
public class DescendantLevel1 : CustomBase
{
}
public class DescendantLevel2 : DescendantLevel1
{
}
public class AbstractChildWithoutSuffix : CustomAbstractBaseController
{
}
[NonController]
public class BasePocoNonControllerController
{
}
[Controller]
public class BaseNonControllerAttributeChildControllerControllerAttributeController : BaseNonControllerController
{
}
public class BasePocoNonControllerControllerChild : BasePocoNonControllerController
{
}
[NonController]
public class BaseNonControllerController : Controller
{
}
public class BaseNonControllerControllerChild : BaseNonControllerController
{
}
[NonController]
public class NonControllerChild : Controller
{
}
[NonController]
public class NonController : Controller
{
}
public class DataModelBase
{
}
public class EntityDataModel : DataModelBase
{
}
public class PersonModel : EntityDataModel
{
}
}
| |
//! \file ArcBIN.cs
//! \date 2019 Feb 23
//! \brief Unity binary data asset.
//
// Copyright (C) 2019 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using GameRes.Utility;
namespace GameRes.Formats.Unity
{
internal class BinArchive : ArcFile
{
public readonly Aes Encryption;
public BinArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, Aes enc)
: base (arc, impl, dir)
{
Encryption = enc;
}
#region IDisposable Members
bool _bin_disposed = false;
protected override void Dispose (bool disposing)
{
if (_bin_disposed)
return;
if (disposing)
Encryption.Dispose();
_bin_disposed = true;
base.Dispose (disposing);
}
#endregion
}
[Serializable]
public class BinPackKey
{
public byte[] Key;
public byte[] IV;
public BinPackKey (string key, string iv)
{
Key = Encoding.UTF8.GetBytes (key);
IV = Encoding.UTF8.GetBytes (iv);
}
}
[Serializable]
public class BinPackScheme : ResourceScheme
{
public Dictionary<string, BinPackKey> KnownKeys;
}
[Export(typeof(ArchiveFormat))]
public class BinOpener : ArchiveFormat
{
public override string Tag { get { return "BIN/IDX"; } }
public override string Description { get { return "Unity engine resource asset"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return true; } }
public override bool CanWrite { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
if (!file.Name.HasExtension (".bin"))
return null;
var idx_name = Path.ChangeExtension (file.Name, "idx");
if (!VFS.FileExists (idx_name))
return null;
var scheme = QueryScheme (file.Name);
if (null == scheme)
return null;
var dir = new List<Entry>();
using (var idx = VFS.OpenBinaryStream (idx_name))
using (var aes = Aes.Create())
{
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
aes.KeySize = 128;
aes.Key = scheme.Key;
aes.IV = scheme.IV;
var input_buffer = new byte[0x100];
var unpacker = new BinDeserializer();
while (idx.PeekByte() != -1)
{
int length = idx.ReadInt32();
if (length <= 0)
return null;
if (length > input_buffer.Length)
input_buffer = new byte[length];
if (idx.Read (input_buffer, 0, length) < length)
return null;
using (var decryptor = aes.CreateDecryptor())
using (var encrypted = new MemoryStream (input_buffer, 0, length))
using (var input = new InputCryptoStream (encrypted, decryptor))
{
var info = unpacker.DeserializeEntry (input);
var filename = info["fileName"] as string;
if (string.IsNullOrEmpty (filename))
return null;
filename = filename.TrimStart ('/', '\\');
var entry = Create<Entry> (filename);
entry.Offset = Convert.ToInt64 (info["index"]);
entry.Size = Convert.ToUInt32 (info["size"]);
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
}
}
}
if (0 == dir.Count)
return null;
var arc_aes = Aes.Create();
arc_aes.Padding = PaddingMode.PKCS7;
arc_aes.Mode = CipherMode.CBC;
arc_aes.KeySize = 256;
arc_aes.Key = scheme.Key;
arc_aes.IV = scheme.IV;
return new BinArchive (file, this, dir, arc_aes);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var bin_arc = (BinArchive)arc;
var decryptor = bin_arc.Encryption.CreateDecryptor();
var input = arc.File.CreateStream (entry.Offset, entry.Size);
return new InputCryptoStream (input, decryptor);
}
BinPackKey QueryScheme (string arc_name)
{
return DefaultScheme.KnownKeys.Values.FirstOrDefault();
}
static BinPackScheme DefaultScheme = new BinPackScheme { KnownKeys = new Dictionary<string, BinPackKey>() };
public override ResourceScheme Scheme
{
get { return DefaultScheme; }
set { DefaultScheme = (BinPackScheme)value; }
}
}
internal class BinDeserializer
{
byte[] m_buffer = new byte[0x20];
public IDictionary DeserializeEntry (Stream input)
{
int id = input.ReadByte();
if (id < 0x80 || id > 0x8F)
throw new FormatException();
int field_count = id & 0xF;
var map = new Hashtable (field_count);
for (int i = 0; i < field_count; ++i)
{
id = input.ReadByte();
if (id < 0xA0 || id > 0xBF)
throw new FormatException();
int length = id & 0x1F;
if (input.Read (m_buffer, 0, length) < length)
throw new FormatException();
var key = Encoding.UTF8.GetString (m_buffer, 0, length);
var value = ReadField (input);
map[key] = value;
}
return map;
}
object ReadField (Stream input)
{
int id = input.ReadByte();
if (id >= 0 && id < 0x80)
{
return id;
}
else if (id >= 0xA0 && id < 0xC0)
{
int length = id & 0x1F;
return ReadString (input, length);
}
switch (id)
{
case 0xD0: // Int8
int value = input.ReadByte();
if (-1 == value)
throw new FormatException();
return (sbyte)value;
case 0xD1: // Int16
if (input.Read (m_buffer, 0, 2) < 2)
throw new FormatException();
return BigEndian.ToInt16 (m_buffer, 0);
case 0xD2: // Int32
if (input.Read (m_buffer, 0, 4) < 4)
throw new FormatException();
return BigEndian.ToInt32 (m_buffer, 0);
case 0xDA: // Raw16
if (input.Read (m_buffer, 0, 2) < 2)
throw new FormatException();
int length = BigEndian.ToUInt16 (m_buffer, 0);
return ReadString (input, length);
default:
throw new FormatException();
}
}
string ReadString (Stream input, int length)
{
if (length > m_buffer.Length)
m_buffer = new byte[(length + 0xF) & ~0xF];
input.Read (m_buffer, 0, length);
return Encoding.UTF8.GetString (m_buffer, 0, length);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache.Store
{
using System;
using System.Collections;
using System.Collections.Generic;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Store;
using NUnit.Framework;
/// <summary>
///
/// </summary>
class Key
{
private readonly int _idx;
public Key(int idx)
{
_idx = idx;
}
public int Index()
{
return _idx;
}
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != GetType())
return false;
Key key = (Key)obj;
return key._idx == _idx;
}
public override int GetHashCode()
{
return _idx;
}
}
/// <summary>
///
/// </summary>
class Value
{
private int _idx;
public Value(int idx)
{
_idx = idx;
}
public int Index()
{
return _idx;
}
}
/// <summary>
/// Cache entry predicate.
/// </summary>
[Serializable]
public class CacheEntryFilter : ICacheEntryFilter<int, string>
{
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, string> entry)
{
return entry.Key >= 105;
}
}
/// <summary>
/// Cache entry predicate that throws an exception.
/// </summary>
[Serializable]
public class ExceptionalEntryFilter : ICacheEntryFilter<int, string>
{
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, string> entry)
{
throw new Exception("Expected exception in ExceptionalEntryFilter");
}
}
/// <summary>
/// Filter that can't be serialized.
/// </summary>
public class InvalidCacheEntryFilter : CacheEntryFilter
{
// No-op.
}
/// <summary>
///
/// </summary>
public class CacheStoreTest
{
/** */
private const string BinaryStoreCacheName = "binary_store";
/** */
private const string ObjectStoreCacheName = "object_store";
/** */
private const string CustomStoreCacheName = "custom_store";
/** */
private const string TemplateStoreCacheName = "template_store*";
/** */
private volatile int _storeCount = 3;
/// <summary>
///
/// </summary>
[TestFixtureSetUp]
public void BeforeTests()
{
TestUtils.KillProcesses();
TestUtils.JvmDebug = true;
var cfg = new IgniteConfiguration
{
GridName = GridName,
JvmClasspath = TestUtils.CreateTestClasspath(),
JvmOptions = TestUtils.TestJavaOptions(),
SpringConfigUrl = "config\\native-client-test-cache-store.xml",
BinaryConfiguration = new BinaryConfiguration(typeof (Key), typeof (Value))
};
Ignition.Start(cfg);
}
/// <summary>
///
/// </summary>
[TestFixtureTearDown]
public virtual void AfterTests()
{
Ignition.StopAll(true);
}
/// <summary>
///
/// </summary>
[SetUp]
public void BeforeTest()
{
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
///
/// </summary>
[TearDown]
public void AfterTest()
{
var cache = GetCache();
cache.Clear();
Assert.IsTrue(cache.IsEmpty(), "Cache is not empty: " + cache.GetSize());
CacheTestStore.Reset();
TestUtils.AssertHandleRegistryHasItems(300, _storeCount, Ignition.GetIgnite(GridName));
Console.WriteLine("Test finished: " + TestContext.CurrentContext.Test.Name);
}
[Test]
public void TestLoadCache()
{
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LoadCache(new CacheEntryFilter(), 100, 10);
Assert.AreEqual(5, cache.GetSize());
for (int i = 105; i < 110; i++)
Assert.AreEqual("val_" + i, cache.Get(i));
// Test invalid filter
Assert.Throws<BinaryObjectException>(() => cache.LoadCache(new InvalidCacheEntryFilter(), 100, 10));
// Test exception in filter
Assert.Throws<CacheStoreException>(() => cache.LoadCache(new ExceptionalEntryFilter(), 100, 10));
}
[Test]
public void TestLocalLoadCache()
{
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCache(new CacheEntryFilter(), 100, 10);
Assert.AreEqual(5, cache.GetSize());
for (int i = 105; i < 110; i++)
Assert.AreEqual("val_" + i, cache.Get(i));
}
[Test]
public void TestLoadCacheMetadata()
{
CacheTestStore.LoadObjects = true;
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCache(null, 0, 3);
Assert.AreEqual(3, cache.GetSize());
var meta = cache.WithKeepBinary<Key, IBinaryObject>().Get(new Key(0)).GetBinaryType();
Assert.NotNull(meta);
Assert.AreEqual("Value", meta.TypeName);
}
[Test]
public void TestLoadCacheAsync()
{
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCacheAsync(new CacheEntryFilter(), 100, 10).Wait();
Assert.AreEqual(5, cache.GetSizeAsync().Result);
for (int i = 105; i < 110; i++)
{
Assert.AreEqual("val_" + i, cache.GetAsync(i).Result);
}
}
[Test]
public void TestPutLoad()
{
var cache = GetCache();
cache.Put(1, "val");
IDictionary map = StoreMap();
Assert.AreEqual(1, map.Count);
cache.LocalEvict(new[] { 1 });
Assert.AreEqual(0, cache.GetSize());
Assert.AreEqual("val", cache.Get(1));
Assert.AreEqual(1, cache.GetSize());
}
[Test]
public void TestPutLoadBinarizable()
{
var cache = GetBinaryStoreCache<int, Value>();
cache.Put(1, new Value(1));
IDictionary map = StoreMap();
Assert.AreEqual(1, map.Count);
IBinaryObject v = (IBinaryObject)map[1];
Assert.AreEqual(1, v.GetField<int>("_idx"));
cache.LocalEvict(new[] { 1 });
Assert.AreEqual(0, cache.GetSize());
Assert.AreEqual(1, cache.Get(1).Index());
Assert.AreEqual(1, cache.GetSize());
}
[Test]
public void TestPutLoadObjects()
{
var cache = GetObjectStoreCache<int, Value>();
cache.Put(1, new Value(1));
IDictionary map = StoreMap();
Assert.AreEqual(1, map.Count);
Value v = (Value)map[1];
Assert.AreEqual(1, v.Index());
cache.LocalEvict(new[] { 1 });
Assert.AreEqual(0, cache.GetSize());
Assert.AreEqual(1, cache.Get(1).Index());
Assert.AreEqual(1, cache.GetSize());
}
[Test]
public void TestPutLoadAll()
{
var putMap = new Dictionary<int, string>();
for (int i = 0; i < 10; i++)
putMap.Add(i, "val_" + i);
var cache = GetCache();
cache.PutAll(putMap);
IDictionary map = StoreMap();
Assert.AreEqual(10, map.Count);
for (int i = 0; i < 10; i++)
Assert.AreEqual("val_" + i, map[i]);
cache.Clear();
Assert.AreEqual(0, cache.GetSize());
ICollection<int> keys = new List<int>();
for (int i = 0; i < 10; i++)
keys.Add(i);
IDictionary<int, string> loaded = cache.GetAll(keys);
Assert.AreEqual(10, loaded.Count);
for (int i = 0; i < 10; i++)
Assert.AreEqual("val_" + i, loaded[i]);
Assert.AreEqual(10, cache.GetSize());
}
[Test]
public void TestRemove()
{
var cache = GetCache();
for (int i = 0; i < 10; i++)
cache.Put(i, "val_" + i);
IDictionary map = StoreMap();
Assert.AreEqual(10, map.Count);
for (int i = 0; i < 5; i++)
cache.Remove(i);
Assert.AreEqual(5, map.Count);
for (int i = 5; i < 10; i++)
Assert.AreEqual("val_" + i, map[i]);
}
[Test]
public void TestRemoveAll()
{
var cache = GetCache();
for (int i = 0; i < 10; i++)
cache.Put(i, "val_" + i);
IDictionary map = StoreMap();
Assert.AreEqual(10, map.Count);
cache.RemoveAll(new List<int> { 0, 1, 2, 3, 4 });
Assert.AreEqual(5, map.Count);
for (int i = 5; i < 10; i++)
Assert.AreEqual("val_" + i, map[i]);
}
[Test]
public void TestTx()
{
var cache = GetCache();
using (var tx = cache.Ignite.GetTransactions().TxStart())
{
CacheTestStore.ExpCommit = true;
tx.AddMeta("meta", 100);
cache.Put(1, "val");
tx.Commit();
}
IDictionary map = StoreMap();
Assert.AreEqual(1, map.Count);
Assert.AreEqual("val", map[1]);
}
[Test]
public void TestLoadCacheMultithreaded()
{
CacheTestStore.LoadMultithreaded = true;
var cache = GetCache();
Assert.AreEqual(0, cache.GetSize());
cache.LocalLoadCache(null, 0, null);
Assert.AreEqual(1000, cache.GetSize());
for (int i = 0; i < 1000; i++)
Assert.AreEqual("val_" + i, cache.Get(i));
}
[Test]
public void TestCustomStoreProperties()
{
var cache = GetCustomStoreCache();
Assert.IsNotNull(cache);
Assert.AreEqual(42, CacheTestStore.intProperty);
Assert.AreEqual("String value", CacheTestStore.stringProperty);
}
[Test]
public void TestDynamicStoreStart()
{
var cache = GetTemplateStoreCache();
Assert.IsNotNull(cache);
cache.Put(1, cache.Name);
Assert.AreEqual(cache.Name, CacheTestStore.Map[1]);
_storeCount++;
}
/// <summary>
/// Get's grid name for this test.
/// </summary>
/// <value>Grid name.</value>
protected virtual string GridName
{
get { return null; }
}
private IDictionary StoreMap()
{
return CacheTestStore.Map;
}
private ICache<int, string> GetCache()
{
return GetBinaryStoreCache<int, string>();
}
private ICache<TK, TV> GetBinaryStoreCache<TK, TV>()
{
return Ignition.GetIgnite(GridName).GetCache<TK, TV>(BinaryStoreCacheName);
}
private ICache<TK, TV> GetObjectStoreCache<TK, TV>()
{
return Ignition.GetIgnite(GridName).GetCache<TK, TV>(ObjectStoreCacheName);
}
private ICache<int, string> GetCustomStoreCache()
{
return Ignition.GetIgnite(GridName).GetCache<int, string>(CustomStoreCacheName);
}
private ICache<int, string> GetTemplateStoreCache()
{
var cacheName = TemplateStoreCacheName.Replace("*", Guid.NewGuid().ToString());
return Ignition.GetIgnite(GridName).GetOrCreateCache<int, string>(cacheName);
}
}
/// <summary>
///
/// </summary>
public class NamedNodeCacheStoreTest : CacheStoreTest
{
/** <inheritDoc /> */
protected override string GridName
{
get { return "name"; }
}
}
}
| |
/*
* DISCLAIMER
*
* Copyright 2016 ArangoDB GmbH, Cologne, Germany
*
* 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 holder is ArangoDB GmbH, Cologne, Germany
*/
namespace ArangoDB.Velocypack.Internal
{
/// <author>Mark - mark at arangodb.com</author>
public class VPackKeyMapAdapters
{
private VPackKeyMapAdapters()
: base()
{
}
public static VPackKeyMapAdapter<java.lang.Enum<object>>
createEnumAdapter(global::System.Type type)
{
return new _VPackKeyMapAdapter_40(type);
}
private sealed class _VPackKeyMapAdapter_40 : VPackKeyMapAdapter
<java.lang.Enum<object>>
{
public _VPackKeyMapAdapter_40(global::System.Type type)
{
this.type = type;
}
public string serialize<_T0>(java.lang.Enum<_T0> key)
where _T0 : java.lang.Enum<E>
{
return key.name();
}
public java.lang.Enum<object> deserialize(string key)
{
java.lang.Class enumType = (java.lang.Class)this.type;
return java.lang.Enum.valueOf(enumType, key);
}
private readonly global::System.Type type;
}
private sealed class _VPackKeyMapAdapter_55 : VPackKeyMapAdapter
<string>
{
public _VPackKeyMapAdapter_55()
{
}
public string serialize(string key)
{
return key;
}
public string deserialize(string key)
{
return key;
}
}
public static readonly VPackKeyMapAdapter<string> STRING =
new _VPackKeyMapAdapter_55();
private sealed class _VPackKeyMapAdapter_66 : VPackKeyMapAdapter
<bool>
{
public _VPackKeyMapAdapter_66()
{
}
public string serialize(bool key)
{
return key.ToString();
}
public bool deserialize(string key)
{
return bool.valueOf(key);
}
}
public static readonly VPackKeyMapAdapter<bool> BOOLEAN =
new _VPackKeyMapAdapter_66();
private sealed class _VPackKeyMapAdapter_77 : VPackKeyMapAdapter
<int>
{
public _VPackKeyMapAdapter_77()
{
}
public string serialize(int key)
{
return key.ToString();
}
public int deserialize(string key)
{
return int.Parse(key);
}
}
public static readonly VPackKeyMapAdapter<int> INTEGER =
new _VPackKeyMapAdapter_77();
private sealed class _VPackKeyMapAdapter_88 : VPackKeyMapAdapter
<long>
{
public _VPackKeyMapAdapter_88()
{
}
public string serialize(long key)
{
return key.ToString();
}
public long deserialize(string key)
{
return long.valueOf(key);
}
}
public static readonly VPackKeyMapAdapter<long> LONG = new
_VPackKeyMapAdapter_88();
private sealed class _VPackKeyMapAdapter_99 : VPackKeyMapAdapter
<short>
{
public _VPackKeyMapAdapter_99()
{
}
public string serialize(short key)
{
return key.ToString();
}
public short deserialize(string key)
{
return short.valueOf(key);
}
}
public static readonly VPackKeyMapAdapter<short> SHORT =
new _VPackKeyMapAdapter_99();
private sealed class _VPackKeyMapAdapter_110 : VPackKeyMapAdapter
<double>
{
public _VPackKeyMapAdapter_110()
{
}
public string serialize(double key)
{
return key.ToString();
}
public double deserialize(string key)
{
return double.valueOf(key);
}
}
public static readonly VPackKeyMapAdapter<double> DOUBLE =
new _VPackKeyMapAdapter_110();
private sealed class _VPackKeyMapAdapter_121 : VPackKeyMapAdapter
<float>
{
public _VPackKeyMapAdapter_121()
{
}
public string serialize(float key)
{
return key.ToString();
}
public float deserialize(string key)
{
return float.valueOf(key);
}
}
public static readonly VPackKeyMapAdapter<float> FLOAT =
new _VPackKeyMapAdapter_121();
private sealed class _VPackKeyMapAdapter_132 : VPackKeyMapAdapter
<java.math.BigInteger>
{
public _VPackKeyMapAdapter_132()
{
}
public string serialize(java.math.BigInteger key)
{
return key.ToString();
}
public java.math.BigInteger deserialize(string key)
{
return new java.math.BigInteger(key);
}
}
public static readonly VPackKeyMapAdapter<java.math.BigInteger
> BIG_INTEGER = new _VPackKeyMapAdapter_132();
private sealed class _VPackKeyMapAdapter_143 : VPackKeyMapAdapter
<java.math.BigDecimal>
{
public _VPackKeyMapAdapter_143()
{
}
public string serialize(java.math.BigDecimal key)
{
return key.ToString();
}
public java.math.BigDecimal deserialize(string key)
{
return new java.math.BigDecimal(key);
}
}
public static readonly VPackKeyMapAdapter<java.math.BigDecimal
> BIG_DECIMAL = new _VPackKeyMapAdapter_143();
private sealed class _VPackKeyMapAdapter_154 : VPackKeyMapAdapter
<java.lang.Number>
{
public _VPackKeyMapAdapter_154()
{
}
public string serialize(java.lang.Number key)
{
return key.ToString();
}
public java.lang.Number deserialize(string key)
{
return double.valueOf(key);
}
}
public static readonly VPackKeyMapAdapter<java.lang.Number
> NUMBER = new _VPackKeyMapAdapter_154();
private sealed class _VPackKeyMapAdapter_165 : VPackKeyMapAdapter
<char>
{
public _VPackKeyMapAdapter_165()
{
}
public string serialize(char key)
{
return key.ToString();
}
public char deserialize(string key)
{
return key[0];
}
}
public static readonly VPackKeyMapAdapter<char> CHARACTER
= new _VPackKeyMapAdapter_165();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Security;
namespace System.IO.MemoryMappedFiles
{
public partial class MemoryMappedFile : IDisposable
{
private readonly SafeMemoryMappedFileHandle _handle;
private readonly bool _leaveOpen;
private readonly FileStream _fileStream;
internal const int DefaultSize = 0;
// Private constructors to be used by the factory methods.
[SecurityCritical]
private MemoryMappedFile(SafeMemoryMappedFileHandle handle)
{
Debug.Assert(handle != null);
Debug.Assert(!handle.IsClosed);
Debug.Assert(!handle.IsInvalid);
_handle = handle;
_leaveOpen = true; // No FileStream to dispose of in this case.
}
[SecurityCritical]
private MemoryMappedFile(SafeMemoryMappedFileHandle handle, FileStream fileStream, bool leaveOpen)
{
Debug.Assert(handle != null);
Debug.Assert(!handle.IsClosed);
Debug.Assert(!handle.IsInvalid);
Debug.Assert(fileStream != null);
_handle = handle;
_fileStream = fileStream;
_leaveOpen = leaveOpen;
}
// Factory Method Group #1: Opens an existing named memory mapped file. The native OpenFileMapping call
// will check the desiredAccessRights against the ACL on the memory mapped file. Note that a memory
// mapped file created without an ACL will use a default ACL taken from the primary or impersonation token
// of the creator. On my machine, I always get ReadWrite access to it so I never have to use anything but
// the first override of this method. Note: having ReadWrite access to the object does not mean that we
// have ReadWrite access to the pages mapping the file. The OS will check against the access on the pages
// when a view is created.
public static MemoryMappedFile OpenExisting(string mapName)
{
return OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.None);
}
public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights)
{
return OpenExisting(mapName, desiredAccessRights, HandleInheritability.None);
}
[SecurityCritical]
public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights,
HandleInheritability inheritability)
{
if (mapName == null)
{
throw new ArgumentNullException(nameof(mapName), SR.ArgumentNull_MapName);
}
if (mapName.Length == 0)
{
throw new ArgumentException(SR.Argument_MapNameEmptyString);
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
{
throw new ArgumentOutOfRangeException(nameof(inheritability));
}
if (((int)desiredAccessRights & ~((int)(MemoryMappedFileRights.FullControl | MemoryMappedFileRights.AccessSystemSecurity))) != 0)
{
throw new ArgumentOutOfRangeException(nameof(desiredAccessRights));
}
SafeMemoryMappedFileHandle handle = OpenCore(mapName, inheritability, desiredAccessRights, false);
return new MemoryMappedFile(handle);
}
// Factory Method Group #2: Creates a new memory mapped file where the content is taken from an existing
// file on disk. This file must be opened by a FileStream before given to us. Specifying DefaultSize to
// the capacity will make the capacity of the memory mapped file match the size of the file. Specifying
// a value larger than the size of the file will enlarge the new file to this size. Note that in such a
// case, the capacity (and there for the size of the file) will be rounded up to a multiple of the system
// page size. One can use FileStream.SetLength to bring the length back to a desirable size. By default,
// the MemoryMappedFile will close the FileStream object when it is disposed. This behavior can be
// changed by the leaveOpen boolean argument.
public static MemoryMappedFile CreateFromFile(string path)
{
return CreateFromFile(path, FileMode.Open, null, DefaultSize, MemoryMappedFileAccess.ReadWrite);
}
public static MemoryMappedFile CreateFromFile(string path, FileMode mode)
{
return CreateFromFile(path, mode, null, DefaultSize, MemoryMappedFileAccess.ReadWrite);
}
public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string mapName)
{
return CreateFromFile(path, mode, mapName, DefaultSize, MemoryMappedFileAccess.ReadWrite);
}
public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string mapName, long capacity)
{
return CreateFromFile(path, mode, mapName, capacity, MemoryMappedFileAccess.ReadWrite);
}
[SecurityCritical]
public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string mapName, long capacity,
MemoryMappedFileAccess access)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
if (mapName != null && mapName.Length == 0)
{
throw new ArgumentException(SR.Argument_MapNameEmptyString);
}
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired);
}
if (access < MemoryMappedFileAccess.ReadWrite ||
access > MemoryMappedFileAccess.ReadWriteExecute)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
if (mode == FileMode.Append)
{
throw new ArgumentException(SR.Argument_NewMMFAppendModeNotAllowed, nameof(mode));
}
if (access == MemoryMappedFileAccess.Write)
{
throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, nameof(access));
}
bool existed = File.Exists(path);
FileStream fileStream = new FileStream(path, mode, GetFileAccess(access), FileShare.Read, 0x1000, FileOptions.None);
if (capacity == 0 && fileStream.Length == 0)
{
CleanupFile(fileStream, existed, path);
throw new ArgumentException(SR.Argument_EmptyFile);
}
if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length)
{
CleanupFile(fileStream, existed, path);
throw new ArgumentException(SR.Argument_ReadAccessWithLargeCapacity);
}
if (capacity == DefaultSize)
{
capacity = fileStream.Length;
}
// one can always create a small view if they do not want to map an entire file
if (fileStream.Length > capacity)
{
CleanupFile(fileStream, existed, path);
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_CapacityGEFileSizeRequired);
}
SafeMemoryMappedFileHandle handle = null;
try
{
handle = CreateCore(fileStream, mapName, HandleInheritability.None,
access, MemoryMappedFileOptions.None, capacity);
}
catch
{
CleanupFile(fileStream, existed, path);
throw;
}
Debug.Assert(handle != null);
Debug.Assert(!handle.IsInvalid);
return new MemoryMappedFile(handle, fileStream, false);
}
[SecurityCritical]
public static MemoryMappedFile CreateFromFile(FileStream fileStream, string mapName, long capacity,
MemoryMappedFileAccess access,
HandleInheritability inheritability, bool leaveOpen)
{
if (fileStream == null)
{
throw new ArgumentNullException(nameof(fileStream), SR.ArgumentNull_FileStream);
}
if (mapName != null && mapName.Length == 0)
{
throw new ArgumentException(SR.Argument_MapNameEmptyString);
}
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired);
}
if (capacity == 0 && fileStream.Length == 0)
{
throw new ArgumentException(SR.Argument_EmptyFile);
}
if (access < MemoryMappedFileAccess.ReadWrite ||
access > MemoryMappedFileAccess.ReadWriteExecute)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
if (access == MemoryMappedFileAccess.Write)
{
throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, nameof(access));
}
if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length)
{
throw new ArgumentException(SR.Argument_ReadAccessWithLargeCapacity);
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
{
throw new ArgumentOutOfRangeException(nameof(inheritability));
}
// flush any bytes written to the FileStream buffer so that we can see them in our MemoryMappedFile
fileStream.Flush();
if (capacity == DefaultSize)
{
capacity = fileStream.Length;
}
// one can always create a small view if they do not want to map an entire file
if (fileStream.Length > capacity)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_CapacityGEFileSizeRequired);
}
SafeMemoryMappedFileHandle handle = CreateCore(fileStream, mapName, inheritability,
access, MemoryMappedFileOptions.None, capacity);
return new MemoryMappedFile(handle, fileStream, leaveOpen);
}
// Factory Method Group #3: Creates a new empty memory mapped file. Such memory mapped files are ideal
// for IPC, when mapName != null.
public static MemoryMappedFile CreateNew(string mapName, long capacity)
{
return CreateNew(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None,
HandleInheritability.None);
}
public static MemoryMappedFile CreateNew(string mapName, long capacity, MemoryMappedFileAccess access)
{
return CreateNew(mapName, capacity, access, MemoryMappedFileOptions.None,
HandleInheritability.None);
}
[SecurityCritical]
public static MemoryMappedFile CreateNew(string mapName, long capacity, MemoryMappedFileAccess access,
MemoryMappedFileOptions options,
HandleInheritability inheritability)
{
if (mapName != null && mapName.Length == 0)
{
throw new ArgumentException(SR.Argument_MapNameEmptyString);
}
if (capacity <= 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedPositiveNumber);
}
if (IntPtr.Size == 4 && capacity > uint.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed);
}
if (access < MemoryMappedFileAccess.ReadWrite ||
access > MemoryMappedFileAccess.ReadWriteExecute)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
if (access == MemoryMappedFileAccess.Write)
{
throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, nameof(access));
}
if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0)
{
throw new ArgumentOutOfRangeException(nameof(options));
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
{
throw new ArgumentOutOfRangeException(nameof(inheritability));
}
SafeMemoryMappedFileHandle handle = CreateCore(null, mapName, inheritability, access, options, capacity);
return new MemoryMappedFile(handle);
}
// Factory Method Group #4: Creates a new empty memory mapped file or opens an existing
// memory mapped file if one exists with the same name. The capacity, options, and
// memoryMappedFileSecurity arguments will be ignored in the case of the later.
// This is ideal for P2P style IPC.
public static MemoryMappedFile CreateOrOpen(string mapName, long capacity)
{
return CreateOrOpen(mapName, capacity, MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileOptions.None, HandleInheritability.None);
}
public static MemoryMappedFile CreateOrOpen(string mapName, long capacity,
MemoryMappedFileAccess access)
{
return CreateOrOpen(mapName, capacity, access, MemoryMappedFileOptions.None, HandleInheritability.None);
}
[SecurityCritical]
public static MemoryMappedFile CreateOrOpen(string mapName, long capacity,
MemoryMappedFileAccess access, MemoryMappedFileOptions options,
HandleInheritability inheritability)
{
if (mapName == null)
{
throw new ArgumentNullException(nameof(mapName), SR.ArgumentNull_MapName);
}
if (mapName.Length == 0)
{
throw new ArgumentException(SR.Argument_MapNameEmptyString);
}
if (capacity <= 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedPositiveNumber);
}
if (IntPtr.Size == 4 && capacity > uint.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed);
}
if (access < MemoryMappedFileAccess.ReadWrite ||
access > MemoryMappedFileAccess.ReadWriteExecute)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0)
{
throw new ArgumentOutOfRangeException(nameof(options));
}
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
{
throw new ArgumentOutOfRangeException(nameof(inheritability));
}
SafeMemoryMappedFileHandle handle;
// special case for write access; create will never succeed
if (access == MemoryMappedFileAccess.Write)
{
handle = OpenCore(mapName, inheritability, access, true);
}
else
{
handle = CreateOrOpenCore(mapName, inheritability, access, options, capacity);
}
return new MemoryMappedFile(handle);
}
// Creates a new view in the form of a stream.
public MemoryMappedViewStream CreateViewStream()
{
return CreateViewStream(0, DefaultSize, MemoryMappedFileAccess.ReadWrite);
}
public MemoryMappedViewStream CreateViewStream(long offset, long size)
{
return CreateViewStream(offset, size, MemoryMappedFileAccess.ReadWrite);
}
[SecurityCritical]
public MemoryMappedViewStream CreateViewStream(long offset, long size, MemoryMappedFileAccess access)
{
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (size < 0)
{
throw new ArgumentOutOfRangeException(nameof(size), SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired);
}
if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
if (IntPtr.Size == 4 && size > uint.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(size), SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed);
}
MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size);
return new MemoryMappedViewStream(view);
}
// Creates a new view in the form of an accessor. Accessors are for random access.
public MemoryMappedViewAccessor CreateViewAccessor()
{
return CreateViewAccessor(0, DefaultSize, MemoryMappedFileAccess.ReadWrite);
}
public MemoryMappedViewAccessor CreateViewAccessor(long offset, long size)
{
return CreateViewAccessor(offset, size, MemoryMappedFileAccess.ReadWrite);
}
[SecurityCritical]
public MemoryMappedViewAccessor CreateViewAccessor(long offset, long size, MemoryMappedFileAccess access)
{
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (size < 0)
{
throw new ArgumentOutOfRangeException(nameof(size), SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired);
}
if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
if (IntPtr.Size == 4 && size > uint.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(size), SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed);
}
MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size);
return new MemoryMappedViewAccessor(view);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
try
{
if (!_handle.IsClosed)
{
_handle.Dispose();
}
}
finally
{
if (_fileStream != null && _leaveOpen == false)
{
_fileStream.Dispose();
}
}
}
public SafeMemoryMappedFileHandle SafeMemoryMappedFileHandle
{
[SecurityCritical]
get { return _handle; }
}
// This converts a MemoryMappedFileAccess to a FileAccess. MemoryMappedViewStream and
// MemoryMappedViewAccessor subclass UnmanagedMemoryStream and UnmanagedMemoryAccessor, which both use
// FileAccess to determine whether they are writable and/or readable.
internal static FileAccess GetFileAccess(MemoryMappedFileAccess access)
{
switch (access)
{
case MemoryMappedFileAccess.Read:
case MemoryMappedFileAccess.ReadExecute:
return FileAccess.Read;
case MemoryMappedFileAccess.ReadWrite:
case MemoryMappedFileAccess.CopyOnWrite:
case MemoryMappedFileAccess.ReadWriteExecute:
return FileAccess.ReadWrite;
default:
Debug.Assert(access == MemoryMappedFileAccess.Write);
return FileAccess.Write;
}
}
// clean up: close file handle and delete files we created
private static void CleanupFile(FileStream fileStream, bool existed, string path)
{
fileStream.Dispose();
if (!existed)
{
File.Delete(path);
}
}
}
}
| |
// 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.Immutable;
using System.IO;
using System.Reflection.Metadata.Tests;
using System.Reflection.PortableExecutable;
using Xunit;
namespace System.Reflection.Metadata.Decoding.Tests
{
public class CustomAttributeDecoderTests
{
[Fact]
public void TestCustomAttributeDecoder()
{
using (FileStream stream = File.OpenRead(typeof(HasAttributes).GetTypeInfo().Assembly.Location))
using (var peReader = new PEReader(stream))
{
MetadataReader reader = peReader.GetMetadataReader();
var provider = new CustomAttributeTypeProvider();
TypeDefinitionHandle typeDefHandle = TestMetadataResolver.FindTestType(reader, typeof(HasAttributes));
int i = 0;
foreach (CustomAttributeHandle attributeHandle in reader.GetCustomAttributes(typeDefHandle))
{
CustomAttribute attribute = reader.GetCustomAttribute(attributeHandle);
CustomAttributeValue<string> value = attribute.DecodeValue(provider);
switch (i++)
{
case 0:
Assert.Empty(value.FixedArguments);
Assert.Empty(value.NamedArguments);
break;
case 1:
Assert.Equal(3, value.FixedArguments.Length);
Assert.Equal("string", value.FixedArguments[0].Type);
Assert.Equal("0", value.FixedArguments[0].Value);
Assert.Equal("int32", value.FixedArguments[1].Type);
Assert.Equal(1, value.FixedArguments[1].Value);
Assert.Equal("float64", value.FixedArguments[2].Type);
Assert.Equal(2.0, value.FixedArguments[2].Value);
Assert.Empty(value.NamedArguments);
break;
case 2:
Assert.Equal(3, value.NamedArguments.Length);
Assert.Equal(CustomAttributeNamedArgumentKind.Field, value.NamedArguments[0].Kind);
Assert.Equal("StringField", value.NamedArguments[0].Name);
Assert.Equal("string", value.NamedArguments[0].Type);
Assert.Equal("0", value.NamedArguments[0].Value);
Assert.Equal(CustomAttributeNamedArgumentKind.Field, value.NamedArguments[1].Kind);
Assert.Equal("Int32Field", value.NamedArguments[1].Name);
Assert.Equal("int32", value.NamedArguments[1].Type);
Assert.Equal(1, value.NamedArguments[1].Value);
Assert.Equal(CustomAttributeNamedArgumentKind.Property, value.NamedArguments[2].Kind);
Assert.Equal("SByteEnumArrayProperty", value.NamedArguments[2].Name);
Assert.Equal(typeof(SByteEnum).FullName + "[]", value.NamedArguments[2].Type);
var array = (ImmutableArray<CustomAttributeTypedArgument<string>>)(value.NamedArguments[2].Value);
Assert.Equal(1, array.Length);
Assert.Equal(typeof(SByteEnum).FullName, array[0].Type);
Assert.Equal((sbyte)SByteEnum.Value, array[0].Value);
break;
default:
// TODO: https://github.com/dotnet/corefx/issues/6534
// The other cases are missing corresponding assertions. This needs some refactoring to
// be data-driven. A better approach would probably be to generically compare reflection
// CustomAttributeData to S.R.M CustomAttributeValue for every test attribute applied.
break;
}
}
}
}
// no arguments
[Test]
// multiple fixed arguments
[Test("0", 1, 2.0)]
// multiple named arguments
[Test(StringField = "0", Int32Field = 1, SByteEnumArrayProperty = new[] { SByteEnum.Value })]
// multiple fixed and named arguments
[Test("0", 1, 2.0, StringField = "0", Int32Field = 1, DoubleField = 2.0)]
// single fixed null argument
[Test((object)null)]
[Test((string)null)]
[Test((Type)null)]
[Test((int[])null)]
// single fixed arguments with strong type
[Test("string")]
[Test((sbyte)-1)]
[Test((short)-2)]
[Test((int)-4)]
[Test((long)-8)]
[Test((sbyte)-1)]
[Test((short)-2)]
[Test((int)-4)]
[Test((long)-8)]
[Test((byte)1)]
[Test((ushort)2)]
[Test((uint)4)]
[Test((ulong)8)]
[Test(true)]
[Test(false)]
[Test(typeof(string))]
[Test(SByteEnum.Value)]
[Test(Int16Enum.Value)]
[Test(Int32Enum.Value)]
[Test(Int64Enum.Value)]
[Test(ByteEnum.Value)]
[Test(UInt16Enum.Value)]
[Test(UInt32Enum.Value)]
[Test(UInt64Enum.Value)]
[Test(new string[] { })]
[Test(new string[] { "x", "y", "z", null })]
[Test(new Int32Enum[] { Int32Enum.Value })]
// same single fixed arguments as above, typed as object
[Test((object)("string"))]
[Test((object)(sbyte)-1)]
[Test((object)(short)-2)]
[Test((object)(int)-4)]
[Test((object)(long)-8)]
[Test((object)(sbyte)-1)]
[Test((object)(short)-2)]
[Test((object)(int)-4)]
[Test((object)(long)-8)]
[Test((object)(byte)1)]
[Test((object)(ushort)2)]
[Test((object)(uint)4)]
[Test((object)(true))]
[Test((object)(false))]
[Test((object)(typeof(string)))]
[Test((object)(SByteEnum.Value))]
[Test((object)(Int16Enum.Value))]
[Test((object)(Int32Enum.Value))]
[Test((object)(Int64Enum.Value))]
[Test((object)(ByteEnum.Value))]
[Test((object)(UInt16Enum.Value))]
[Test((object)(UInt32Enum.Value))]
[Test((object)(UInt64Enum.Value))]
[Test((object)(new string[] { }))]
[Test((object)(new string[] { "x", "y", "z", null }))]
[Test((object)(new Int32Enum[] { Int32Enum.Value }))]
// same values as above two cases, but put into an object[]
[Test(new object[] {
"string",
(sbyte)-1,
(short)-2,
(int)-4,
(long)-8,
(sbyte)-1,
(short)-2,
(int)-4,
(long)-8,
(byte)1,
(ushort)2,
(uint)4,
true,
false,
typeof(string),
SByteEnum.Value,
Int16Enum.Value,
Int32Enum.Value,
Int64Enum.Value,
SByteEnum.Value,
Int16Enum.Value,
Int32Enum.Value,
Int64Enum.Value,
new string[] {},
new string[] { "x", "y", "z", null },
})]
// same values as strongly-typed fixed arguments as named arguments
// single fixed arguments with strong type
[Test(StringField = "string")]
[Test(SByteField = -1)]
[Test(Int16Field = -2)]
[Test(Int32Field = -4)]
[Test(Int64Field = -8)]
[Test(SByteField = -1)]
[Test(Int16Field = -2)]
[Test(Int32Field = -4)]
[Test(Int64Field = -8)]
[Test(ByteField = 1)]
[Test(UInt16Field = 2)]
[Test(UInt32Field = 4)]
[Test(UInt64Field = 8)]
[Test(BooleanField = true)]
[Test(BooleanField = false)]
[Test(TypeField = typeof(string))]
[Test(SByteEnumField = SByteEnum.Value)]
[Test(Int16EnumField = Int16Enum.Value)]
[Test(Int32EnumField = Int32Enum.Value)]
[Test(Int64EnumField = Int64Enum.Value)]
[Test(ByteEnumField = ByteEnum.Value)]
[Test(UInt16EnumField = UInt16Enum.Value)]
[Test(UInt32EnumField = UInt32Enum.Value)]
[Test(UInt64EnumField = UInt64Enum.Value)]
[Test(new string[] { })]
[Test(new string[] { "x", "y", "z", null })]
[Test(new Int32Enum[] { Int32Enum.Value })]
// null named arguments
[Test(ObjectField = null)]
[Test(StringField = null)]
[Test(Int32ArrayProperty = null)]
private sealed class HasAttributes { }
public enum SByteEnum : sbyte { Value = -1 }
public enum Int16Enum : short { Value = -2 }
public enum Int32Enum : int { Value = -3 }
public enum Int64Enum : long { Value = -4 }
public enum ByteEnum : sbyte { Value = 1 }
public enum UInt16Enum : ushort { Value = 2 }
public enum UInt32Enum : uint { Value = 3 }
public enum UInt64Enum : ulong { Value = 4 }
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public sealed class TestAttribute : Attribute
{
public TestAttribute() { }
public TestAttribute(string x, int y, double z) { }
public TestAttribute(string value) { }
public TestAttribute(object value) { }
public TestAttribute(sbyte value) { }
public TestAttribute(short value) { }
public TestAttribute(int value) { }
public TestAttribute(long value) { }
public TestAttribute(byte value) { }
public TestAttribute(ushort value) { }
public TestAttribute(uint value) { }
public TestAttribute(ulong value) { }
public TestAttribute(bool value) { }
public TestAttribute(float value) { }
public TestAttribute(double value) { }
public TestAttribute(Type value) { }
public TestAttribute(SByteEnum value) { }
public TestAttribute(Int16Enum value) { }
public TestAttribute(Int32Enum value) { }
public TestAttribute(Int64Enum value) { }
public TestAttribute(ByteEnum value) { }
public TestAttribute(UInt16Enum value) { }
public TestAttribute(UInt32Enum value) { }
public TestAttribute(UInt64Enum value) { }
public TestAttribute(string[] value) { }
public TestAttribute(object[] value) { }
public TestAttribute(sbyte[] value) { }
public TestAttribute(short[] value) { }
public TestAttribute(int[] value) { }
public TestAttribute(long[] value) { }
public TestAttribute(byte[] value) { }
public TestAttribute(ushort[] value) { }
public TestAttribute(uint[] value) { }
public TestAttribute(ulong[] value) { }
public TestAttribute(bool[] value) { }
public TestAttribute(float[] value) { }
public TestAttribute(double[] value) { }
public TestAttribute(Type[] value) { }
public TestAttribute(SByteEnum[] value) { }
public TestAttribute(Int16Enum[] value) { }
public TestAttribute(Int32Enum[] value) { }
public TestAttribute(Int64Enum[] value) { }
public TestAttribute(ByteEnum[] value) { }
public TestAttribute(UInt16Enum[] value) { }
public TestAttribute(UInt32Enum[] value) { }
public TestAttribute(UInt64Enum[] value) { }
public string StringField;
public object ObjectField;
public sbyte SByteField;
public short Int16Field;
public int Int32Field;
public long Int64Field;
public byte ByteField;
public ushort UInt16Field;
public uint UInt32Field;
public ulong UInt64Field;
public bool BooleanField;
public float SingleField;
public double DoubleField;
public Type TypeField;
public SByteEnum SByteEnumField;
public Int16Enum Int16EnumField;
public Int32Enum Int32EnumField;
public Int64Enum Int64EnumField;
public ByteEnum ByteEnumField;
public UInt16Enum UInt16EnumField;
public UInt32Enum UInt32EnumField;
public UInt64Enum UInt64EnumField;
public string[] StringArrayProperty { get; set; }
public object[] ObjectArrayProperty { get; set; }
public sbyte[] SByteArrayProperty { get; set; }
public short[] Int16ArrayProperty { get; set; }
public int[] Int32ArrayProperty { get; set; }
public long[] Int64ArrayProperty { get; set; }
public byte[] ByteArrayProperty { get; set; }
public ushort[] UInt16ArrayProperty { get; set; }
public uint[] UInt32ArrayProperty { get; set; }
public ulong[] UInt64ArrayProperty { get; set; }
public bool[] BooleanArrayProperty { get; set; }
public float[] SingleArrayProperty { get; set; }
public double[] DoubleArrayProperty { get; set; }
public Type[] TypeArrayProperty { get; set; }
public SByteEnum[] SByteEnumArrayProperty { get; set; }
public Int16Enum[] Int16EnumArrayProperty { get; set; }
public Int32Enum[] Int32EnumArrayProperty { get; set; }
public Int64Enum[] Int64EnumArrayProperty { get; set; }
public ByteEnum[] ByteEnumArrayProperty { get; set; }
public UInt16Enum[] UInt16EnumArrayProperty { get; set; }
public UInt32Enum[] UInt32EnumArrayProperty { get; set; }
public UInt64Enum[] UInt64EnumArrayProperty { get; set; }
}
private class CustomAttributeTypeProvider : DisassemblingTypeProvider, ICustomAttributeTypeProvider<string>
{
public string GetSystemType()
{
return "[System.Runtime]System.Type";
}
public bool IsSystemType(string type)
{
return type == "[System.Runtime]System.Type" // encountered as typeref
|| Type.GetType(type) == typeof(Type); // encountered as serialized to reflection notation
}
public string GetTypeFromSerializedName(string name)
{
return name;
}
public PrimitiveTypeCode GetUnderlyingEnumType(string type)
{
Type runtimeType = Type.GetType(type.Replace('/', '+')); // '/' vs '+' is only difference between ilasm and reflection notation for fixed set below.
if (runtimeType == typeof(SByteEnum))
return PrimitiveTypeCode.SByte;
if (runtimeType == typeof(Int16Enum))
return PrimitiveTypeCode.Int16;
if (runtimeType == typeof(Int32Enum))
return PrimitiveTypeCode.Int32;
if (runtimeType == typeof(Int64Enum))
return PrimitiveTypeCode.Int64;
if (runtimeType == typeof(ByteEnum))
return PrimitiveTypeCode.Byte;
if (runtimeType == typeof(UInt16Enum))
return PrimitiveTypeCode.UInt16;
if (runtimeType == typeof(UInt32Enum))
return PrimitiveTypeCode.UInt32;
if (runtimeType == typeof(UInt64Enum))
return PrimitiveTypeCode.UInt64;
throw new ArgumentOutOfRangeException();
}
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.CodeDom;
using System.Reflection;
using Orleans.CodeGeneration;
namespace Orleans.Runtime
{
/// <summary>
/// A collection of utility functions for dealing with Type information.
/// </summary>
internal static class TypeUtils
{
private static string GetSimpleNameHandleArray(Type t, Language language)
{
if (t.IsArray && language == Language.VisualBasic)
return t.Name.Replace('[', '(').Replace(']', ')');
return t.Name;
}
public static string GetSimpleTypeName(Type t, Func<Type, bool> fullName=null, Language language = Language.CSharp)
{
if (t.IsNestedPublic || t.IsNestedPrivate)
{
if (t.DeclaringType.IsGenericType)
return GetTemplatedName(GetUntemplatedTypeName(t.DeclaringType.Name), t.DeclaringType, t.GetGenericArguments(), _ => true, language) + "." + GetUntemplatedTypeName(t.Name);
return GetTemplatedName(t.DeclaringType, language: language) + "." + GetUntemplatedTypeName(t.Name);
}
if (t.IsGenericType) return GetSimpleTypeName(fullName != null && fullName(t) ? GetFullName(t, language) : GetSimpleNameHandleArray(t, language));
return fullName != null && fullName(t) ? GetFullName(t, language) : GetSimpleNameHandleArray(t, language: language);
}
public static string GetUntemplatedTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static string GetSimpleTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('[');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static bool IsConcreteTemplateType(Type t)
{
if (t.IsGenericType) return true;
return t.IsArray && IsConcreteTemplateType(t.GetElementType());
}
public static string GetTemplatedName(Type t, Func<Type, bool> fullName=null, Language language = Language.CSharp)
{
if (t.IsGenericType) return GetTemplatedName(GetSimpleTypeName(t, fullName, language), t, t.GetGenericArguments(), fullName, language);
if (t.IsArray)
{
bool isVB = language == Language.VisualBasic;
return GetTemplatedName(t.GetElementType(), fullName)
+ (isVB ? "(" : "[")
+ new string(',', t.GetArrayRank() - 1)
+ (isVB ? ")" : "]");
}
return GetSimpleTypeName(t, fullName, language);
}
public static string GetTemplatedName(string baseName, Type t, Type[] genericArguments, Func<Type, bool> fullName, Language language = Language.CSharp)
{
if (!t.IsGenericType || (t.DeclaringType != null && t.DeclaringType.IsGenericType)) return baseName;
bool isVB = language == Language.VisualBasic;
string s = baseName;
s += isVB ? "(Of " : "<";
s += GetGenericTypeArgs(genericArguments, fullName, language);
s += isVB ? ")" : ">";
return s;
}
public static string GetGenericTypeArgs(Type[] args, Func<Type, bool> fullName, Language language = Language.CSharp)
{
string s = String.Empty;
bool first = true;
foreach (var genericParameter in args)
{
if (!first)
{
s += ",";
}
if (!genericParameter.IsGenericType)
{
s += GetSimpleTypeName(genericParameter, fullName, language);
}
else
{
s += GetTemplatedName(genericParameter, fullName, language);
}
first = false;
}
return s;
}
public static string GetParameterizedTemplateName(Type t, bool applyRecursively = false, Func<Type, bool> fullName = null, Language language = Language.CSharp)
{
if (fullName == null)
fullName = tt => false;
return GetParameterizedTemplateName(t, fullName, applyRecursively, language);
}
public static string GetParameterizedTemplateName(Type t, Func<Type, bool> fullName, bool applyRecursively = false, Language language = Language.CSharp)
{
if (t.IsGenericType)
{
return GetParameterizedTemplateName(GetSimpleTypeName(t, fullName), t, applyRecursively, fullName, language);
}
else
{
if(fullName != null && fullName(t)==true)
{
return t.FullName;
}
}
return t.Name;
}
public static string GetParameterizedTemplateName(string baseName, Type t, bool applyRecursively = false, Func<Type, bool> fullName = null, Language language = Language.CSharp)
{
if (fullName == null)
fullName = tt => false;
if (!t.IsGenericType) return baseName;
bool isVB = language == Language.VisualBasic;
string s = baseName;
s += isVB ? "(Of " : "<";
bool first = true;
foreach (var genericParameter in t.GetGenericArguments())
{
if (!first)
{
s += ",";
}
if (applyRecursively && genericParameter.IsGenericType)
{
s += GetParameterizedTemplateName(genericParameter, applyRecursively, language: language);
}
else
{
s += genericParameter.FullName == null || !fullName(genericParameter)
? genericParameter.Name
: genericParameter.FullName;
}
first = false;
}
s += isVB ? ")" : ">";
return s;
}
public static string GetRawClassName(string baseName, Type t)
{
return t.IsGenericType ? baseName + '`' + t.GetGenericArguments().Length : baseName;
}
public static string GetRawClassName(string typeName)
{
int i = typeName.IndexOf('[');
return i <= 0 ? typeName : typeName.Substring(0, i);
}
public static Type[] GenericTypeArgs(string className)
{
var typeArgs = new List<Type>();
var genericTypeDef = GenericTypeArgsString(className).Replace("[]", "##"); // protect array arguments
string[] genericArgs = genericTypeDef.Split('[', ']');
foreach (string genericArg in genericArgs)
{
string typeArg = genericArg.Trim('[', ']');
if (typeArg.Length > 0 && typeArg != ",")
typeArgs.Add(Type.GetType(typeArg.Replace("##", "[]"))); // restore array arguments
}
return typeArgs.ToArray();
}
public static string GenericTypeArgsString(string className)
{
int startIndex = className.IndexOf('[');
int endIndex = className.LastIndexOf(']');
return className.Substring(startIndex + 1, endIndex - startIndex - 1);
}
public static CodeTypeParameterCollection GenericTypeParameters(Type t)
{
if (!t.IsGenericType) return null;
var p = new CodeTypeParameterCollection();
foreach (var genericParameter in t.GetGenericTypeDefinition().GetGenericArguments())
{
var param = new CodeTypeParameter(genericParameter.Name);
if ((genericParameter.GenericParameterAttributes &
GenericParameterAttributes.ReferenceTypeConstraint) != GenericParameterAttributes.None)
{
param.Constraints.Add(" class");
}
if ((genericParameter.GenericParameterAttributes &
GenericParameterAttributes.NotNullableValueTypeConstraint) != GenericParameterAttributes.None)
{
param.Constraints.Add(" struct");
}
var constraints = genericParameter.GetGenericParameterConstraints();
foreach (var constraintType in constraints)
{
param.Constraints.Add(
new CodeTypeReference(TypeUtils.GetParameterizedTemplateName(constraintType, false,
x => true)));
}
if ((genericParameter.GenericParameterAttributes &
GenericParameterAttributes.DefaultConstructorConstraint) != GenericParameterAttributes.None)
{
param.HasConstructorConstraint = true;
}
p.Add(param);
}
return p;
}
public static bool IsGenericClass(string name)
{
return name.Contains("`") || name.Contains("[");
}
public static string GetFullName(Type t, Language language = Language.CSharp)
{
if (t == null) throw new ArgumentNullException("t");
if (t.IsNested && !t.IsGenericParameter)
{
return t.Namespace + "." + t.DeclaringType.Name + "." + GetSimpleNameHandleArray(t, language);
}
if (t.IsArray)
{
bool isVB = language == Language.VisualBasic;
return GetFullName(t.GetElementType(), language)
+ (isVB ? "(" : "[")
+ new string(',', t.GetArrayRank() - 1)
+ (isVB ? ")" : "]");
}
return t.FullName ?? ( t.IsGenericParameter ? GetSimpleNameHandleArray(t, language) : t.Namespace + "." + GetSimpleNameHandleArray(t, language));
}
/// <summary>
/// decide whether the class is derived from Grain
/// </summary>
public static bool IsGrainClass(Type type)
{
var grainType = typeof(Grain);
var grainChevronType = typeof(Grain<>);
if (type.Assembly.ReflectionOnly)
{
grainType = ToReflectionOnlyType(grainType);
grainChevronType = ToReflectionOnlyType(grainChevronType);
}
if (grainType == type || grainChevronType == type) return false;
if (!grainType.IsAssignableFrom(type)) return false;
// exclude generated classes.
return !IsGeneratedType(type);
}
public static bool IsSystemTargetClass(Type type)
{
Type systemTargetType;
if (!TryResolveType("Orleans.Runtime.SystemTarget", out systemTargetType)) return false;
var systemTargetInterfaceType = typeof(ISystemTarget);
var systemTargetBaseInterfaceType = typeof(ISystemTargetBase);
if (type.Assembly.ReflectionOnly)
{
systemTargetType = ToReflectionOnlyType(systemTargetType);
systemTargetInterfaceType = ToReflectionOnlyType(systemTargetInterfaceType);
systemTargetBaseInterfaceType = ToReflectionOnlyType(systemTargetBaseInterfaceType);
}
if (!systemTargetInterfaceType.IsAssignableFrom(type) ||
!systemTargetBaseInterfaceType.IsAssignableFrom(type) ||
!systemTargetType.IsAssignableFrom(type)) return false;
// exclude generated classes.
return !IsGeneratedType(type);
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints, bool complain)
{
complaints = null;
if (!IsGrainClass(type)) return false;
if (!type.IsAbstract) return true;
complaints = complain ? new[] { string.Format("Grain type {0} is abstract and cannot be instantiated.", type.FullName) } : null;
return false;
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints)
{
return IsConcreteGrainClass(type, out complaints, complain: true);
}
public static bool IsConcreteGrainClass(Type type)
{
IEnumerable<string> complaints;
return IsConcreteGrainClass(type, out complaints, complain: false);
}
public static bool IsGeneratedType(Type type)
{
return TypeHasAttribute(type, typeof(GeneratedAttribute));
}
public static bool IsGrainMethodInvokerType(Type type)
{
var generalType = typeof(IGrainMethodInvoker);
if (type.Assembly.ReflectionOnly)
{
generalType = ToReflectionOnlyType(generalType);
}
return generalType.IsAssignableFrom(type) && TypeHasAttribute(type, typeof(MethodInvokerAttribute));
}
public static bool IsGrainStateType(Type type)
{
var generalType = typeof(GrainState);
if (type.Assembly.ReflectionOnly)
{
generalType = ToReflectionOnlyType(generalType);
}
return generalType.IsAssignableFrom(type) && TypeHasAttribute(type, typeof(GrainStateAttribute));
}
public static Type ResolveType(string fullName)
{
return CachedTypeResolver.Instance.ResolveType(fullName);
}
public static bool TryResolveType(string fullName, out Type type)
{
return CachedTypeResolver.Instance.TryResolveType(fullName, out type);
}
public static Type ResolveReflectionOnlyType(string assemblyQualifiedName)
{
return CachedReflectionOnlyTypeResolver.Instance.ResolveType(assemblyQualifiedName);
}
public static Type ToReflectionOnlyType(Type type)
{
return type.Assembly.ReflectionOnly ? type : ResolveReflectionOnlyType(type.AssemblyQualifiedName);
}
public static IEnumerable<Type> GetTypes(Assembly assembly, Func<Type, bool> whereFunc)
{
return assembly.IsDynamic ? Enumerable.Empty<Type>() : assembly.GetTypes().Where(type => !type.IsNestedPrivate && whereFunc(type));
}
public static IEnumerable<Type> GetTypes(Func<Type, bool> whereFunc)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var result = new List<Type>();
foreach (var assembly in assemblies)
{
// there's no point in evaluating nested private types-- one of them fails to coerce to a reflection-only type anyhow.
var types = GetTypes(assembly, whereFunc);
result.AddRange(types);
}
return result;
}
public static IEnumerable<Type> GetTypes(List<string> assemblies, Func<Type, bool> whereFunc)
{
var currentAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var result = new List<Type>();
foreach (var assembly in currentAssemblies.Where(loaded => !loaded.IsDynamic && assemblies.Contains(loaded.Location)))
{
// there's no point in evaluating nested private types-- one of them fails to coerce to a reflection-only type anyhow.
var types = GetTypes(assembly, whereFunc);
result.AddRange(types);
}
return result;
}
public static bool TypeHasAttribute(Type type, Type attribType)
{
if (type.Assembly.ReflectionOnly || attribType.Assembly.ReflectionOnly)
{
type = ToReflectionOnlyType(type);
attribType = ToReflectionOnlyType(attribType);
}
// we can't use Type.GetCustomAttributes here because we could potentially be working with a reflection-only type.
return CustomAttributeData.GetCustomAttributes(type).Any(
attrib => attribType.IsAssignableFrom(attrib.AttributeType));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpSys.Internal;
namespace Microsoft.AspNetCore.Server.HttpSys
{
/// <summary>
/// A collection or URL prefixes
/// </summary>
public class UrlPrefixCollection : ICollection<UrlPrefix>
{
private readonly IDictionary<int, UrlPrefix> _prefixes = new Dictionary<int, UrlPrefix>(1);
private UrlGroup? _urlGroup;
private int _nextId = 1;
// Valid port range of 5000 - 48000.
private const int BasePort = 5000;
private const int MaxPortIndex = 43000;
private const int MaxRetries = 1000;
private static int NextPortIndex;
internal UrlPrefixCollection()
{
}
/// <inheritdoc />
public int Count
{
get
{
lock (_prefixes)
{
return _prefixes.Count;
}
}
}
/// <summary>
/// Gets a value that determines if this collection is readOnly.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Creates a <see cref="UrlPrefix"/> from the given string, and adds it to this collection.
/// </summary>
/// <param name="prefix">The string representing the <see cref="UrlPrefix"/> to add to this collection.</param>
public void Add(string prefix)
{
Add(UrlPrefix.Create(prefix));
}
/// <summary>
/// Adds a <see cref="UrlPrefix"/> to this collection.
/// </summary>
/// <param name="item">The prefix to add to this collection.</param>
public void Add(UrlPrefix item)
{
lock (_prefixes)
{
var id = _nextId++;
if (_urlGroup != null)
{
_urlGroup.RegisterPrefix(item.FullPrefix, id);
}
_prefixes.Add(id, item);
}
}
internal UrlPrefix? GetPrefix(int id)
{
lock (_prefixes)
{
return _prefixes.TryGetValue(id, out var prefix) ? prefix : null;
}
}
internal bool TryMatchLongestPrefix(bool isHttps, string host, string originalPath, [NotNullWhen(true)] out string? pathBase, [NotNullWhen(true)] out string? remainingPath)
{
var originalPathString = new PathString(originalPath);
var found = false;
pathBase = null;
remainingPath = null;
lock (_prefixes)
{
foreach (var prefix in _prefixes.Values)
{
// The scheme, host, port, and start of path must match.
// Note this does not currently handle prefixes with wildcard subdomains.
if (isHttps == prefix.IsHttps
&& string.Equals(host, prefix.HostAndPort, StringComparison.OrdinalIgnoreCase)
&& originalPathString.StartsWithSegments(new PathString(prefix.PathWithoutTrailingSlash), StringComparison.OrdinalIgnoreCase, out var remainder)
&& (!found || remainder.Value!.Length < remainingPath!.Length)) // Longest match
{
found = true;
pathBase = originalPath.Substring(0, prefix.PathWithoutTrailingSlash.Length); // Maintain the input casing
remainingPath = remainder.Value;
}
}
}
return found;
}
/// <inheritdoc />
public void Clear()
{
lock (_prefixes)
{
if (_urlGroup != null)
{
UnregisterAllPrefixes();
}
_prefixes.Clear();
}
}
/// <inheritdoc />
public bool Contains(UrlPrefix item)
{
lock (_prefixes)
{
return _prefixes.Values.Contains(item);
}
}
/// <inheritdoc />
public void CopyTo(UrlPrefix[] array, int arrayIndex)
{
lock (_prefixes)
{
_prefixes.Values.CopyTo(array, arrayIndex);
}
}
/// <inheritdoc />
public bool Remove(string prefix)
{
return Remove(UrlPrefix.Create(prefix));
}
/// <inheritdoc />
public bool Remove(UrlPrefix item)
{
lock (_prefixes)
{
int? id = null;
foreach (var pair in _prefixes)
{
if (pair.Value.Equals(item))
{
id = pair.Key;
if (_urlGroup != null)
{
_urlGroup.UnregisterPrefix(pair.Value.FullPrefix);
}
}
}
if (id.HasValue)
{
_prefixes.Remove(id.Value);
return true;
}
return false;
}
}
/// <summary>
/// Returns an enumerator that iterates through this collection.
/// </summary>
public IEnumerator<UrlPrefix> GetEnumerator()
{
lock (_prefixes)
{
return _prefixes.Values.GetEnumerator();
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
internal void RegisterAllPrefixes(UrlGroup urlGroup)
{
lock (_prefixes)
{
_urlGroup = urlGroup;
// go through the uri list and register for each one of them
// Call ToList to avoid modification when enumerating.
foreach (var pair in _prefixes.ToList())
{
var urlPrefix = pair.Value;
if (urlPrefix.PortValue == 0)
{
if (urlPrefix.IsHttps)
{
throw new InvalidOperationException("Cannot bind to port 0 with https.");
}
FindHttpPortUnsynchronized(pair.Key, urlPrefix);
}
else
{
// We'll get this index back on each request and use it to look up the prefix to calculate PathBase.
_urlGroup.RegisterPrefix(pair.Value.FullPrefix, pair.Key);
}
}
}
}
private void FindHttpPortUnsynchronized(int key, UrlPrefix urlPrefix)
{
Debug.Assert(_urlGroup != null);
for (var index = 0; index < MaxRetries; index++)
{
try
{
// Bit of complicated math to always try 3000 ports, starting from NextPortIndex + 5000,
// circling back around if we go above 8000 back to 5000, and so on.
var port = ((index + NextPortIndex) % MaxPortIndex) + BasePort;
Debug.Assert(port >= 5000 || port < 8000);
var newPrefix = UrlPrefix.Create(urlPrefix.Scheme, urlPrefix.Host, port, urlPrefix.Path);
_urlGroup.RegisterPrefix(newPrefix.FullPrefix, key);
_prefixes[key] = newPrefix;
NextPortIndex += index + 1;
return;
}
catch (HttpSysException ex)
{
if ((ex.ErrorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_ACCESS_DENIED
&& ex.ErrorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SHARING_VIOLATION
&& ex.ErrorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_ALREADY_EXISTS) || index == MaxRetries - 1)
{
throw;
}
}
}
}
internal void UnregisterAllPrefixes()
{
lock (_prefixes)
{
if (_urlGroup == null)
{
return;
}
// go through the uri list and unregister for each one of them
foreach (var prefix in _prefixes.Values)
{
// ignore possible failures
_urlGroup.UnregisterPrefix(prefix.FullPrefix);
}
}
}
}
}
| |
//
// ExtensionNodeSchemaItem.cs
//
// Author:
// Mikayla Hutchinson <m.j.hutchinson@gmail.com>
//
// Copyright (c) 2015 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Addins.Description;
using MonoDevelop.Ide.CodeCompletion;
using MonoDevelop.Xml.Dom;
namespace MonoDevelop.AddinMaker.Editor.ManifestSchema
{
class ExtensionNodeElement : SchemaElement
{
readonly AddinProjectFlavor proj;
readonly ExtensionNodeType info;
readonly ExtensionPoint extensionPoint;
public ExtensionNodeElement (AddinProjectFlavor proj, ExtensionPoint extensionPoint, ExtensionNodeType info) : base (info.NodeName, info.Description)
{
this.proj = proj;
this.extensionPoint = extensionPoint;
this.info = info;
}
public override void GetAttributeCompletions (CompletionDataList list, IAttributedXObject attributedOb, Dictionary<string, string> existingAtts)
{
var required = new NodeCompletionCategory ("Required", 0);
var optional = new NodeCompletionCategory ("Optional", 1);
foreach (NodeTypeAttribute att in info.Attributes) {
if (!existingAtts.ContainsKey (att.Name)) {
var data = new NodeTypeAttributeCompletionData (att) {
CompletionCategory = att.Required ? required : optional
};
list.Add (data);
}
}
var ordering = new NodeCompletionCategory ("Ordering", 2);
if (!existingAtts.ContainsKey ("id")) {
list.Add (new CompletionData ("id", null, "ID for the extension, unique in this extension point.") { CompletionCategory = ordering });
}
if (!existingAtts.ContainsKey ("insertbefore")) {
list.Add (new CompletionData ("insertbefore", null, "ID of an existing extension before which to insert this.") { CompletionCategory = ordering });
}
if (!existingAtts.ContainsKey ("insertafter")) {
list.Add (new CompletionData ("insertafter", null, "ID of an existing extension after which to insert this.") { CompletionCategory = ordering });
}
}
public override SchemaElement GetChild (XElement element)
{
var node = info.GetAllowedNodeTypes ().FirstOrDefault (n => n.NodeName == element.Name.FullName);
if (node != null) {
return new ExtensionNodeElement (proj, extensionPoint, node);
}
return null;
}
public override void GetElementCompletions (CompletionDataList list, XElement element)
{
foreach (ExtensionNodeType n in info.GetAllowedNodeTypes ()) {
list.Add (n.NodeName, null, n.Description);
}
}
internal static IEnumerable<Extension> GetExtensions (AddinProjectFlavor project, ExtensionPoint extensionPoint)
{
//TODO: handle node sets
foreach (var addin in extensionPoint.ExtenderAddins) {
var modules = project.AddinRegistry.GetAddin (addin).Description.AllModules;
foreach (ModuleDescription module in modules) {
foreach (Extension extension in module.Extensions) {
if (extension.Path == extensionPoint.Path)
yield return extension;
}
}
}
}
public override void GetAttributeValueCompletions (CompletionDataList list, IAttributedXObject attributedOb, XAttribute att)
{
var name = att.Name.FullName;
if (name == "insertbefore" || name == "insertafter") {
//TODO: conditions, children
foreach (var ext in GetExtensions (proj, extensionPoint)) {
foreach (ExtensionNodeDescription node in ext.ExtensionNodes) {
if (!string.IsNullOrEmpty (node.Id)) {
list.Add (node.Id, null, "From " + node.ParentAddinDescription.AddinId);
}
}
}
}
}
class NodeCompletionCategory : CompletionCategory
{
readonly int weight;
public NodeCompletionCategory (string label, int weight)
{
DisplayText = label;
this.weight = weight;
}
public override int CompareTo (CompletionCategory other)
{
var n = other as NodeCompletionCategory;
if (n != null)
return weight - n.weight;
return string.Compare (DisplayText, other.DisplayText, StringComparison.Ordinal);
}
}
class NodeTypeAttributeCompletionData : CompletionData
{
readonly NodeTypeAttribute att;
string markup;
public NodeTypeAttributeCompletionData (NodeTypeAttribute att)
{
this.att = att;
}
public override string DisplayText {
get { return att.Name; }
set { throw new NotSupportedException (); }
}
public override string Description {
get { return markup ?? (markup = GenerateDescriptionMarkup ()); }
set { throw new NotSupportedException (); }
}
public override string CompletionText {
get { return att.Name; }
set { throw new NotSupportedException (); }
}
public override DisplayFlags DisplayFlags {
get {
var flags = DisplayFlags.DescriptionHasMarkup;
if (att.Required) {
flags |= DisplayFlags.MarkedBold;
}
return flags;
}
set { throw new NotSupportedException (); }
}
string GenerateDescriptionMarkup ()
{
var sb = new StringBuilder ();
sb.AppendFormat ("{0}", GLib.Markup.EscapeText (att.Name));
sb.AppendLine ();
if (att.Required) {
sb.AppendLine ("<b>Required</b>");
}
switch (att.ContentType) {
case Mono.Addins.ContentType.Text:
if (att.Localizable) {
sb.AppendLine ("<i>Localizable</i>");
}
break;
case Mono.Addins.ContentType.Class:
sb.Append ("<i>Type");
if (string.IsNullOrEmpty (att.Type)) {
sb.Append (": ");
sb.Append (GLib.Markup.EscapeText (att.Type));
}
sb.AppendLine ("</i>");
break;
case Mono.Addins.ContentType.Resource:
sb.AppendLine ("<i>Resource</i>");
break;
case Mono.Addins.ContentType.File:
sb.AppendLine ("<i>File</i>");
break;
}
if (string.IsNullOrEmpty (att.Description)) {
return sb.ToString ();
}
sb.AppendLine ();
sb.AppendLine (GLib.Markup.EscapeText (att.Description));
return sb.ToString ();
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Nini.Config;
using log4net;
using System.Reflection;
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Collections.Generic;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using Mono.Addins;
namespace OpenSim.Server
{
public class OpenSimServer
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
protected static HttpServerBase m_Server = null;
protected static List<IServiceConnector> m_ServiceConnectors =
new List<IServiceConnector>();
protected static PluginLoader loader;
private static bool m_NoVerifyCertChain = false;
private static bool m_NoVerifyCertHostname = false;
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (m_NoVerifyCertChain)
sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
if (m_NoVerifyCertHostname)
sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNameMismatch;
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
return false;
}
public static int Main(string[] args)
{
Culture.SetCurrentCulture();
Culture.SetDefaultCurrentCulture();
ServicePointManager.DefaultConnectionLimit = 64;
ServicePointManager.Expect100Continue = false;
ServicePointManager.UseNagleAlgorithm = false;
ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
try { ServicePointManager.DnsRefreshTimeout = 300000; } catch { }
m_Server = new HttpServerBase("R.O.B.U.S.T.", args);
string registryLocation;
IConfig serverConfig = m_Server.Config.Configs["Startup"];
if (serverConfig == null)
{
System.Console.WriteLine("Startup config section missing in .ini file");
throw new Exception("Configuration error");
}
m_NoVerifyCertChain = serverConfig.GetBoolean("NoVerifyCertChain", m_NoVerifyCertChain);
m_NoVerifyCertHostname = serverConfig.GetBoolean("NoVerifyCertHostname", m_NoVerifyCertHostname);
string connList = serverConfig.GetString("ServiceConnectors", String.Empty);
registryLocation = serverConfig.GetString("RegistryLocation",".");
IConfig servicesConfig = m_Server.Config.Configs["ServiceList"];
if (servicesConfig != null)
{
List<string> servicesList = new List<string>();
if (connList != String.Empty)
servicesList.Add(connList);
foreach (string k in servicesConfig.GetKeys())
{
string v = servicesConfig.GetString(k);
if (v != String.Empty)
servicesList.Add(v);
}
connList = String.Join(",", servicesList.ToArray());
}
string[] conns = connList.Split(new char[] {',', ' ', '\n', '\r', '\t'});
// int i = 0;
foreach (string c in conns)
{
if (c == String.Empty)
continue;
string configName = String.Empty;
string conn = c;
uint port = 0;
string[] split1 = conn.Split(new char[] {'/'});
if (split1.Length > 1)
{
conn = split1[1];
string[] split2 = split1[0].Split(new char[] {'@'});
if (split2.Length > 1)
{
configName = split2[0];
port = Convert.ToUInt32(split2[1]);
}
else
{
port = Convert.ToUInt32(split1[0]);
}
}
string[] parts = conn.Split(new char[] {':'});
string friendlyName = parts[0];
if (parts.Length > 1)
friendlyName = parts[1];
IHttpServer server;
if (port != 0)
server = MainServer.GetHttpServer(port);
else
server = MainServer.Instance;
m_log.InfoFormat("[SERVER]: Loading {0} on port {1}", friendlyName, server.Port);
IServiceConnector connector = null;
Object[] modargs = new Object[] { m_Server.Config, server, configName };
connector = ServerUtils.LoadPlugin<IServiceConnector>(conn, modargs);
if (connector == null)
{
modargs = new Object[] { m_Server.Config, server };
connector = ServerUtils.LoadPlugin<IServiceConnector>(conn, modargs);
}
if (connector != null)
{
m_ServiceConnectors.Add(connector);
m_log.InfoFormat("[SERVER]: {0} loaded successfully", friendlyName);
}
else
{
m_log.ErrorFormat("[SERVER]: Failed to load {0}", conn);
}
}
loader = new PluginLoader(m_Server.Config, registryLocation);
int res = m_Server.Run();
if(m_Server != null)
m_Server.Shutdown();
Util.StopThreadPool();
Environment.Exit(res);
return 0;
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using NUnit.Framework;
using MooGet;
namespace MooGet.Specs.Core {
/// <summary>Testing the core implementation of MooDir. 1 [Test] for each ISource method (to start with)</summary>
[TestFixture]
public class MooDirSpec : Spec {
MooDir dir;
DirectoryOfNupkg morePackages = new DirectoryOfNupkg(PathToContent("more_packages"));
DirectoryOfNupkg morePackageDependencies = new DirectoryOfNupkg(PathToContent("more_packages_dependencies"));
[SetUp]
public void Before() {
base.BeforeEach();
dir = new MooDir(PathToTemp("MyMooDir"));
dir.Initialize();
}
[Test]
public void can_initialize() {
var mooDir = new MooDir(PathToTemp("FooBar"));
PathToTemp("FooBar").AsDir().Exists().Should(Be.False);
mooDir.Initialize();
PathToTemp("FooBar" ).AsDir().Exists().Should(Be.True);
PathToTemp("FooBar", "packages" ).AsDir().Exists().Should(Be.True); // unpacked packages go here
PathToTemp("FooBar", "cache" ).AsDir().Exists().Should(Be.True); // .nupkg's are cached here
PathToTemp("FooBar", "bin" ).AsDir().Exists().Should(Be.True); // this should be added to the user's PATH to run tools
mooDir.PackageDirectory.ShouldEqual(PathToTemp("FooBar", "packages"));
mooDir.CacheDirectory.ShouldEqual(PathToTemp("FooBar", "cache"));
mooDir.BinDirectory.ShouldEqual(PathToTemp("FooBar", "bin"));
}
[Test]
public void can_have_a_Name() {
new MooDir { Name = "MySource" }.Name.ShouldEqual("MySource");
}
[Test]
public void can_set_Path() {
new MooDir("/").Path.ShouldEqual("/");
new MooDir { Path = "/" }.Path.ShouldEqual("/");
}
[Test]
public void can_have_AuthData() {
new MooDir { AuthData = 5 }.AuthData.ShouldEqual(5);
}
// [Test][Ignore]
// public void Get() {
// dir.Get(new PackageDependency("MarkdownSharp")).Should(Be.Null);
// dir.Get(new PackageDependency("NUnit")).Should(Be.Null);
// dir.Push(new Nupkg(PathToContent("packages/NUnit.2.5.7.10213.nupkg")));
// dir.Get(new PackageDependency("MarkdownSharp")).Should(Be.Null);
// var nunit = dir.Get(new PackageDependency("NUnit"));
// nunit.ShouldNot(Be.Null);
// nunit.Id.ShouldEqual("NUnit");
// nunit.Version.ToString().ShouldEqual("2.5.7.10213");
// }
[Test]
public void Packages() {
dir.Packages.Should(Be.Empty);
// if we copy an UnpackedPackage into our PackageDirectory, it should show up!
Path.Combine(dir.PackageDirectory, "MarkdownSharp.1.13.0.0").AsDir().Exists().Should(Be.False);
new UnpackedNupkg(PathToContent("packages/MarkdownSharp.1.13.0.0")).Copy(dir.PackageDirectory);
Path.Combine(dir.PackageDirectory, "MarkdownSharp.1.13.0.0").AsDir().Exists().Should(Be.True);
dir.Packages.Count.ShouldEqual(1);
var package = dir.Packages.First();
package.Id.ShouldEqual("MarkdownSharp");
package.Should(Be.InstanceOf(typeof(MooDirPackage)));
(package as MooDirPackage).Unpacked.Should(Be.InstanceOf(typeof(UnpackedNupkg)));
(package as MooDirPackage).Unpacked.Path.ShouldEqual(Path.Combine(dir.PackageDirectory, "MarkdownSharp.1.13.0.0"));
(package as MooDirPackage).Nupkg.Should(Be.Null);
// if we put the cached nupkg where it's supposed to be, we should see it ...
Path.Combine(dir.CacheDirectory, "MarkdownSharp.1.13.0.0.nupkg").AsFile().Exists().Should(Be.False);
new Nupkg(PathToContent("packages/MarkdownSharp.1.13.0.0.nupkg")).Copy(dir.CacheDirectory);
Path.Combine(dir.CacheDirectory, "MarkdownSharp.1.13.0.0.nupkg").AsFile().Exists().Should(Be.True);
package = dir.Packages.First();
package.Id.ShouldEqual("MarkdownSharp");
package.Should(Be.InstanceOf(typeof(MooDirPackage)));
(package as MooDirPackage).Unpacked.Should(Be.InstanceOf(typeof(UnpackedNupkg)));
(package as MooDirPackage).Unpacked.Path.ShouldEqual(Path.Combine(dir.PackageDirectory, "MarkdownSharp.1.13.0.0"));
(package as MooDirPackage).Nupkg.Should(Be.InstanceOf(typeof(Nupkg)));
(package as MooDirPackage).Nupkg.Path.ShouldEqual(Path.Combine(dir.CacheDirectory, "MarkdownSharp.1.13.0.0.nupkg"));
}
// [Test][Ignore]
// public void LatestPackages() {
// morePackages.GetPackagesWithId("NuGet.CommandLine").Select(p => p.Version.ToString()).ToList().Join(", ").
// ShouldEqual("1.0.11220.26, 1.1.2120.134, 1.1.2120.136");
// morePackages.LatestPackages.Where(p => p.Id == "NuGet.CommandLine").Select(p => p.Version.ToString()).ToList().Join(", ").
// ShouldEqual("1.1.2120.136");
// }
// /// <summary>This tests an external extension method supporting any List of Package</summary>
// [Test][Ignore]
// public void Packages_Latest() {
// }
// /// <summary>This tests an external extension method supporting any List of Package</summary>
// [Test][Ignore]
// public void Packages_GroupByVersion() {
// }
// [Test][Ignore]
// public void GetPackagesWithId() {
// morePackages.GetPackagesWithId("NUnit").Ids().ShouldEqual(new List<string>{ });
// morePackages.GetPackagesWithId("Antlr").Ids().ShouldEqual(new List<string>{ "Antlr" });
// morePackages.GetPackagesWithId("NuGet.CommandLine").Ids().ShouldEqual(new List<string>{ "NuGet.CommandLine", "NuGet.CommandLine", "NuGet.CommandLine" });
// }
// [Test][Ignore]
// public void GetPackagesWithIdStartingWith() {
// morePackages.GetPackagesWithIdStartingWith("zzz").Ids().ShouldEqual(new List<string>{ });
// morePackages.GetPackagesWithIdStartingWith("A").Ids().ShouldEqual(new List<string>{ "Antlr", "Apache.NMS", "Apache.NMS.ActiveMQ", "AttributeRouting" });
// morePackages.GetPackagesWithIdStartingWith("ap").Ids().ShouldEqual(new List<string>{ "Apache.NMS", "Apache.NMS.ActiveMQ" });
// }
// [Test][Ignore]
// public void GetPackagesMatchingDependencies() {
// morePackages.GetPackagesMatchingDependencies(new PackageDependency("NUnit")).Should(Be.Empty);
// morePackages.GetPackagesMatchingDependencies(new PackageDependency("Antlr")).Count.ShouldEqual(1);
// morePackages.GetPackagesMatchingDependencies(new PackageDependency("NuGet.CommandLine")).Count.ShouldEqual(3);
// morePackages.GetPackagesMatchingDependencies(new PackageDependency("NuGet.CommandLine >= 1.1")).Count.ShouldEqual(2);
// var matches = morePackages.GetPackagesMatchingDependencies(new PackageDependency("NuGet.CommandLine >= 1.1"), new PackageDependency("NuGet.CommandLine < 1.1.2120.135"));
// matches.Count.ShouldEqual(1);
// matches.First().IdAndVersion().ShouldEqual("NuGet.CommandLine-1.1.2120.134");
// }
[Test]
public void Fetch() {
dir.Push(new Nupkg(PathToContent("package_working_directories/just-a-tool-1.0.0.0.nupkg")));
dir.Packages.Count.ShouldEqual(1);
Directory.CreateDirectory(PathToTemp("nupkgs"));
PathToTemp("nupkgs", "just-a-tool-1.0.0.0.nupkg").AsFile().Exists().Should(Be.False);
var nupkg = dir.Fetch(new PackageDependency("just-a-tool"), PathToTemp("nupkgs"));
nupkg.Path.ShouldEqual(PathToTemp("nupkgs", "just-a-tool-1.0.0.0.nupkg"));
PathToTemp("nupkgs", "just-a-tool-1.0.0.0.nupkg").AsFile().Exists().Should(Be.True);
}
[Test]
public void Push() {
dir.Packages.Should(Be.Empty);
var pkg = dir.Push(new Nupkg(PathToContent("packages/MarkdownSharp.1.13.0.0.nupkg")));
// check the IPackage that we get back
pkg.Should(Be.InstanceOf(typeof(MooDirPackage)));
pkg.Id.ShouldEqual("MarkdownSharp");
pkg.Source.ShouldEqual(dir);
(pkg as MooDirPackage).Nupkg.Path.ShouldEqual(Path.Combine(dir.CacheDirectory, "MarkdownSharp-1.13.0.0.nupkg"));
(pkg as MooDirPackage).Unpacked.Path.ShouldEqual(Path.Combine(dir.PackageDirectory, "MarkdownSharp-1.13.0.0"));
dir.Packages.Count.ShouldEqual(1);
dir.Packages.First().Id.ShouldEqual("MarkdownSharp");
dir.BinDirectory.AsDir().Files().Count.ShouldEqual(0);
dir.Push(new Nupkg(PathToContent("package_working_directories/just-a-tool-1.0.0.0.nupkg")));
dir.Packages.Count.ShouldEqual(2);
dir.Packages.Ids().ShouldEqual(new List<string>{ "MarkdownSharp", "just-a-tool" });
dir.BinDirectory.AsDir().Files().Count.ShouldEqual(2); // tool.exe should have a 'tool' script and a 'tool.bat' script
dir.BinDirectory.AsDir().Files().Select(f => f.Name()).ToList().ShouldEqual(new List<string>{ "tool", "tool.bat" });
}
[Test]
public void Yank() {
dir.Packages.Count.ShouldEqual(0);
dir.Cache.Packages.Count.ShouldEqual(0);
dir.BinDirectory.AsDir().Files().Count.ShouldEqual(0);
dir.Push(new Nupkg(PathToContent("package_working_directories/just-a-tool-1.0.0.0.nupkg")));
dir.Push(new Nupkg(PathToContent("packages/MarkdownSharp.1.13.0.0.nupkg")));
dir.Packages.Ids().ShouldEqual(new List<string>{ "MarkdownSharp", "just-a-tool" });
dir.Packages.Count.ShouldEqual(2);
dir.Cache.Packages.Count.ShouldEqual(2);
dir.BinDirectory.AsDir().Files().Count.ShouldEqual(2); // tool.exe should have a 'tool' script and a 'tool.bat' script
dir.Yank(new PackageDependency("DontExist")).ShouldBeFalse();
dir.Packages.Ids().ShouldEqual(new List<string>{ "MarkdownSharp", "just-a-tool" });
dir.Packages.Count.ShouldEqual(2);
dir.Cache.Packages.Count.ShouldEqual(2);
dir.Yank(new PackageDependency("MarkdownSharp")).ShouldBeTrue();
dir.Packages.Ids().ShouldEqual(new List<string>{ "just-a-tool" });
dir.Packages.Count.ShouldEqual(1);
dir.Cache.Packages.Count.ShouldEqual(2); // we keep the cache
dir.BinDirectory.AsDir().Files().Count.ShouldEqual(2); // tool.exe binaries should still be there
dir.Yank(new PackageDependency("just-a-tool")).ShouldBeTrue();
dir.Packages.Should(Be.Empty);
dir.Packages.Count.ShouldEqual(0);
dir.Cache.Packages.Count.ShouldEqual(2); // we keep the cache
dir.BinDirectory.AsDir().Files().Count.ShouldEqual(0); // tool.exe binaries should have been removed when we yanked just-a-tool
}
[Test]
public void Install() {
Directory.CreateDirectory(PathToTemp("mydir"));
var mydir = new MooDir(PathToTemp("mydir")).Initialize();
mydir.Packages.Should(Be.Empty);
// if we don't provide any sources, it can't find the package we're talking about ...
Should.Throw<PackageNotFoundException>("Package not found: FluentNHibernate", () => {
mydir.Install(new PackageDependency("FluentNHibernate"));
});
// we find the package we're talking about, but we're missing one of the dependencies
Should.Throw<MissingDependencyException>("No packages were found that satisfy these dependencies: Iesi.Collections >= 1.0.1, Castle.DynamicProxy >= 2.1.0", () => {
mydir.Install(new PackageDependency("FluentNHibernate"), morePackages);
});
mydir.Packages.Should(Be.Empty);
// check the dependencies that we're going to install (assuming Install() calls FindDependencies)
var dependencies = Source.FindDependencies(morePackages.Get(new PackageDependency("FluentNHibernate")), morePackages, morePackageDependencies);
dependencies.Count.ShouldEqual(6);
dependencies.Select(pkg => pkg.IdAndVersion()).ToList().ShouldContainAll(
"NHibernate-2.1.2.4000", "log4net-1.2.10", "Iesi.Collections-1.0.1", "Antlr-3.1.1",
"Castle.DynamicProxy-2.1.0", "Castle.Core-1.1.0", "log4net-1.2.10"
);
// Inspect their sources to see that some come from 1, some come from another
dependencies.First(d => d.Id == "NHibernate").Source.ShouldEqual(morePackages);
dependencies.First(d => d.Id == "log4net").Source.ShouldEqual(morePackages);
dependencies.First(d => d.Id == "Antlr").Source.ShouldEqual(morePackages);
dependencies.First(d => d.Id == "Castle.Core").Source.ShouldEqual(morePackages);
dependencies.First(d => d.Id == "Iesi.Collections").Source.ShouldEqual(morePackageDependencies);
dependencies.First(d => d.Id == "Castle.DynamicProxy").Source.ShouldEqual(morePackageDependencies);
mydir.Install(new PackageDependency("FluentNHibernate"), morePackages, morePackageDependencies);
mydir.Packages.Count.ShouldEqual(7);
mydir.Packages.Select(pkg => pkg.IdAndVersion()).ToList().ShouldContainAll(
"NHibernate-2.1.2.4000", "log4net-1.2.10", "Iesi.Collections-1.0.1", "Antlr-3.1.1",
"Castle.DynamicProxy-2.1.0", "Castle.Core-1.1.0", "FluentNHibernate-1.1.0.694"
);
}
[Test]
public void Uninstall_without_dependencies() {
Directory.CreateDirectory(PathToTemp("mydir"));
var mydir = new MooDir(PathToTemp("mydir")).Initialize();
mydir.Install(new PackageDependency("FluentNHibernate"), morePackages, morePackageDependencies);
mydir.Packages.Count.ShouldEqual(7);
mydir.Packages.Select(pkg => pkg.IdAndVersion()).ToList().ShouldContainAll(
"NHibernate-2.1.2.4000", "log4net-1.2.10", "Iesi.Collections-1.0.1", "Antlr-3.1.1",
"Castle.DynamicProxy-2.1.0", "Castle.Core-1.1.0", "FluentNHibernate-1.1.0.694"
);
mydir.Uninstall(new PackageDependency("FluentNHibernate"), false).Should(Be.True);
mydir.Packages.Count.ShouldEqual(6);
mydir.Packages.Select(pkg => pkg.IdAndVersion()).ToList().ShouldContainAll(
"NHibernate-2.1.2.4000", "log4net-1.2.10", "Iesi.Collections-1.0.1", "Antlr-3.1.1",
"Castle.DynamicProxy-2.1.0", "Castle.Core-1.1.0"
);
mydir.Uninstall(new PackageDependency("FluentNHibernate"), false).Should(Be.False);
mydir.Packages.Count.ShouldEqual(6);
}
[Test]
public void Uninstall_with_dependencies() {
Directory.CreateDirectory(PathToTemp("mydir"));
var mydir = new MooDir(PathToTemp("mydir")).Initialize();
mydir.Install(new PackageDependency("FluentNHibernate"), morePackages, morePackageDependencies);
mydir.Packages.Count.ShouldEqual(7);
mydir.Packages.Select(pkg => pkg.IdAndVersion()).ToList().ShouldContainAll(
"NHibernate-2.1.2.4000", "log4net-1.2.10", "Iesi.Collections-1.0.1", "Antlr-3.1.1",
"Castle.DynamicProxy-2.1.0", "Castle.Core-1.1.0", "FluentNHibernate-1.1.0.694"
);
mydir.Uninstall(new PackageDependency("FluentNHibernate"), true).Should(Be.True);
mydir.Packages.Count.ShouldEqual(0);
mydir.Uninstall(new PackageDependency("FluentNHibernate"), true).Should(Be.False);
mydir.Packages.Count.ShouldEqual(0);
}
[Test]
public void Can_add_sources() {
Directory.CreateDirectory(PathToTemp("mydir"));
var mydir = new MooDir(PathToTemp("mydir")).Initialize();
// default has no sources (currently)
mydir.SourceFile.Exists().Should(Be.True); // there should be a template, but no sources
mydir.SourceFile.Read().ShouldContain("MooGet"); // should should be some text (commented out)
mydir.SourceFile.Sources.Count.ShouldEqual(0);
mydir.Sources.Count.ShouldEqual(0);
// add a source by adding to the file's text [example with name]
//mydir.SourceFile.AppendLine("Cool Source " + PathToContent("packages"));
mydir.SourceFile.Add("Cool Source", PathToContent("packages"));
mydir.Sources.Count.ShouldEqual(1);
mydir.Sources.First().Name.ShouldEqual("Cool Source");
mydir.Sources.First().Path.ShouldEqual(PathToContent("packages"));
mydir.Sources.First().Should(Be.InstanceOf(typeof(DirectoryOfNupkg)));
// add a source by adding to the file's text [example without name]
//mydir.SourceFile.AppendLine(PathToContent("more_packages"));
mydir.SourceFile.Add(PathToContent("more_packages"));
mydir.Sources.Count.ShouldEqual(2);
mydir.Sources.First().Name.ShouldEqual("Cool Source");
mydir.Sources.First().Path.ShouldEqual(PathToContent("packages"));
mydir.Sources.First().Should(Be.InstanceOf(typeof(DirectoryOfNupkg)));
mydir.Sources.Last().Name.Should(Be.Null);
mydir.Sources.Last().Path.ShouldEqual(PathToContent("more_packages"));
mydir.Sources.Last().Should(Be.InstanceOf(typeof(DirectoryOfNupkg)));
mydir.SourceFile.Read().ShouldContain("MooGet"); // this should still be in the file
}
[Test]
public void Can_remove_sources() {
Directory.CreateDirectory(PathToTemp("mydir"));
var mydir = new MooDir(PathToTemp("mydir")).Initialize();
mydir.SourceFile.Add("Cool Source", PathToContent("packages"));
mydir.SourceFile.Add(PathToContent("more_packages"));
mydir.Sources.Count.ShouldEqual(2);
// remove by name
mydir.SourceFile.Remove("Cool Source");
mydir.Sources.Count.ShouldEqual(1);
mydir.Sources.First().Path.ShouldEqual(PathToContent("more_packages"));
// remove by path
mydir.SourceFile.Remove(PathToContent("more_packages"));
mydir.Sources.Count.ShouldEqual(0);
}
// Once we re-implement this source
[Test][Ignore]
public void Has_the_official_NuGet_repository_as_a_default_source() {
}
}
}
| |
using NetApp.Tests.Helpers;
using Microsoft.Azure.Management.NetApp;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using Xunit;
using System;
using System.Collections.Generic;
using Microsoft.Azure.Management.NetApp.Models;
using Microsoft.Rest.Azure;
using Newtonsoft.Json;
using System.Threading;
namespace NetApp.Tests.ResourceTests
{
public class ANFBackupPolicyTests : TestBase
{
private const int delay = 5000;
[Fact]
public void CreateDeleteBackupPolicy()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
//create account
ResourceUtils.CreateAccount(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName: ResourceUtils.volumeBackupAccountName1);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
// create the backupPolicy
var backupPolicy = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName1);
var backupPoliciesBefore = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, backupPolicy);
// check backupPolicy exists
var backupPolciesBefore = netAppMgmtClient.BackupPolicies.List(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1);
Assert.Single(backupPolciesBefore);
var resultBackupPolicy = netAppMgmtClient.BackupPolicies.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1);
Assert.Equal($"{ResourceUtils.volumeBackupAccountName1}/{ResourceUtils.backupPolicyName1}", resultBackupPolicy.Name);
// delete the backupPolicy and check again
netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
var backupPoliciesAfter = netAppMgmtClient.BackupPolicies.List(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1);
Assert.Empty(backupPoliciesAfter);
// cleanup - remove the resources
netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1);
ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1);
}
}
[Fact]
public void ListBackupPolices()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
ResourceUtils.CreateAccount(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName: ResourceUtils.volumeBackupAccountName1);
// create two backupPolicies under same account
var backupPolicy1 = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName1);
var backupPolicy2 = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName2);
var resultbackupPolicy1 = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, backupPolicy1);
var resultbackupPolicy2 = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName2, backupPolicy2);
// get the backupPolicy list and check
var backupPolicies = netAppMgmtClient.BackupPolicies.List(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1);
Assert.Equal($"{ResourceUtils.volumeBackupAccountName1}/{ResourceUtils.backupPolicyName1}", backupPolicies.ElementAt(0).Name );
Assert.Equal($"{ResourceUtils.volumeBackupAccountName1}/{ResourceUtils.backupPolicyName2}", backupPolicies.ElementAt(1).Name);
Assert.Equal(2, backupPolicies.Count());
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
// clean up
netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1);
netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName2);
ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1);
}
}
[Fact]
public void GetBackupPolicyByName()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
//Create account
ResourceUtils.CreateAccount(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName: ResourceUtils.volumeBackupAccountName1);
var backupPolicy = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName1);
// create the backupPolicy
var createBackupPolicy = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, backupPolicy);
var resultBackupPolicy = netAppMgmtClient.BackupPolicies.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1);
Assert.Equal($"{ResourceUtils.volumeBackupAccountName1}/{ResourceUtils.backupPolicyName1}", resultBackupPolicy.Name);
Assert.Equal(createBackupPolicy.Name, resultBackupPolicy.Name);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
// cleanup - remove the resources
netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1);
ResourceUtils.DeletePool(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1);
ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1);
}
}
//[Fact(Skip ="Backups are not fully supported here")]
[Fact]
public void CreateVolumeWithBackupPolicy()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the Pool and account
ResourceUtils.CreatePool(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1, location: ResourceUtils.backupLocation);
// create the backupPolicy
var backupPolicy = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName1);
var createBackupPolicy = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, backupPolicy);
//Get vault
var vaultsList = netAppMgmtClient.Vaults.List(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1);
Assert.NotEmpty(vaultsList);
string vaultID = vaultsList.ElementAt(0).Id;
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
// Create volume
//var createVolume = ResourceUtils.CreateBackedupVolume(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName:ResourceUtils.volumeBackupAccountName1, vnet: ResourceUtils.backupVnet, backupPolicyId: null, backupVaultId: vaultID);
var createVolume = ResourceUtils.CreateVolume(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName: ResourceUtils.volumeBackupAccountName1, volumeName: ResourceUtils.backupVolumeName1, vnet: ResourceUtils.backupVnet);
Assert.Equal("Succeeded", createVolume.ProvisioningState);
//Get volume and check
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
var createGetVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1);
Assert.Equal("Succeeded", createGetVolume.ProvisioningState);
// Now try and modify the backuppolicy
var patchBackupPolicy = new BackupPolicyPatch()
{
DailyBackupsToKeep = 1
};
var resultbackupPolicy = netAppMgmtClient.BackupPolicies.Update(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, patchBackupPolicy);
//check volume again
createGetVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1);
Assert.Equal("Succeeded", createGetVolume.ProvisioningState);
// Now try and set dataprotection on the volume
var dataProtection = new VolumePatchPropertiesDataProtection
{
Backup = new VolumeBackupProperties {PolicyEnforced = true, BackupEnabled = true, BackupPolicyId = createBackupPolicy.Id, VaultId = vaultID }
};
var volumePatch = new VolumePatch()
{
DataProtection = dataProtection
};
// patch and enable backups
var updatedVolume = netAppMgmtClient.Volumes.Update(volumePatch, ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1);
//Get volume and check
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
var getVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1);
Assert.NotNull(getVolume.DataProtection);
Assert.NotNull(getVolume.DataProtection.Backup);
Assert.NotNull(getVolume.DataProtection.Backup.BackupPolicyId);
Assert.Equal(createBackupPolicy.Id, getVolume.DataProtection.Backup.BackupPolicyId);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
// Try and disable backups
var disableDataProtection = new VolumePatchPropertiesDataProtection
{
Backup = new VolumeBackupProperties { BackupEnabled = false, VaultId = vaultID }
};
var disableVolumePatch = new VolumePatch()
{
DataProtection = disableDataProtection
};
// patch
var disabledBackupVolume = netAppMgmtClient.Volumes.Update(disableVolumePatch, ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1);
var getDisabledVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
//check
Assert.NotNull(getDisabledVolume.DataProtection);
Assert.NotNull(getDisabledVolume.DataProtection.Backup);
Assert.False(getDisabledVolume.DataProtection.Backup.BackupEnabled);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
// clean up
ResourceUtils.DeleteVolume(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1, volumeName: ResourceUtils.backupVolumeName1);
netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1);
ResourceUtils.DeletePool(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1);
ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1);
}
}
[Fact]
public void PatchBackupPolicy()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
//Create acccount
ResourceUtils.CreateAccount(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName: ResourceUtils.volumeBackupAccountName1);
//create the backupPolicy
var backupPolicy = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName1);
var createBackupPolicy = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, backupPolicy);
// Now try and modify it
var patchBackupPolicy = new BackupPolicyPatch()
{
DailyBackupsToKeep = 1
};
var resultbackupPolicy = netAppMgmtClient.BackupPolicies.Update(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, patchBackupPolicy);
Assert.NotNull(resultbackupPolicy);
Assert.NotNull(resultbackupPolicy.DailyBackupsToKeep);
Assert.Equal(patchBackupPolicy.DailyBackupsToKeep, resultbackupPolicy.DailyBackupsToKeep);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay);
}
// cleanup
netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1);
ResourceUtils.DeletePool(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1);
ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1);
}
}
private static BackupPolicy CreateBackupPolicy(string location , string name = "")
{
// Create basic policy records with a selection of data
BackupPolicy testBackupPolicy = new BackupPolicy(location: location, name: name)
{
Enabled = true,
DailyBackupsToKeep = 4,
WeeklyBackupsToKeep = 3,
MonthlyBackupsToKeep = 2,
YearlyBackupsToKeep = 1
};
return testBackupPolicy;
}
private static string GetSessionsDirectoryPath()
{
string executingAssemblyPath = typeof(NetApp.Tests.ResourceTests.ANFBackupPolicyTests).GetTypeInfo().Assembly.Location;
return Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
namespace System.Security.Cryptography.X509Certificates
{
public partial class X509CertificateCollection : ICollection, IEnumerable, IList
{
private readonly List<X509Certificate> _list;
public X509CertificateCollection()
{
_list = new List<X509Certificate>();
}
public X509CertificateCollection(X509Certificate[] value)
: this()
{
AddRange(value);
}
public X509CertificateCollection(X509CertificateCollection value)
: this()
{
AddRange(value);
}
public int Count
{
get { return _list.Count; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return NonGenericList.SyncRoot; }
}
bool IList.IsFixedSize
{
get { return false; }
}
bool IList.IsReadOnly
{
get { return false; }
}
object IList.this[int index]
{
get
{
return NonGenericList[index];
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
NonGenericList[index] = value;
}
}
public X509Certificate this[int index]
{
get
{
return _list[index];
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_list[index] = value;
}
}
public int Add(X509Certificate value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
int index = _list.Count;
_list.Add(value);
return index;
}
public void AddRange(X509Certificate[] value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
for (int i = 0; i < value.Length; i++)
{
Add(value[i]);
}
}
public void AddRange(X509CertificateCollection value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
for (int i = 0; i < value.Count; i++)
{
Add(value[i]);
}
}
public void Clear()
{
_list.Clear();
}
public bool Contains(X509Certificate value)
{
return _list.Contains(value);
}
public void CopyTo(X509Certificate[] array, int index)
{
_list.CopyTo(array, index);
}
public X509CertificateEnumerator GetEnumerator()
{
return new X509CertificateEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public override int GetHashCode()
{
int hashCode = 0;
foreach (X509Certificate cert in _list)
{
hashCode += cert.GetHashCode();
}
return hashCode;
}
public int IndexOf(X509Certificate value)
{
return _list.IndexOf(value);
}
public void Insert(int index, X509Certificate value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_list.Insert(index, value);
}
public void Remove(X509Certificate value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
bool removed = _list.Remove(value);
// This throws on full framework, so it will also throw here.
if (!removed)
{
throw new ArgumentException(SR.Arg_RemoveArgNotFound);
}
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
void ICollection.CopyTo(Array array, int index)
{
NonGenericList.CopyTo(array, index);
}
int IList.Add(object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
return NonGenericList.Add(value);
}
bool IList.Contains(object value)
{
return NonGenericList.Contains(value);
}
int IList.IndexOf(object value)
{
return NonGenericList.IndexOf(value);
}
void IList.Insert(int index, object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
NonGenericList.Insert(index, value);
}
void IList.Remove(object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
// On full framework this method throws when removing an item that
// is not present in the collection, and that behavior needs to be
// preserved.
//
// Since that behavior is not provided by the IList.Remove exposed
// via the NonGenericList property, this method can't just defer
// like the rest of the IList explicit implementations do.
//
// The List<T> which backs this collection will guard against any
// objects which are not X509Certificiate-or-derived, and we've
// already checked whether value itself was null. Therefore we
// know that any (value as X509Certificate) which becomes null
// could not have been in our collection, and when not null we
// have a rich object reference and can defer to the other Remove
// method on this class.
X509Certificate cert = value as X509Certificate;
if (cert == null)
{
throw new ArgumentException(SR.Arg_RemoveArgNotFound);
}
Remove(cert);
}
private IList NonGenericList
{
get { return _list; }
}
internal void GetEnumerator(out List<X509Certificate>.Enumerator enumerator)
{
enumerator = _list.GetEnumerator();
}
}
}
| |
using UnityEngine;
using UnityEditor;
using ProBuilder2.Common;
using ProBuilder2.EditorCommon;
using System.Collections;
using System.Linq;
#if PB_DEBUG
using Parabox.Debug;
#endif
public class pb_Preferences
{
private static bool prefsLoaded = false;
static Color pbDefaultFaceColor;
static Color pbDefaultEdgeColor;
static Color pbDefaultSelectedVertexColor;
static Color pbDefaultVertexColor;
static bool defaultOpenInDockableWindow;
static Material pbDefaultMaterial;
static Vector2 settingsScroll = Vector2.zero;
static bool pbShowEditorNotifications;
static bool pbForceConvex = false;
static bool pbDragCheckLimit = false;
static bool pbForceVertexPivot = true;
static bool pbForceGridPivot = true;
static bool pbManifoldEdgeExtrusion;
static bool pbPerimeterEdgeBridgeOnly;
static bool pbPBOSelectionOnly;
static bool pbCloseShapeWindow = false;
static bool pbUVEditorFloating = true;
static bool pbShowSceneToolbar = true;
static bool pbStripProBuilderOnBuild = true;
static bool pbDisableAutoUV2Generation = false;
static bool pbShowSceneInfo = false;
static bool pbEnableBackfaceSelection = false;
static bool pbUniqueModeShortcuts = false;
static ColliderType defaultColliderType = ColliderType.BoxCollider;
static SceneToolbarLocation pbToolbarLocation = SceneToolbarLocation.UpperCenter;
static EntityType pbDefaultEntity = EntityType.Detail;
static float pbUVGridSnapValue;
static float pbVertexHandleSize;
static pb_Shortcut[] defaultShortcuts;
[PreferenceItem (pb_Constant.PRODUCT_NAME)]
public static void PreferencesGUI ()
{
// Load the preferences
if (!prefsLoaded) {
LoadPrefs();
prefsLoaded = true;
OnWindowResize();
}
settingsScroll = EditorGUILayout.BeginScrollView(settingsScroll, GUILayout.MaxHeight(200));
EditorGUI.BeginChangeCheck();
/**
* GENERAL SETTINGS
*/
GUILayout.Label("General Settings", EditorStyles.boldLabel);
pbStripProBuilderOnBuild = EditorGUILayout.Toggle(new GUIContent("Strip PB Scripts on Build", "If true, when building an executable all ProBuilder scripts will be stripped from your built product."), pbStripProBuilderOnBuild);
pbDisableAutoUV2Generation = EditorGUILayout.Toggle(new GUIContent("Disable Auto UV2 Generation", "Disables automatic generation of UV2 channel. If Unity is sluggish when working with large ProBuilder objects, disabling UV2 generation will improve performance. Use `Actions/Generate UV2` or `Actions/Generate Scene UV2` to build lightmap UVs prior to baking."), pbDisableAutoUV2Generation);
pbShowSceneInfo = EditorGUILayout.Toggle(new GUIContent("Show Scene Info", "Displays the selected object vertex and triangle counts in the scene view."), pbShowSceneInfo);
pbEnableBackfaceSelection = EditorGUILayout.Toggle(new GUIContent("Enable Back-face Selection", "If enabled, you may select faces that have been culled by their back face."), pbEnableBackfaceSelection);
pbDefaultMaterial = (Material) EditorGUILayout.ObjectField("Default Material", pbDefaultMaterial, typeof(Material), false);
defaultOpenInDockableWindow = EditorGUILayout.Toggle("Open in Dockable Window", defaultOpenInDockableWindow);
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Default Entity");
pbDefaultEntity = ((EntityType)EditorGUILayout.EnumPopup( (EntityType)pbDefaultEntity ));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Default Collider");
defaultColliderType = ((ColliderType)EditorGUILayout.EnumPopup( (ColliderType)defaultColliderType ));
GUILayout.EndHorizontal();
if((ColliderType)defaultColliderType == ColliderType.MeshCollider)
pbForceConvex = EditorGUILayout.Toggle("Force Convex Mesh Collider", pbForceConvex);
pbShowEditorNotifications = EditorGUILayout.Toggle("Show Editor Notifications", pbShowEditorNotifications);
pbDragCheckLimit = EditorGUILayout.Toggle(new GUIContent("Limit Drag Check to Selection", "If true, when drag selecting faces, only currently selected pb-Objects will be tested for matching faces. If false, all pb_Objects in the scene will be checked. The latter may be slower in large scenes."), pbDragCheckLimit);
pbPBOSelectionOnly = EditorGUILayout.Toggle(new GUIContent("Only PBO are Selectable", "If true, you will not be able to select non probuilder objects in Geometry and Texture mode"), pbPBOSelectionOnly);
pbCloseShapeWindow = EditorGUILayout.Toggle(new GUIContent("Close shape window after building", "If true the shape window will close after hitting the build button"), pbCloseShapeWindow);
pbShowSceneToolbar = EditorGUILayout.Toggle(new GUIContent("Show Scene Toolbar", "Hide or show the SceneView mode toolbar."), pbShowSceneToolbar);
GUI.enabled = pbShowSceneToolbar;
pbToolbarLocation = (SceneToolbarLocation) EditorGUILayout.EnumPopup("Toolbar Location", pbToolbarLocation);
GUI.enabled = true;
pbUniqueModeShortcuts = EditorGUILayout.Toggle(new GUIContent("Unique Mode Shortcuts", "When off, the G key toggles between Object and Element modes and H enumerates the element modes. If on, G, H, J, and K are shortcuts to Object, Vertex, Edge, and Face modes respectively."), pbUniqueModeShortcuts);
GUILayout.Space(4);
/**
* GEOMETRY EDITING SETTINGS
*/
GUILayout.Label("Geometry Editing Settings", EditorStyles.boldLabel);
pbDefaultFaceColor = EditorGUILayout.ColorField("Selected Face Color", pbDefaultFaceColor);
pbDefaultEdgeColor = EditorGUILayout.ColorField("Edge Wireframe Color", pbDefaultEdgeColor);
pbDefaultVertexColor = EditorGUILayout.ColorField("Vertex Color", pbDefaultVertexColor);
pbDefaultSelectedVertexColor = EditorGUILayout.ColorField("Selected Vertex Color", pbDefaultSelectedVertexColor);
pbVertexHandleSize = EditorGUILayout.Slider("Vertex Handle Size", pbVertexHandleSize, 0f, 1f);
pbForceVertexPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Vertex Point", "If true, new objects will automatically have their pivot point set to a vertex instead of the center."), pbForceVertexPivot);
pbForceGridPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Grid", "If true, newly instantiated pb_Objects will be snapped to the nearest point on grid. If ProGrids is present, the snap value will be used, otherwise decimals are simply rounded to whole numbers."), pbForceGridPivot);
pbManifoldEdgeExtrusion = EditorGUILayout.Toggle(new GUIContent("Manifold Edge Extrusion", "If false, only edges non-manifold edges may be extruded. If true, you may extrude any edge you like (for those who like to live dangerously)."), pbManifoldEdgeExtrusion);
pbPerimeterEdgeBridgeOnly = EditorGUILayout.Toggle(new GUIContent("Bridge Perimeter Edges Only", "If true, only edges on the perimeters of an object may be bridged. If false, you may bridge any between any two edges you like."), pbPerimeterEdgeBridgeOnly);
GUILayout.Space(4);
/**
* UV EDITOR SETTINGS
*/
GUILayout.Label("UV Editing Settings", EditorStyles.boldLabel);
pbUVGridSnapValue = EditorGUILayout.FloatField("UV Snap Increment", pbUVGridSnapValue);
pbUVGridSnapValue = Mathf.Clamp(pbUVGridSnapValue, .015625f, 2f);
pbUVEditorFloating = EditorGUILayout.Toggle(new GUIContent("Editor window floating", "If true UV Editor window will open as a floating window"), pbUVEditorFloating);
EditorGUILayout.EndScrollView();
GUILayout.Space(4);
GUILayout.Label("Shortcut Settings", EditorStyles.boldLabel);
if(GUI.Button(resetRect, "Use defaults"))
ResetToDefaults();
ShortcutSelectPanel();
ShortcutEditPanel();
// Save the preferences
if (EditorGUI.EndChangeCheck())
SetPrefs();
}
public static void OnWindowResize()
{
int pad = 10, buttonWidth = 100, buttonHeight = 20;
resetRect = new Rect(Screen.width-pad-buttonWidth, Screen.height-pad-buttonHeight, buttonWidth, buttonHeight);
}
public static void ResetToDefaults()
{
if(EditorUtility.DisplayDialog("Delete ProBuilder editor preferences?", "Are you sure you want to delete these?, this action cannot be undone.", "Yes", "No")) {
EditorPrefs.DeleteKey(pb_Constant.pbDefaultFaceColor);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultEdgeColor);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultOpenInDockableWindow);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultShortcuts);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultMaterial);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultCollider);
EditorPrefs.DeleteKey(pb_Constant.pbForceConvex);
EditorPrefs.DeleteKey(pb_Constant.pbShowEditorNotifications);
EditorPrefs.DeleteKey(pb_Constant.pbDragCheckLimit);
EditorPrefs.DeleteKey(pb_Constant.pbForceVertexPivot);
EditorPrefs.DeleteKey(pb_Constant.pbForceGridPivot);
EditorPrefs.DeleteKey(pb_Constant.pbManifoldEdgeExtrusion);
EditorPrefs.DeleteKey(pb_Constant.pbPerimeterEdgeBridgeOnly);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultSelectedVertexColor);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultVertexColor);
EditorPrefs.DeleteKey(pb_Constant.pbVertexHandleSize);
EditorPrefs.DeleteKey(pb_Constant.pbPBOSelectionOnly);
EditorPrefs.DeleteKey(pb_Constant.pbCloseShapeWindow);
EditorPrefs.DeleteKey(pb_Constant.pbUVEditorFloating);
EditorPrefs.DeleteKey(pb_Constant.pbShowSceneToolbar);
EditorPrefs.DeleteKey(pb_Constant.pbUVGridSnapValue);
EditorPrefs.DeleteKey(pb_Constant.pbStripProBuilderOnBuild);
EditorPrefs.DeleteKey(pb_Constant.pbDisableAutoUV2Generation);
EditorPrefs.DeleteKey(pb_Constant.pbShowSceneInfo);
EditorPrefs.DeleteKey(pb_Constant.pbEnableBackfaceSelection);
EditorPrefs.DeleteKey(pb_Constant.pbToolbarLocation);
EditorPrefs.DeleteKey(pb_Constant.pbDefaultEntity);
EditorPrefs.DeleteKey(pb_Constant.pbUniqueModeShortcuts);
}
LoadPrefs();
}
static int shortcutIndex = 0;
static Rect selectBox = new Rect(130, 253, 183, 142);
static Rect resetRect = new Rect(0,0,0,0);
static Vector2 shortcutScroll = Vector2.zero;
static int CELL_HEIGHT = 20;
// static int tmp = 0;
static void ShortcutSelectPanel()
{
// tmp = EditorGUI.IntField(new Rect(400, 340, 80, 24), "", tmp);
GUILayout.Space(4);
GUI.contentColor = Color.white;
GUI.Box(selectBox, "");
GUIStyle labelStyle = GUIStyle.none;
if(EditorGUIUtility.isProSkin)
labelStyle.normal.textColor = new Color(1f, 1f, 1f, .8f);
labelStyle.alignment = TextAnchor.MiddleLeft;
labelStyle.contentOffset = new Vector2(4f, 0f);
shortcutScroll = EditorGUILayout.BeginScrollView(shortcutScroll, false, true, GUILayout.MaxWidth(183), GUILayout.MaxHeight(156));
for(int n = 1; n < defaultShortcuts.Length; n++)
{
if(n == shortcutIndex) {
GUI.backgroundColor = new Color(0.23f, .49f, .89f, 1f);
labelStyle.normal.background = EditorGUIUtility.whiteTexture;
Color oc = labelStyle.normal.textColor;
labelStyle.normal.textColor = Color.white;
GUILayout.Box(defaultShortcuts[n].action, labelStyle, GUILayout.MinHeight(CELL_HEIGHT), GUILayout.MaxHeight(CELL_HEIGHT));
labelStyle.normal.background = null;
labelStyle.normal.textColor = oc;
GUI.backgroundColor = Color.white;
}
else
{
if(GUILayout.Button(defaultShortcuts[n].action, labelStyle, GUILayout.MinHeight(CELL_HEIGHT), GUILayout.MaxHeight(CELL_HEIGHT)))
shortcutIndex = n;
}
}
EditorGUILayout.EndScrollView();
}
static Rect keyRect = new Rect(324, 240, 168, 18);
static Rect keyInputRect = new Rect(356, 240, 133, 18);
static Rect descriptionTitleRect = new Rect(324, 300, 168, 200);
static Rect descriptionRect = new Rect(324, 320, 168, 200);
static Rect modifiersRect = new Rect(324, 270, 168, 18);
static Rect modifiersInputRect = new Rect(383, 270, 107, 18);
static void ShortcutEditPanel()
{
// descriptionTitleRect = EditorGUI.RectField(new Rect(240,150,200,50), descriptionTitleRect);
string keyString = defaultShortcuts[shortcutIndex].key.ToString();
GUI.Label(keyRect, "Key");
keyString = EditorGUI.TextField(keyInputRect, keyString);
defaultShortcuts[shortcutIndex].key = pbUtil.ParseEnum(keyString, KeyCode.None);
GUI.Label(modifiersRect, "Modifiers");
defaultShortcuts[shortcutIndex].eventModifiers =
(EventModifiers)EditorGUI.EnumMaskField(modifiersInputRect, defaultShortcuts[shortcutIndex].eventModifiers);
GUI.Label(descriptionTitleRect, "Description", EditorStyles.boldLabel);
GUI.Label(descriptionRect, defaultShortcuts[shortcutIndex].description, EditorStyles.wordWrappedLabel);
}
static void LoadPrefs()
{
pbStripProBuilderOnBuild = pb_Preferences_Internal.GetBool(pb_Constant.pbStripProBuilderOnBuild);
pbDisableAutoUV2Generation = pb_Preferences_Internal.GetBool(pb_Constant.pbDisableAutoUV2Generation);
pbShowSceneInfo = pb_Preferences_Internal.GetBool(pb_Constant.pbShowSceneInfo);
pbEnableBackfaceSelection = pb_Preferences_Internal.GetBool(pb_Constant.pbEnableBackfaceSelection);
defaultOpenInDockableWindow = pb_Preferences_Internal.GetBool(pb_Constant.pbDefaultOpenInDockableWindow);
pbDragCheckLimit = pb_Preferences_Internal.GetBool(pb_Constant.pbDragCheckLimit);
pbForceConvex = pb_Preferences_Internal.GetBool(pb_Constant.pbForceConvex);
pbForceGridPivot = pb_Preferences_Internal.GetBool(pb_Constant.pbForceGridPivot);
pbForceVertexPivot = pb_Preferences_Internal.GetBool(pb_Constant.pbForceVertexPivot);
pbManifoldEdgeExtrusion = pb_Preferences_Internal.GetBool(pb_Constant.pbManifoldEdgeExtrusion);
pbPerimeterEdgeBridgeOnly = pb_Preferences_Internal.GetBool(pb_Constant.pbPerimeterEdgeBridgeOnly);
pbPBOSelectionOnly = pb_Preferences_Internal.GetBool(pb_Constant.pbPBOSelectionOnly);
pbCloseShapeWindow = pb_Preferences_Internal.GetBool(pb_Constant.pbCloseShapeWindow);
pbUVEditorFloating = pb_Preferences_Internal.GetBool(pb_Constant.pbUVEditorFloating);
pbShowSceneToolbar = pb_Preferences_Internal.GetBool(pb_Constant.pbShowSceneToolbar);
pbShowEditorNotifications = pb_Preferences_Internal.GetBool(pb_Constant.pbShowEditorNotifications);
pbUniqueModeShortcuts = pb_Preferences_Internal.GetBool(pb_Constant.pbUniqueModeShortcuts);
pbDefaultFaceColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultFaceColor );
pbDefaultEdgeColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultEdgeColor );
pbDefaultSelectedVertexColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultSelectedVertexColor );
pbDefaultVertexColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultVertexColor );
pbUVGridSnapValue = pb_Preferences_Internal.GetFloat(pb_Constant.pbUVGridSnapValue);
pbVertexHandleSize = pb_Preferences_Internal.GetFloat(pb_Constant.pbVertexHandleSize);
defaultColliderType = pb_Preferences_Internal.GetEnum<ColliderType>(pb_Constant.pbDefaultCollider);
pbToolbarLocation = pb_Preferences_Internal.GetEnum<SceneToolbarLocation>(pb_Constant.pbToolbarLocation);
pbDefaultEntity = pb_Preferences_Internal.GetEnum<EntityType>(pb_Constant.pbDefaultEntity);
pbDefaultMaterial = pb_Preferences_Internal.GetMaterial(pb_Constant.pbDefaultMaterial);
defaultShortcuts = pb_Preferences_Internal.GetShortcuts().ToArray();
}
public static void SetPrefs()
{
EditorPrefs.SetBool (pb_Constant.pbStripProBuilderOnBuild, pbStripProBuilderOnBuild);
EditorPrefs.SetBool (pb_Constant.pbDisableAutoUV2Generation, pbDisableAutoUV2Generation);
EditorPrefs.SetBool (pb_Constant.pbShowSceneInfo, pbShowSceneInfo);
EditorPrefs.SetBool (pb_Constant.pbEnableBackfaceSelection, pbEnableBackfaceSelection);
EditorPrefs.SetInt (pb_Constant.pbToolbarLocation, (int)pbToolbarLocation);
EditorPrefs.SetInt (pb_Constant.pbDefaultEntity, (int)pbDefaultEntity);
EditorPrefs.SetString (pb_Constant.pbDefaultFaceColor, pbDefaultFaceColor.ToString());
EditorPrefs.SetString (pb_Constant.pbDefaultEdgeColor, pbDefaultEdgeColor.ToString());
EditorPrefs.SetString (pb_Constant.pbDefaultSelectedVertexColor, pbDefaultSelectedVertexColor.ToString());
EditorPrefs.SetString (pb_Constant.pbDefaultVertexColor, pbDefaultVertexColor.ToString());
EditorPrefs.SetBool (pb_Constant.pbDefaultOpenInDockableWindow, defaultOpenInDockableWindow);
EditorPrefs.SetString (pb_Constant.pbDefaultShortcuts, pb_Shortcut.ShortcutsToString(defaultShortcuts));
string matPath = pbDefaultMaterial != null ? AssetDatabase.GetAssetPath(pbDefaultMaterial) : "";
EditorPrefs.SetString (pb_Constant.pbDefaultMaterial, matPath);
EditorPrefs.SetInt (pb_Constant.pbDefaultCollider, (int)defaultColliderType);
EditorPrefs.SetBool (pb_Constant.pbShowEditorNotifications, pbShowEditorNotifications);
EditorPrefs.SetBool (pb_Constant.pbForceConvex, pbForceConvex);
EditorPrefs.SetBool (pb_Constant.pbDragCheckLimit, pbDragCheckLimit);
EditorPrefs.SetBool (pb_Constant.pbForceVertexPivot, pbForceVertexPivot);
EditorPrefs.SetBool (pb_Constant.pbForceGridPivot, pbForceGridPivot);
EditorPrefs.SetBool (pb_Constant.pbManifoldEdgeExtrusion, pbManifoldEdgeExtrusion);
EditorPrefs.SetBool (pb_Constant.pbPerimeterEdgeBridgeOnly, pbPerimeterEdgeBridgeOnly);
EditorPrefs.SetBool (pb_Constant.pbPBOSelectionOnly, pbPBOSelectionOnly);
EditorPrefs.SetBool (pb_Constant.pbCloseShapeWindow, pbCloseShapeWindow);
EditorPrefs.SetBool (pb_Constant.pbUVEditorFloating, pbUVEditorFloating);
EditorPrefs.SetBool (pb_Constant.pbShowSceneToolbar, pbShowSceneToolbar);
EditorPrefs.SetBool (pb_Constant.pbUniqueModeShortcuts, pbUniqueModeShortcuts);
EditorPrefs.SetFloat (pb_Constant.pbVertexHandleSize, pbVertexHandleSize);
EditorPrefs.SetFloat (pb_Constant.pbUVGridSnapValue, pbUVGridSnapValue);
if(pb_Editor.instance != null)
pb_Editor.instance.OnEnable();
SceneView.RepaintAll();
}
}
| |
using System;
using System.Collections.Generic;
using DG.Tweening;
using ICSharpCode.SharpZipLib.Zip;
using MoreMountains.NiceVibrations;
using Proyecto26;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
[RequireComponent(typeof(CanvasGroup))]
public class ProfileWidget : SingletonMonoBehavior<ProfileWidget>, ScreenChangeListener
{
[GetComponent] public RectTransform rectTransform;
public HorizontalLayoutGroup layoutGroup;
public Canvas canvas;
public CanvasGroup canvasGroup;
public Image background;
public Image avatarImage;
public SpinnerElement spinner;
public new Text name;
public LayoutGroup infoLayoutGroup;
public Text rating;
public Text level;
private Vector2 startAnchoredPosition;
private Profile lastProfile;
protected override void Awake()
{
SetSignedOut();
infoLayoutGroup.gameObject.SetActive(false);
canvas.overrideSorting = true;
canvas.sortingOrder = NavigationSortingOrder.ProfileWidget;
canvasGroup.alpha = 0;
canvasGroup.blocksRaycasts = false;
}
private async void Start()
{
startAnchoredPosition = rectTransform.anchoredPosition;
Context.ScreenManager.AddHandler(this);
Context.OnlinePlayer.OnProfileChanged.AddListener(profile =>
{
UpdateRatingAndLevel(profile, Context.ScreenManager.ActiveScreen.GetId() == ResultScreen.Id);
});
await UniTask.WaitUntil(() => this == null || Context.ScreenManager.ActiveScreen != null);
if (this == null) return;
if (Context.ScreenManager.ActiveScreen.GetId() != MainMenuScreen.Id)
{
Shrink();
}
}
private new void OnDestroy()
{
Context.ScreenManager.RemoveHandler(this);
}
public void Enter()
{
FadeIn();
if (Context.OnlinePlayer.IsAuthenticating) return;
if (Context.OnlinePlayer.IsAuthenticated)
{
SetSignedIn(Context.OnlinePlayer.LastProfile);
}
else if (!Context.OnlinePlayer.IsAuthenticated && !Context.OnlinePlayer.IsAuthenticating &&
!string.IsNullOrEmpty(Context.Player.Settings.LoginToken))
{
SetSigningIn();
}
else
{
SetSignedOut();
}
}
public void Enlarge()
{
rectTransform.DOAnchorPos(startAnchoredPosition, 0.4f);
transform.DOScale(1f, 0.4f);
}
public void Shrink()
{
rectTransform.DOAnchorPos(startAnchoredPosition + new Vector2(12, 20), 0.4f);
transform.DOScale(0.9f, 0.4f);
}
public void SetSigningIn()
{
name.text = "PROFILE_WIDGET_SIGNING_IN".Get();
name.DOKill();
name.color = name.color.WithAlpha(1);
name.DOFade(0, 0.4f).SetLoops(-1, LoopType.Yoyo).SetEase(Ease.InOutFlash);
infoLayoutGroup.gameObject.SetActive(false);
LayoutFixer.Fix(layoutGroup.transform);
background.color = Color.white;
spinner.IsSpinning = true;
if (Context.IsOffline())
{
Context.OnlinePlayer.FetchProfile().Then(it =>
{
if (it == null)
{
SetSignedOut();
Context.OnlinePlayer.Deauthenticate();
}
else
{
SetSignedIn(Context.OnlinePlayer.LastProfile = it);
Context.OnlinePlayer.IsAuthenticated = true;
}
});
return;
}
Context.OnlinePlayer.AuthenticateWithJwtToken()
.Then(profile =>
{
Toast.Next(Toast.Status.Success, "TOAST_SUCCESSFULLY_SIGNED_IN".Get());
SetSignedIn(profile);
Context.OnlinePlayer.IsAuthenticated = true;
if (Context.IsOffline()) Context.SetOffline(false);
})
.CatchRequestError(error =>
{
Context.OnlinePlayer.IsAuthenticated = false;
if (error.IsNetworkError)
{
Context.Haptic(HapticTypes.Warning, true);
var dialog = Dialog.Instantiate();
dialog.Message = "DIALOG_USE_OFFLINE_MODE".Get();
dialog.UseProgress = false;
dialog.UsePositiveButton = true;
dialog.UseNegativeButton = true;
dialog.OnPositiveButtonClicked = _ =>
{
Context.SetOffline(true);
Context.OnlinePlayer.FetchProfile().Then(it =>
{
if (it == null)
{
SetSignedOut();
Context.OnlinePlayer.Deauthenticate();
}
else
{
SetSignedIn(Context.OnlinePlayer.LastProfile = it);
Context.OnlinePlayer.IsAuthenticated = true;
}
dialog.Close();
}).Catch(exception => throw new InvalidOperationException()); // Impossible
};
dialog.OnNegativeButtonClicked = _ =>
{
dialog.Close();
SetSigningIn();
};
dialog.Open();
}
else
{
var errorResponse = JsonConvert.DeserializeObject<ErrorResponse>(error.Response);
Toast.Next(Toast.Status.Failure, errorResponse.message);
Debug.LogWarning("Sign in failed.");
Debug.LogWarning(error);
SetSignedOut();
}
});
}
public async void SetSignedIn(Profile profile)
{
name.text = profile.User.Uid;
name.DOKill();
name.DOFade(1, 0.2f);
infoLayoutGroup.gameObject.SetActive(true);
LayoutFixer.Fix(layoutGroup.transform);
if (avatarImage.sprite == null)
{
spinner.IsSpinning = true;
var url = profile.User.Avatar.LargeUrl;
print("Avatar URL: " + url);
var sprite = await Context.AssetMemory.LoadAsset<Sprite>(
url,
AssetTag.PlayerAvatar,
useFileCacheOnly: Context.IsOffline()
);
spinner.IsSpinning = false;
if (sprite != null)
{
SetAvatarSprite(sprite);
}
else
{
if (Context.IsOnline())
{
Toast.Enqueue(Toast.Status.Failure, "TOAST_COULD_NOT_DOWNLOAD_AVATAR".Get());
}
}
}
UpdateRatingAndLevel(profile);
}
public void SetAvatarSprite(Sprite sprite)
{
avatarImage.sprite = sprite;
avatarImage.DOColor(Color.white, 0.4f).OnComplete(() =>
{
background.color = Color.clear;
spinner.defaultIcon.GetComponent<Image>().color = Color.clear;
});
}
public void SetSignedOut()
{
name.text = "PROFILE_WIDGET_NOT_SIGNED_IN".Get();
name.DOKill();
name.DOFade(1, 0.2f);
infoLayoutGroup.gameObject.SetActive(false);
LayoutFixer.Fix(layoutGroup.transform);
background.color = Color.white;
spinner.defaultIcon.GetComponent<Image>().color = Color.white;
spinner.IsSpinning = false;
avatarImage.sprite = null;
avatarImage.color = Color.clear;
}
public static readonly HashSet<string> HiddenScreenIds = new HashSet<string> {SignInScreen.Id, ProfileScreen.Id, SettingsScreen.Id, CharacterSelectionScreen.Id};
public static readonly HashSet<string> StaticScreenIds = new HashSet<string> {ResultScreen.Id, TierBreakScreen.Id, TierResultScreen.Id};
public void OnScreenChangeStarted(Screen from, Screen to)
{
if (from != null && from.GetId() == MainMenuScreen.Id)
{
Shrink();
}
else if (to.GetId() == MainMenuScreen.Id)
{
Enlarge();
}
if (HiddenScreenIds.Contains(to.GetId()))
{
FadeOut();
}
if (StaticScreenIds.Contains(to.GetId()))
{
canvasGroup.blocksRaycasts = canvasGroup.interactable = false;
}
}
public void OnScreenChangeFinished(Screen from, Screen to)
{
if (from != null && HiddenScreenIds.Contains(from.GetId()) && !HiddenScreenIds.Contains(to.GetId()))
{
FadeIn();
}
if (StaticScreenIds.Contains(to.GetId()))
{
canvasGroup.blocksRaycasts = canvasGroup.interactable = false;
}
if (Context.OnlinePlayer.LastProfile != null)
{
UpdateRatingAndLevel(Context.OnlinePlayer.LastProfile);
}
}
public void FadeIn()
{
canvasGroup.DOFade(1, 0.2f).SetEase(Ease.OutCubic);
canvasGroup.blocksRaycasts = canvasGroup.interactable =
!StaticScreenIds.Contains(Context.ScreenManager.ActiveScreen.GetId());
}
public void FadeOut()
{
canvasGroup.DOFade(0, 0.2f).SetEase(Ease.OutCubic);
canvasGroup.blocksRaycasts = canvasGroup.interactable = false;
}
public void UpdateRatingAndLevel(Profile profile, bool showChange = false)
{
rating.text = $"{"PROFILE_WIDGET_RATING".Get()} {profile.Rating:N2}";
level.text = $"{"PROFILE_WIDGET_LEVEL".Get()} {profile.Exp.CurrentLevel}";
if (showChange && lastProfile != null)
{
var lastRating = Math.Floor(lastProfile.Rating * 100) / 100;
var currentRating = Math.Floor(profile.Rating * 100) / 100;
var rtDifference = currentRating - lastRating;
if (rtDifference >= 0.01)
{
rating.text += $" <color=#9BC53D>(+{Math.Round(rtDifference, 2)})</color>";
}
/*else if (rtDifference <= -0.01)
{
rating.text += $" <color=#E55934>({Math.Round(rtDifference, 2)})</color>";
}*/
var levelDifference = profile.Exp.CurrentLevel - lastProfile.Exp.CurrentLevel;
if (levelDifference > 0)
{
level.text += $" <color=#9BC53D>(+{levelDifference})</color>";
}
}
lastProfile = profile;
if (layoutGroup != null) LayoutFixer.Fix(layoutGroup.transform);
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using SR = System.Reflection;
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public enum ReadingMode {
Immediate = 1,
Deferred = 2,
}
public sealed class ReaderParameters {
ReadingMode reading_mode;
internal IAssemblyResolver assembly_resolver;
internal IMetadataResolver metadata_resolver;
#if !READ_ONLY
internal IMetadataImporterProvider metadata_importer_provider;
#if !CF
internal IReflectionImporterProvider reflection_importer_provider;
#endif
#endif
Stream symbol_stream;
ISymbolReaderProvider symbol_reader_provider;
bool read_symbols;
public ReadingMode ReadingMode {
get { return reading_mode; }
set { reading_mode = value; }
}
public IAssemblyResolver AssemblyResolver {
get { return assembly_resolver; }
set { assembly_resolver = value; }
}
public IMetadataResolver MetadataResolver {
get { return metadata_resolver; }
set { metadata_resolver = value; }
}
#if !READ_ONLY
public IMetadataImporterProvider MetadataImporterProvider {
get { return metadata_importer_provider; }
set { metadata_importer_provider = value; }
}
#if !CF
public IReflectionImporterProvider ReflectionImporterProvider {
get { return reflection_importer_provider; }
set { reflection_importer_provider = value; }
}
#endif
#endif
public Stream SymbolStream {
get { return symbol_stream; }
set { symbol_stream = value; }
}
public ISymbolReaderProvider SymbolReaderProvider {
get { return symbol_reader_provider; }
set { symbol_reader_provider = value; }
}
public bool ReadSymbols {
get { return read_symbols; }
set { read_symbols = value; }
}
public ReaderParameters ()
: this (ReadingMode.Deferred)
{
}
public ReaderParameters (ReadingMode readingMode)
{
this.reading_mode = readingMode;
}
}
#if !READ_ONLY
public sealed class ModuleParameters {
ModuleKind kind;
TargetRuntime runtime;
TargetArchitecture architecture;
IAssemblyResolver assembly_resolver;
IMetadataResolver metadata_resolver;
#if !READ_ONLY
IMetadataImporterProvider metadata_importer_provider;
#if !CF
IReflectionImporterProvider reflection_importer_provider;
#endif
#endif
public ModuleKind Kind {
get { return kind; }
set { kind = value; }
}
public TargetRuntime Runtime {
get { return runtime; }
set { runtime = value; }
}
public TargetArchitecture Architecture {
get { return architecture; }
set { architecture = value; }
}
public IAssemblyResolver AssemblyResolver {
get { return assembly_resolver; }
set { assembly_resolver = value; }
}
public IMetadataResolver MetadataResolver {
get { return metadata_resolver; }
set { metadata_resolver = value; }
}
#if !READ_ONLY
public IMetadataImporterProvider MetadataImporterProvider {
get { return metadata_importer_provider; }
set { metadata_importer_provider = value; }
}
#if !CF
public IReflectionImporterProvider ReflectionImporterProvider {
get { return reflection_importer_provider; }
set { reflection_importer_provider = value; }
}
#endif
#endif
public ModuleParameters ()
{
this.kind = ModuleKind.Dll;
this.Runtime = GetCurrentRuntime ();
this.architecture = TargetArchitecture.I386;
}
static TargetRuntime GetCurrentRuntime ()
{
#if !CF
return typeof (object).Assembly.ImageRuntimeVersion.ParseRuntime ();
#else
var corlib_version = typeof (object).Assembly.GetName ().Version;
switch (corlib_version.Major) {
case 1:
return corlib_version.Minor == 0
? TargetRuntime.Net_1_0
: TargetRuntime.Net_1_1;
case 2:
return TargetRuntime.Net_2_0;
case 4:
return TargetRuntime.Net_4_0;
default:
throw new NotSupportedException ();
}
#endif
}
}
public sealed class WriterParameters {
Stream symbol_stream;
ISymbolWriterProvider symbol_writer_provider;
bool write_symbols;
#if !SILVERLIGHT && !CF
SR.StrongNameKeyPair key_pair;
#endif
public Stream SymbolStream {
get { return symbol_stream; }
set { symbol_stream = value; }
}
public ISymbolWriterProvider SymbolWriterProvider {
get { return symbol_writer_provider; }
set { symbol_writer_provider = value; }
}
public bool WriteSymbols {
get { return write_symbols; }
set { write_symbols = value; }
}
#if !SILVERLIGHT && !CF
public SR.StrongNameKeyPair StrongNameKeyPair {
get { return key_pair; }
set { key_pair = value; }
}
#endif
}
#endif
public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider {
internal Image Image;
internal MetadataSystem MetadataSystem;
internal ReadingMode ReadingMode;
internal ISymbolReaderProvider SymbolReaderProvider;
internal ISymbolReader symbol_reader;
internal IAssemblyResolver assembly_resolver;
internal IMetadataResolver metadata_resolver;
internal TypeSystem type_system;
readonly MetadataReader reader;
readonly string fq_name;
internal string runtime_version;
internal ModuleKind kind;
TargetRuntime runtime;
TargetArchitecture architecture;
ModuleAttributes attributes;
ModuleCharacteristics characteristics;
Guid mvid;
internal AssemblyDefinition assembly;
MethodDefinition entry_point;
#if !READ_ONLY
#if !CF
internal IReflectionImporter reflection_importer;
#endif
internal IMetadataImporter metadata_importer;
#endif
Collection<CustomAttribute> custom_attributes;
Collection<AssemblyNameReference> references;
Collection<ModuleReference> modules;
Collection<Resource> resources;
Collection<ExportedType> exported_types;
TypeDefinitionCollection types;
public bool IsMain {
get { return kind != ModuleKind.NetModule; }
}
public ModuleKind Kind {
get { return kind; }
set { kind = value; }
}
public TargetRuntime Runtime {
get { return runtime; }
set {
runtime = value;
runtime_version = runtime.RuntimeVersionString ();
}
}
public string RuntimeVersion {
get { return runtime_version; }
set {
runtime_version = value;
runtime = runtime_version.ParseRuntime ();
}
}
public TargetArchitecture Architecture {
get { return architecture; }
set { architecture = value; }
}
public ModuleAttributes Attributes {
get { return attributes; }
set { attributes = value; }
}
public ModuleCharacteristics Characteristics {
get { return characteristics; }
set { characteristics = value; }
}
public string FullyQualifiedName {
get { return fq_name; }
}
public Guid Mvid {
get { return mvid; }
set { mvid = value; }
}
internal bool HasImage {
get { return Image != null; }
}
public bool HasSymbols {
get { return symbol_reader != null; }
}
public ISymbolReader SymbolReader {
get { return symbol_reader; }
}
public override MetadataScopeType MetadataScopeType {
get { return MetadataScopeType.ModuleDefinition; }
}
public AssemblyDefinition Assembly {
get { return assembly; }
}
#if !READ_ONLY
#if !CF
internal IReflectionImporter ReflectionImporter {
get {
if (reflection_importer == null)
Interlocked.CompareExchange (ref reflection_importer, new ReflectionImporter (this), null);
return reflection_importer;
}
}
#endif
internal IMetadataImporter MetadataImporter {
get {
if (metadata_importer == null)
Interlocked.CompareExchange (ref metadata_importer, new MetadataImporter (this), null);
return metadata_importer;
}
}
#endif
public IAssemblyResolver AssemblyResolver {
get {
if (assembly_resolver == null)
Interlocked.CompareExchange (ref assembly_resolver, new DefaultAssemblyResolver (), null);
return assembly_resolver;
}
}
public IMetadataResolver MetadataResolver {
get {
if (metadata_resolver == null)
Interlocked.CompareExchange (ref metadata_resolver, new MetadataResolver (this.AssemblyResolver), null);
return metadata_resolver;
}
}
public TypeSystem TypeSystem {
get {
if (type_system == null)
Interlocked.CompareExchange (ref type_system, TypeSystem.CreateTypeSystem (this), null);
return type_system;
}
}
public bool HasAssemblyReferences {
get {
if (references != null)
return references.Count > 0;
return HasImage && Image.HasTable (Table.AssemblyRef);
}
}
public Collection<AssemblyNameReference> AssemblyReferences {
get {
if (references != null)
return references;
if (HasImage)
return Read (ref references, this, (_, reader) => reader.ReadAssemblyReferences ());
return references = new Collection<AssemblyNameReference> ();
}
}
public bool HasModuleReferences {
get {
if (modules != null)
return modules.Count > 0;
return HasImage && Image.HasTable (Table.ModuleRef);
}
}
public Collection<ModuleReference> ModuleReferences {
get {
if (modules != null)
return modules;
if (HasImage)
return Read (ref modules, this, (_, reader) => reader.ReadModuleReferences ());
return modules = new Collection<ModuleReference> ();
}
}
public bool HasResources {
get {
if (resources != null)
return resources.Count > 0;
if (HasImage)
return Image.HasTable (Table.ManifestResource) || Read (this, (_, reader) => reader.HasFileResource ());
return false;
}
}
public Collection<Resource> Resources {
get {
if (resources != null)
return resources;
if (HasImage)
return Read (ref resources, this, (_, reader) => reader.ReadResources ());
return resources = new Collection<Resource> ();
}
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return this.GetHasCustomAttributes (this);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, this)); }
}
public bool HasTypes {
get {
if (types != null)
return types.Count > 0;
return HasImage && Image.HasTable (Table.TypeDef);
}
}
public Collection<TypeDefinition> Types {
get {
if (types != null)
return types;
if (HasImage)
return Read (ref types, this, (_, reader) => reader.ReadTypes ());
return types = new TypeDefinitionCollection (this);
}
}
public bool HasExportedTypes {
get {
if (exported_types != null)
return exported_types.Count > 0;
return HasImage && Image.HasTable (Table.ExportedType);
}
}
public Collection<ExportedType> ExportedTypes {
get {
if (exported_types != null)
return exported_types;
if (HasImage)
return Read (ref exported_types, this, (_, reader) => reader.ReadExportedTypes ());
return exported_types = new Collection<ExportedType> ();
}
}
public MethodDefinition EntryPoint {
get {
if (entry_point != null)
return entry_point;
if (HasImage)
return Read (ref entry_point, this, (_, reader) => reader.ReadEntryPoint ());
return entry_point = null;
}
set { entry_point = value; }
}
internal ModuleDefinition ()
{
this.MetadataSystem = new MetadataSystem ();
this.token = new MetadataToken (TokenType.Module, 1);
}
internal ModuleDefinition (Image image)
: this ()
{
this.Image = image;
this.kind = image.Kind;
this.RuntimeVersion = image.RuntimeVersion;
this.architecture = image.Architecture;
this.attributes = image.Attributes;
this.characteristics = image.Characteristics;
this.fq_name = image.FileName;
this.reader = new MetadataReader (this);
}
public bool HasTypeReference (string fullName)
{
return HasTypeReference (string.Empty, fullName);
}
public bool HasTypeReference (string scope, string fullName)
{
CheckFullName (fullName);
if (!HasImage)
return false;
return GetTypeReference (scope, fullName) != null;
}
public bool TryGetTypeReference (string fullName, out TypeReference type)
{
return TryGetTypeReference (string.Empty, fullName, out type);
}
public bool TryGetTypeReference (string scope, string fullName, out TypeReference type)
{
CheckFullName (fullName);
if (!HasImage) {
type = null;
return false;
}
return (type = GetTypeReference (scope, fullName)) != null;
}
TypeReference GetTypeReference (string scope, string fullname)
{
return Read (new Row<string, string> (scope, fullname), (row, reader) => reader.GetTypeReference (row.Col1, row.Col2));
}
public IEnumerable<TypeReference> GetTypeReferences ()
{
if (!HasImage)
return Empty<TypeReference>.Array;
return Read (this, (_, reader) => reader.GetTypeReferences ());
}
public IEnumerable<MemberReference> GetMemberReferences ()
{
if (!HasImage)
return Empty<MemberReference>.Array;
return Read (this, (_, reader) => reader.GetMemberReferences ());
}
public TypeReference GetType (string fullName, bool runtimeName)
{
return runtimeName
? TypeParser.ParseType (this, fullName)
: GetType (fullName);
}
public TypeDefinition GetType (string fullName)
{
CheckFullName (fullName);
var position = fullName.IndexOf ('/');
if (position > 0)
return GetNestedType (fullName);
return ((TypeDefinitionCollection) this.Types).GetType (fullName);
}
public TypeDefinition GetType (string @namespace, string name)
{
Mixin.CheckName (name);
return ((TypeDefinitionCollection) this.Types).GetType (@namespace ?? string.Empty, name);
}
public IEnumerable<TypeDefinition> GetTypes ()
{
return GetTypes (Types);
}
static IEnumerable<TypeDefinition> GetTypes (Collection<TypeDefinition> types)
{
for (int i = 0; i < types.Count; i++) {
var type = types [i];
yield return type;
if (!type.HasNestedTypes)
continue;
foreach (var nested in GetTypes (type.NestedTypes))
yield return nested;
}
}
static void CheckFullName (string fullName)
{
if (fullName == null)
throw new ArgumentNullException ("fullName");
if (fullName.Length == 0)
throw new ArgumentException ();
}
TypeDefinition GetNestedType (string fullname)
{
var names = fullname.Split ('/');
var type = GetType (names [0]);
if (type == null)
return null;
for (int i = 1; i < names.Length; i++) {
var nested_type = type.GetNestedType (names [i]);
if (nested_type == null)
return null;
type = nested_type;
}
return type;
}
internal FieldDefinition Resolve (FieldReference field)
{
return MetadataResolver.Resolve (field);
}
internal MethodDefinition Resolve (MethodReference method)
{
return MetadataResolver.Resolve (method);
}
internal TypeDefinition Resolve (TypeReference type)
{
return MetadataResolver.Resolve (type);
}
#if !READ_ONLY
static void CheckContext (IGenericParameterProvider context, ModuleDefinition module)
{
if (context == null)
return;
if (context.Module != module)
throw new ArgumentException ();
}
#if !CF
[Obsolete ("Use ImportReference", error: false)]
public TypeReference Import (Type type)
{
return ImportReference (type, null);
}
public TypeReference ImportReference (Type type)
{
return ImportReference (type, null);
}
[Obsolete ("Use ImportReference", error: false)]
public TypeReference Import (Type type, IGenericParameterProvider context)
{
return ImportReference (type, context);
}
public TypeReference ImportReference (Type type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
CheckContext (context, this);
return ReflectionImporter.ImportReference (type, context);
}
[Obsolete ("Use ImportReference", error: false)]
public FieldReference Import (SR.FieldInfo field)
{
return ImportReference (field, null);
}
[Obsolete ("Use ImportReference", error: false)]
public FieldReference Import (SR.FieldInfo field, IGenericParameterProvider context)
{
return ImportReference (field, context);
}
public FieldReference ImportReference (SR.FieldInfo field)
{
return ImportReference (field, null);
}
public FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
CheckContext (context, this);
return ReflectionImporter.ImportReference (field, context);
}
[Obsolete ("Use ImportReference", error: false)]
public MethodReference Import (SR.MethodBase method)
{
return ImportReference (method, null);
}
[Obsolete ("Use ImportReference", error: false)]
public MethodReference Import (SR.MethodBase method, IGenericParameterProvider context)
{
return ImportReference (method, context);
}
public MethodReference ImportReference (SR.MethodBase method)
{
return ImportReference (method, null);
}
public MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
CheckContext (context, this);
return ReflectionImporter.ImportReference (method, context);
}
#endif
[Obsolete ("Use ImportReference", error: false)]
public TypeReference Import (TypeReference type)
{
return ImportReference (type, null);
}
[Obsolete ("Use ImportReference", error: false)]
public TypeReference Import (TypeReference type, IGenericParameterProvider context)
{
return ImportReference (type, context);
}
public TypeReference ImportReference (TypeReference type)
{
return ImportReference (type, null);
}
public TypeReference ImportReference (TypeReference type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
if (type.Module == this)
return type;
CheckContext (context, this);
return MetadataImporter.ImportReference (type, context);
}
[Obsolete ("Use ImportReference", error: false)]
public FieldReference Import (FieldReference field)
{
return ImportReference (field, null);
}
[Obsolete ("Use ImportReference", error: false)]
public FieldReference Import (FieldReference field, IGenericParameterProvider context)
{
return ImportReference (field, context);
}
public FieldReference ImportReference (FieldReference field)
{
return ImportReference (field, null);
}
public FieldReference ImportReference (FieldReference field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
if (field.Module == this)
return field;
CheckContext (context, this);
return MetadataImporter.ImportReference (field, context);
}
[Obsolete ("Use ImportReference", error: false)]
public MethodReference Import (MethodReference method)
{
return ImportReference (method, null);
}
[Obsolete ("Use ImportReference", error: false)]
public MethodReference Import (MethodReference method, IGenericParameterProvider context)
{
return ImportReference (method, context);
}
public MethodReference ImportReference (MethodReference method)
{
return ImportReference (method, null);
}
public MethodReference ImportReference (MethodReference method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
if (method.Module == this)
return method;
CheckContext (context, this);
return MetadataImporter.ImportReference (method, context);
}
#endif
public IMetadataTokenProvider LookupToken (int token)
{
return LookupToken (new MetadataToken ((uint) token));
}
public IMetadataTokenProvider LookupToken (MetadataToken token)
{
return Read (token, (t, reader) => reader.LookupToken (t));
}
readonly object module_lock = new object();
internal object SyncRoot {
get { return module_lock; }
}
internal TRet Read<TItem, TRet> (TItem item, Func<TItem, MetadataReader, TRet> read)
{
lock (module_lock) {
var position = reader.position;
var context = reader.context;
var ret = read (item, reader);
reader.position = position;
reader.context = context;
return ret;
}
}
internal TRet Read<TItem, TRet> (ref TRet variable, TItem item, Func<TItem, MetadataReader, TRet> read) where TRet : class
{
lock (module_lock) {
if (variable != null)
return variable;
var position = reader.position;
var context = reader.context;
var ret = read (item, reader);
reader.position = position;
reader.context = context;
return variable = ret;
}
}
public bool HasDebugHeader {
get { return Image != null && !Image.Debug.IsZero; }
}
public ImageDebugDirectory GetDebugHeader (out byte [] header)
{
if (!HasDebugHeader)
throw new InvalidOperationException ();
return Image.GetDebugHeader (out header);
}
void ProcessDebugHeader ()
{
if (!HasDebugHeader)
return;
byte [] header;
var directory = GetDebugHeader (out header);
if (!symbol_reader.ProcessDebugHeader (directory, header))
throw new InvalidOperationException ();
}
#if !READ_ONLY
public static ModuleDefinition CreateModule (string name, ModuleKind kind)
{
return CreateModule (name, new ModuleParameters { Kind = kind });
}
public static ModuleDefinition CreateModule (string name, ModuleParameters parameters)
{
Mixin.CheckName (name);
Mixin.CheckParameters (parameters);
var module = new ModuleDefinition {
Name = name,
kind = parameters.Kind,
Runtime = parameters.Runtime,
architecture = parameters.Architecture,
mvid = Guid.NewGuid (),
Attributes = ModuleAttributes.ILOnly,
Characteristics = (ModuleCharacteristics) 0x8540,
};
if (parameters.AssemblyResolver != null)
module.assembly_resolver = parameters.AssemblyResolver;
if (parameters.MetadataResolver != null)
module.metadata_resolver = parameters.MetadataResolver;
#if !READ_ONLY
if (parameters.MetadataImporterProvider != null)
module.metadata_importer = parameters.MetadataImporterProvider.GetMetadataImporter (module);
#if !CF
if (parameters.ReflectionImporterProvider != null)
module.reflection_importer = parameters.ReflectionImporterProvider.GetReflectionImporter (module);
#endif
#endif
if (parameters.Kind != ModuleKind.NetModule) {
var assembly = new AssemblyDefinition ();
module.assembly = assembly;
module.assembly.Name = CreateAssemblyName (name);
assembly.main_module = module;
}
module.Types.Add (new TypeDefinition (string.Empty, "<Module>", TypeAttributes.NotPublic));
return module;
}
static AssemblyNameDefinition CreateAssemblyName (string name)
{
if (name.EndsWith (".dll") || name.EndsWith (".exe"))
name = name.Substring (0, name.Length - 4);
return new AssemblyNameDefinition (name, Mixin.ZeroVersion);
}
#endif
public void ReadSymbols ()
{
if (string.IsNullOrEmpty (fq_name))
throw new InvalidOperationException ();
var provider = SymbolProvider.GetPlatformReaderProvider ();
if (provider == null)
throw new InvalidOperationException ();
ReadSymbols (provider.GetSymbolReader (this, fq_name));
}
public void ReadSymbols (ISymbolReader reader)
{
if (reader == null)
throw new ArgumentNullException ("reader");
symbol_reader = reader;
ProcessDebugHeader ();
}
public static ModuleDefinition ReadModule (string fileName)
{
return ReadModule (fileName, new ReaderParameters (ReadingMode.Deferred));
}
public static ModuleDefinition ReadModule (Stream stream)
{
return ReadModule (stream, new ReaderParameters (ReadingMode.Deferred));
}
public static ModuleDefinition ReadModule (string fileName, ReaderParameters parameters)
{
using (var stream = GetFileStream (fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
return ReadModule (stream, parameters);
}
}
public static ModuleDefinition ReadModule (Stream stream, ReaderParameters parameters)
{
Mixin.CheckStream (stream);
if (!stream.CanRead || !stream.CanSeek)
throw new ArgumentException ();
Mixin.CheckParameters (parameters);
return ModuleReader.CreateModuleFrom (
ImageReader.ReadImageFrom (stream),
parameters);
}
static Stream GetFileStream (string fileName, FileMode mode, FileAccess access, FileShare share)
{
if (fileName == null)
throw new ArgumentNullException ("fileName");
if (fileName.Length == 0)
throw new ArgumentException ();
return new FileStream (fileName, mode, access, share);
}
#if !READ_ONLY
public void Write (string fileName)
{
Write (fileName, new WriterParameters ());
}
public void Write (Stream stream)
{
Write (stream, new WriterParameters ());
}
public void Write (string fileName, WriterParameters parameters)
{
using (var stream = GetFileStream (fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) {
Write (stream, parameters);
}
}
public void Write (Stream stream, WriterParameters parameters)
{
Mixin.CheckStream (stream);
if (!stream.CanWrite || !stream.CanSeek)
throw new ArgumentException ();
Mixin.CheckParameters (parameters);
ModuleWriter.WriteModuleTo (this, stream, parameters);
}
#endif
}
static partial class Mixin {
public static void CheckStream (object stream)
{
if (stream == null)
throw new ArgumentNullException ("stream");
}
#if !READ_ONLY
public static void CheckType (object type)
{
if (type == null)
throw new ArgumentNullException ("type");
}
public static void CheckField (object field)
{
if (field == null)
throw new ArgumentNullException ("field");
}
public static void CheckMethod (object method)
{
if (method == null)
throw new ArgumentNullException ("method");
}
#endif
public static void CheckParameters (object parameters)
{
if (parameters == null)
throw new ArgumentNullException ("parameters");
}
public static bool HasImage (this ModuleDefinition self)
{
return self != null && self.HasImage;
}
public static bool IsCorlib (this ModuleDefinition module)
{
if (module.Assembly == null)
return false;
return module.Assembly.Name.Name == "mscorlib";
}
public static string GetFullyQualifiedName (this Stream self)
{
#if !SILVERLIGHT
var file_stream = self as FileStream;
if (file_stream == null)
return string.Empty;
return Path.GetFullPath (file_stream.Name);
#else
return string.Empty;
#endif
}
public static TargetRuntime ParseRuntime (this string self)
{
switch (self [1]) {
case '1':
return self [3] == '0'
? TargetRuntime.Net_1_0
: TargetRuntime.Net_1_1;
case '2':
return TargetRuntime.Net_2_0;
case '4':
default:
return TargetRuntime.Net_4_0;
}
}
public static string RuntimeVersionString (this TargetRuntime runtime)
{
switch (runtime) {
case TargetRuntime.Net_1_0:
return "v1.0.3705";
case TargetRuntime.Net_1_1:
return "v1.1.4322";
case TargetRuntime.Net_2_0:
return "v2.0.50727";
case TargetRuntime.Net_4_0:
default:
return "v4.0.30319";
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace MVCWebExample.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Log.PublisherBinding", Namespace="urn:iControl")]
public partial class LogPublisher : iControlInterface {
public LogPublisher() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_destination
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/Publisher",
RequestNamespace="urn:iControl:Log/Publisher", ResponseNamespace="urn:iControl:Log/Publisher")]
public void add_destination(
string [] publishers,
string [] [] destinations
) {
this.Invoke("add_destination", new object [] {
publishers,
destinations});
}
public System.IAsyncResult Beginadd_destination(string [] publishers,string [] [] destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_destination", new object[] {
publishers,
destinations}, callback, asyncState);
}
public void Endadd_destination(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/Publisher",
RequestNamespace="urn:iControl:Log/Publisher", ResponseNamespace="urn:iControl:Log/Publisher")]
public void create(
string [] publishers,
string [] [] destinations
) {
this.Invoke("create", new object [] {
publishers,
destinations});
}
public System.IAsyncResult Begincreate(string [] publishers,string [] [] destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
publishers,
destinations}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_publishers
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/Publisher",
RequestNamespace="urn:iControl:Log/Publisher", ResponseNamespace="urn:iControl:Log/Publisher")]
public void delete_all_publishers(
) {
this.Invoke("delete_all_publishers", new object [0]);
}
public System.IAsyncResult Begindelete_all_publishers(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_publishers", new object[0], callback, asyncState);
}
public void Enddelete_all_publishers(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_publisher
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/Publisher",
RequestNamespace="urn:iControl:Log/Publisher", ResponseNamespace="urn:iControl:Log/Publisher")]
public void delete_publisher(
string [] publishers
) {
this.Invoke("delete_publisher", new object [] {
publishers});
}
public System.IAsyncResult Begindelete_publisher(string [] publishers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_publisher", new object[] {
publishers}, callback, asyncState);
}
public void Enddelete_publisher(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/Publisher",
RequestNamespace="urn:iControl:Log/Publisher", ResponseNamespace="urn:iControl:Log/Publisher")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] publishers
) {
object [] results = this.Invoke("get_description", new object [] {
publishers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] publishers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
publishers}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_destination
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/Publisher",
RequestNamespace="urn:iControl:Log/Publisher", ResponseNamespace="urn:iControl:Log/Publisher")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_destination(
string [] publishers
) {
object [] results = this.Invoke("get_destination", new object [] {
publishers});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_destination(string [] publishers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_destination", new object[] {
publishers}, callback, asyncState);
}
public string [] [] Endget_destination(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/Publisher",
RequestNamespace="urn:iControl:Log/Publisher", ResponseNamespace="urn:iControl:Log/Publisher")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/Publisher",
RequestNamespace="urn:iControl:Log/Publisher", ResponseNamespace="urn:iControl:Log/Publisher")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_destinations
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/Publisher",
RequestNamespace="urn:iControl:Log/Publisher", ResponseNamespace="urn:iControl:Log/Publisher")]
public void remove_all_destinations(
string [] publishers
) {
this.Invoke("remove_all_destinations", new object [] {
publishers});
}
public System.IAsyncResult Beginremove_all_destinations(string [] publishers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_destinations", new object[] {
publishers}, callback, asyncState);
}
public void Endremove_all_destinations(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_destination
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/Publisher",
RequestNamespace="urn:iControl:Log/Publisher", ResponseNamespace="urn:iControl:Log/Publisher")]
public void remove_destination(
string [] publishers,
string [] [] destinations
) {
this.Invoke("remove_destination", new object [] {
publishers,
destinations});
}
public System.IAsyncResult Beginremove_destination(string [] publishers,string [] [] destinations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_destination", new object[] {
publishers,
destinations}, callback, asyncState);
}
public void Endremove_destination(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/Publisher",
RequestNamespace="urn:iControl:Log/Publisher", ResponseNamespace="urn:iControl:Log/Publisher")]
public void set_description(
string [] publishers,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
publishers,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] publishers,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
publishers,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup
{
internal sealed partial class EventHookupSessionManager
{
/// <summary>
/// A session begins when an '=' is typed after a '+' and requires determining whether the
/// += is being used to add an event handler to an event. If it is, then we also determine
/// a candidate name for the event handler.
/// </summary>
internal class EventHookupSession : ForegroundThreadAffinitizedObject
{
public readonly Task<string> GetEventNameTask;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly ITrackingPoint _trackingPoint;
private readonly ITrackingSpan _trackingSpan;
private readonly ITextView _textView;
private readonly ITextBuffer _subjectBuffer;
public event Action Dismissed = () => { };
// For testing purposes only! Should always be null except in tests.
internal Mutex TESTSessionHookupMutex = null;
public ITrackingPoint TrackingPoint
{
get
{
AssertIsForeground();
return _trackingPoint;
}
}
public ITrackingSpan TrackingSpan
{
get
{
AssertIsForeground();
return _trackingSpan;
}
}
public ITextView TextView
{
get
{
AssertIsForeground();
return _textView;
}
}
public ITextBuffer SubjectBuffer
{
get
{
AssertIsForeground();
return _subjectBuffer;
}
}
public void Cancel()
{
AssertIsForeground();
_cancellationTokenSource.Cancel();
}
public EventHookupSession(
EventHookupSessionManager eventHookupSessionManager,
EventHookupCommandHandler commandHandler,
ITextView textView,
ITextBuffer subjectBuffer,
IAsynchronousOperationListener asyncListener,
Mutex testSessionHookupMutex)
{
AssertIsForeground();
_cancellationTokenSource = new CancellationTokenSource();
_textView = textView;
_subjectBuffer = subjectBuffer;
this.TESTSessionHookupMutex = testSessionHookupMutex;
var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null && document.Project.Solution.Workspace.CanApplyChange(ApplyChangesKind.ChangeDocument))
{
var position = textView.GetCaretPoint(subjectBuffer).Value.Position;
_trackingPoint = textView.TextSnapshot.CreateTrackingPoint(position, PointTrackingMode.Negative);
_trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(position, 1), SpanTrackingMode.EdgeInclusive);
var asyncToken = asyncListener.BeginAsyncOperation(GetType().Name + ".Start");
this.GetEventNameTask = Task.Factory.SafeStartNewFromAsync(
() => DetermineIfEventHookupAndGetHandlerNameAsync(document, position, _cancellationTokenSource.Token),
_cancellationTokenSource.Token,
TaskScheduler.Default);
var continuedTask = this.GetEventNameTask.SafeContinueWith(t =>
{
AssertIsForeground();
if (t.Result != null)
{
commandHandler.EventHookupSessionManager.EventHookupFoundInSession(this);
}
},
_cancellationTokenSource.Token,
TaskContinuationOptions.OnlyOnRanToCompletion,
ForegroundThreadAffinitizedObject.ForegroundTaskScheduler);
continuedTask.CompletesAsyncOperation(asyncToken);
}
else
{
_trackingPoint = textView.TextSnapshot.CreateTrackingPoint(0, PointTrackingMode.Negative);
_trackingSpan = textView.TextSnapshot.CreateTrackingSpan(new Span(), SpanTrackingMode.EdgeInclusive);
this.GetEventNameTask = SpecializedTasks.Default<string>();
eventHookupSessionManager.CancelAndDismissExistingSessions();
}
}
private async Task<string> DetermineIfEventHookupAndGetHandlerNameAsync(Document document, int position, CancellationToken cancellationToken)
{
AssertIsBackground();
// For test purposes only!
if (TESTSessionHookupMutex != null)
{
TESTSessionHookupMutex.WaitOne();
TESTSessionHookupMutex.ReleaseMutex();
}
using (Logger.LogBlock(FunctionId.EventHookup_Determine_If_Event_Hookup, cancellationToken))
{
var plusEqualsToken = await GetPlusEqualsTokenInsideAddAssignExpressionAsync(document, position, cancellationToken).ConfigureAwait(false);
if (plusEqualsToken == null)
{
return null;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var eventSymbol = GetEventSymbol(semanticModel, plusEqualsToken.Value, cancellationToken);
if (eventSymbol == null)
{
return null;
}
return GetEventHandlerName(eventSymbol, plusEqualsToken.Value, semanticModel, document.GetLanguageService<ISyntaxFactsService>());
}
}
private async Task<SyntaxToken?> GetPlusEqualsTokenInsideAddAssignExpressionAsync(Document document, int position, CancellationToken cancellationToken)
{
AssertIsBackground();
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
if (token.Kind() != SyntaxKind.PlusEqualsToken)
{
return null;
}
if (!token.Parent.IsKind(SyntaxKind.AddAssignmentExpression))
{
return null;
}
return token;
}
private IEventSymbol GetEventSymbol(SemanticModel semanticModel, SyntaxToken plusEqualsToken, CancellationToken cancellationToken)
{
AssertIsBackground();
var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax;
if (parentToken == null)
{
return null;
}
var symbol = semanticModel.GetSymbolInfo(parentToken.Left, cancellationToken).Symbol;
if (symbol == null)
{
return null;
}
return symbol as IEventSymbol;
}
private string GetEventHandlerName(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService)
{
AssertIsBackground();
var basename = string.Format("{0}_{1}", GetNameObjectPart(eventSymbol, plusEqualsToken, semanticModel, syntaxFactsService), eventSymbol.Name);
basename = basename.ToPascalCase(trimLeadingTypePrefix: false);
var reservedNames = semanticModel.LookupSymbols(plusEqualsToken.SpanStart).Select(m => m.Name);
return NameGenerator.EnsureUniqueness(basename, reservedNames);
}
/// <summary>
/// Take another look at the LHS of the += node -- we need to figure out a default name
/// for the event handler, and that's usually based on the object (which is usually a
/// field of 'this', but not always) to which the event belongs. So, if the event is
/// something like 'button1.Click' or 'this.listBox1.Select', we want the names
/// 'button1' and 'listBox1' respectively. If the field belongs to 'this', then we use
/// the name of this class, as we do if we can't make any sense out of the parse tree.
/// </summary>
private string GetNameObjectPart(IEventSymbol eventSymbol, SyntaxToken plusEqualsToken, SemanticModel semanticModel, ISyntaxFactsService syntaxFactsService)
{
AssertIsBackground();
var parentToken = plusEqualsToken.Parent as AssignmentExpressionSyntax;
var memberAccessExpression = parentToken.Left as MemberAccessExpressionSyntax;
if (memberAccessExpression != null)
{
// This is expected -- it means the last thing is(probably) the event name. We
// already have that in eventSymbol. What we need is the LHS of that dot.
var lhs = memberAccessExpression.Expression;
var lhsMemberAccessExpression = lhs as MemberAccessExpressionSyntax;
if (lhsMemberAccessExpression != null)
{
// Okay, cool. The name we're after is in the RHS of this dot.
return lhsMemberAccessExpression.Name.ToString();
}
var lhsNameSyntax = lhs as NameSyntax;
if (lhsNameSyntax != null)
{
// Even easier -- the LHS of the dot is the name itself
return lhsNameSyntax.ToString();
}
}
// If we didn't find an object name above, then the object name is the name of this class.
// Note: For generic, it's ok(it's even a good idea) to exclude type variables,
// because the name is only used as a prefix for the method name.
var typeDeclaration = syntaxFactsService.GetContainingTypeDeclaration(
semanticModel.SyntaxTree.GetRoot(),
plusEqualsToken.SpanStart) as BaseTypeDeclarationSyntax;
return typeDeclaration != null
? typeDeclaration.Identifier.Text
: eventSymbol.ContainingType.Name;
}
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Nova.Controls;
using Nova.Properties;
using Nova.Threading;
using Nova.Threading.WPF;
namespace Nova.Library
{
/// <summary>
/// The controller that handles actions.
/// </summary>
/// <typeparam name="TView">The View.</typeparam>
/// <typeparam name="TViewModel">The ViewModel.</typeparam>
public class ActionController<TView, TViewModel>
where TViewModel : IViewModel
where TView : IView
{
private readonly IActionQueueManager _actionQueueManager;
private readonly TView _view;
private readonly TViewModel _viewModel;
/// <summary>
/// Default ctor.
/// </summary>
/// <param name="view">The View.</param>
/// <param name="viewModel">The ViewModel.</param>
/// <param name="actionQueueManager">The Action Queue Manager</param>
public ActionController(TView view, TViewModel viewModel, IActionQueueManager actionQueueManager)
{
_view = view;
_viewModel = viewModel;
_actionQueueManager = actionQueueManager;
}
/// <summary>
/// Invokes the specified action.
/// </summary>
/// <typeparam name="T">The type of action to invoke.</typeparam>
/// <param name="actionToRun">The action to execute.</param>
/// <param name="disposeActionDuringCleanup">Dispose the action after execution, during cleanup.</param>
/// <param name="executeCompleted">The action to invoke when the async execution completes.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private IAction Invoke<T>(T actionToRun, bool disposeActionDuringCleanup, Action executeCompleted = null)
where T : Actionflow<TView, TViewModel>
{
if (actionToRun == null)
return null;
var action = PrepareAction(actionToRun, disposeActionDuringCleanup, executeCompleted);
if (!_actionQueueManager.Enqueue(action))
{
CleanUpFailedEnqueue(actionToRun, disposeActionDuringCleanup, executeCompleted);
return null;
}
return action;
}
/// <summary>
/// Cleans up an action that failed to enqueue.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="actionToRun">The action to run.</param>
/// <param name="disposeActionDuringCleanup">if set to <c>true</c> [dispose action during cleanup].</param>
/// <param name="executeCompleted">The execute completed.</param>
private static void CleanUpFailedEnqueue<T>(T actionToRun, bool disposeActionDuringCleanup, Action executeCompleted)
where T : Actionflow<TView, TViewModel>
{
Task task = null;
if (executeCompleted != null)
{
task = Task.Run(executeCompleted);
}
if (!disposeActionDuringCleanup) return;
if (task == null)
{
actionToRun.Dispose();
}
else
{
task.ContinueWith(_ => actionToRun.Dispose())
.ContinueWith(x => { if (x.Exception != null) x.Exception.Handle(_ => true); }, TaskContinuationOptions.OnlyOnFaulted);
}
}
/// <summary>
/// Wraps the action into an IAction format so we can pass it on to the Queue Manager.
/// </summary>
/// <typeparam name="T">The type of action to invoke.</typeparam>
/// <param name="actionToRun">The action to execute.</param>
/// <param name="disposeActionDuringCleanup">Dispose the action after execution, during cleanup.</param>
/// <param name="executeCompleted">The action to invoke when the async execution completes.</param>
/// <returns>The action to run in an IAction format.</returns>
private static IAction PrepareAction<T>(T actionToRun, bool disposeActionDuringCleanup, Action executeCompleted)
where T : Actionflow<TView, TViewModel>
{
if (actionToRun == null)
return null;
var action = actionToRun.Wrap(x => x.ViewModel.ID, x => x.InternalOnBefore, x => x.RanSuccesfully, mainThread: true)
.CanExecute(actionToRun.CanExecute)
.ContinueWith(actionToRun.InternalExecute)
.ContinueWith(actionToRun.InternalExecuteCompleted, mainThread: true)
.FinishWith(actionToRun.InternalOnAfter, Priority.BelowNormal, mainThread: true)
.FinishWith(() =>
{
if (disposeActionDuringCleanup)
actionToRun.Dispose();
}, Priority.Lowest, mainThread: true)
.HandleException(x => ExceptionHandler.Handle(x, Resources.UnhandledException)); //Main Thread because view logic in clean up. (e.g. IsLoading)
if (executeCompleted != null)
{
action.ContinueWith(executeCompleted);
}
return action;
}
/// <summary>
/// Invokes the specified action.
/// </summary>
/// <typeparam name="T">The type of action to invoke.</typeparam>
/// <param name="actionContext">The action context.</param>
/// <param name="executeCompleted">The action to invoke when the async execution completes.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private IAction Invoke<T>(ActionContext actionContext, Action executeCompleted = null)
where T : Actionflow<TView, TViewModel>, new()
{
T actionToRun = null;
try
{
actionToRun = Actionflow<TView, TViewModel>.New<T>(_view, _viewModel, actionContext);
}
catch (Exception exception)
{
ExceptionHandler.Handle(exception, Resources.ErrorMessageAction);
}
return Invoke(actionToRun, true, executeCompleted);
}
/// <summary>
/// Invokes the action.
/// </summary>
/// <typeparam name="T">The type of action to invoke.</typeparam>
/// <param name="arguments">The arguments.</param>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter",
Justification = "Required by called method.")]
public void InvokeAction<T>(params ActionContextEntry[] arguments)
where T : Actionflow<TView, TViewModel>, new()
{
var actionContext = ActionContext.New<T>(arguments);
Invoke<T>(actionContext);
}
/// <summary>
/// Invokes the action.
/// This call is for internal means only.
/// </summary>
/// <typeparam name="T">The type of action to invoke.</typeparam>
/// <param name="actionToRun">The action to run.</param>
/// <param name="disposeActionDuringCleanup">Dispose the action after execution, during cleanup.</param>
/// <param name="executeCompleted">The action to execute after completion.</param>
internal void InternalInvokeAction<T>(T actionToRun, bool disposeActionDuringCleanup = true, Action executeCompleted = null)
where T : Actionflow<TView, TViewModel>, new()
{
Invoke(actionToRun, disposeActionDuringCleanup, executeCompleted);
}
/// <summary>
/// Invokes the action.
/// </summary>
/// <typeparam name="T">The type of action to invoke.</typeparam>
/// <param name="arguments">The arguments.</param>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter",
Justification = "Required by called method.")]
public Task<bool> InvokeActionAsync<T>(params ActionContextEntry[] arguments)
where T : Actionflow<TView, TViewModel>, new()
{
var actionContext = ActionContext.New<T>(arguments);
var action = Invoke<T>(actionContext);
return action == null
? Task.FromResult(false)
: action.GetSuccessAsync();
}
}
}
| |
// 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.Concurrent;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public class HttpClientTest
{
[Fact]
public void Dispose_MultipleTimes_Success()
{
var client = new HttpClient();
client.Dispose();
client.Dispose();
}
[Fact]
public void DefaultRequestHeaders_Idempotent()
{
using (var client = new HttpClient())
{
Assert.NotNull(client.DefaultRequestHeaders);
Assert.Same(client.DefaultRequestHeaders, client.DefaultRequestHeaders);
}
}
[Fact]
public void BaseAddress_Roundtrip_Equal()
{
using (var client = new HttpClient())
{
Assert.Null(client.BaseAddress);
Uri uri = new Uri(CreateFakeUri());
client.BaseAddress = uri;
Assert.Equal(uri, client.BaseAddress);
client.BaseAddress = null;
Assert.Null(client.BaseAddress);
}
}
[Fact]
public void BaseAddress_InvalidUri_Throws()
{
using (var client = new HttpClient())
{
AssertExtensions.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("ftp://onlyhttpsupported"));
AssertExtensions.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("/onlyabsolutesupported", UriKind.Relative));
}
}
[Fact]
public void Timeout_Roundtrip_Equal()
{
using (var client = new HttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
Assert.Equal(Timeout.InfiniteTimeSpan, client.Timeout);
client.Timeout = TimeSpan.FromSeconds(1);
Assert.Equal(TimeSpan.FromSeconds(1), client.Timeout);
}
}
[Fact]
public void Timeout_OutOfRange_Throws()
{
using (var client = new HttpClient())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(-2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(int.MaxValue));
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17691")] // Difference in behavior
[Fact]
public void MaxResponseContentBufferSize_Roundtrip_Equal()
{
using (var client = new HttpClient())
{
client.MaxResponseContentBufferSize = 1;
Assert.Equal(1, client.MaxResponseContentBufferSize);
client.MaxResponseContentBufferSize = int.MaxValue;
Assert.Equal(int.MaxValue, client.MaxResponseContentBufferSize);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17691")] // Difference in behavior
[Fact]
public void MaxResponseContentBufferSize_OutOfRange_Throws()
{
using (var client = new HttpClient())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = -1);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = 0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = 1 + (long)int.MaxValue);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17691")] // Difference in behavior
[Fact]
public async Task MaxResponseContentBufferSize_TooSmallForContent_Throws()
{
using (var client = new HttpClient())
{
client.MaxResponseContentBufferSize = 1;
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(Configuration.Http.RemoteEchoServer));
}
}
[Fact]
public async Task Properties_CantChangeAfterOperation_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage()))))
{
(await client.GetAsync(CreateFakeUri())).Dispose();
Assert.Throws<InvalidOperationException>(() => client.BaseAddress = null);
Assert.Throws<InvalidOperationException>(() => client.Timeout = TimeSpan.FromSeconds(1));
Assert.Throws<InvalidOperationException>(() => client.MaxResponseContentBufferSize = 1);
}
}
[Theory]
[InlineData(null)]
[InlineData("/something.html")]
public void GetAsync_NoBaseAddress_InvalidUri_ThrowsException(string uri)
{
using (var client = new HttpClient())
{
Assert.Throws<InvalidOperationException>(() => { client.GetAsync(uri == null ? null : new Uri(uri, UriKind.RelativeOrAbsolute)); });
}
}
[Theory]
[InlineData(null)]
[InlineData("/")]
public async Task GetAsync_BaseAddress_ValidUri_Success(string uri)
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage()))))
{
client.BaseAddress = new Uri(CreateFakeUri());
using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task GetContentAsync_ErrorStatusCode_ExpectedExceptionThrown(bool withResponseContent)
{
using (var client = new HttpClient(new CustomResponseHandler(
(r,c) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = withResponseContent ? new ByteArrayContent(new byte[1]) : null
}))))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetByteArrayAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStreamAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_NullResponse_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult<HttpResponseMessage>(null))))
{
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => client.GetStringAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_NullResponseContent_ReturnsDefaultValue()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage() { Content = null }))))
{
Assert.Same(string.Empty, await client.GetStringAsync(CreateFakeUri()));
Assert.Same(Array.Empty<byte>(), await client.GetByteArrayAsync(CreateFakeUri()));
Assert.Same(Stream.Null, await client.GetStreamAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_SerializingContentThrows_Synchronous_Throws()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler(
(r, c) => Task.FromResult(new HttpResponseMessage() { Content = new CustomContent(stream => { throw e; }) }))))
{
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStringAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetByteArrayAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStreamAsync(CreateFakeUri())));
}
}
[Fact]
public async Task GetContentAsync_SerializingContentThrows_Asynchronous_Throws()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler(
(r, c) => Task.FromResult(new HttpResponseMessage() { Content = new CustomContent(stream => Task.FromException(e)) }))))
{
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStringAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetByteArrayAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStreamAsync(CreateFakeUri())));
}
}
[Fact]
public async Task GetAsync_InvalidUrl_ExpectedExceptionThrown()
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetPutPostDeleteAsync_Canceled_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
var content = new ByteArrayContent(new byte[1]);
var cts = new CancellationTokenSource();
Task t1 = client.GetAsync(CreateFakeUri(), cts.Token);
Task t2 = client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead, cts.Token);
Task t3 = client.PostAsync(CreateFakeUri(), content, cts.Token);
Task t4 = client.PutAsync(CreateFakeUri(), content, cts.Token);
Task t5 = client.DeleteAsync(CreateFakeUri(), cts.Token);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t1);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t2);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t3);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t4);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t5);
}
}
[Fact]
public async Task GetPutPostDeleteAsync_Success()
{
Action<HttpResponseMessage> verify = message => { using (message) Assert.Equal(HttpStatusCode.OK, message.StatusCode); };
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
verify(await client.GetAsync(CreateFakeUri()));
verify(await client.GetAsync(CreateFakeUri(), CancellationToken.None));
verify(await client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead));
verify(await client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead, CancellationToken.None));
verify(await client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])));
verify(await client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1]), CancellationToken.None));
verify(await client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])));
verify(await client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1]), CancellationToken.None));
verify(await client.DeleteAsync(CreateFakeUri()));
verify(await client.DeleteAsync(CreateFakeUri(), CancellationToken.None));
}
}
[Fact]
public void GetAsync_CustomException_Synchronous_ThrowsException()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler((r, c) => { throw e; })))
{
FormatException thrown = Assert.Throws<FormatException>(() => { client.GetAsync(CreateFakeUri()); });
Assert.Same(e, thrown);
}
}
[Fact]
public async Task GetAsync_CustomException_Asynchronous_ThrowsException()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromException<HttpResponseMessage>(e))))
{
FormatException thrown = await Assert.ThrowsAsync<FormatException>(() => client.GetAsync(CreateFakeUri()));
Assert.Same(e, thrown);
}
}
[Fact]
public void SendAsync_NullRequest_ThrowsException()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult<HttpResponseMessage>(null))))
{
AssertExtensions.Throws<ArgumentNullException>("request", () => { client.SendAsync(null); });
}
}
[Fact]
public async Task SendAsync_DuplicateRequest_ThrowsException()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
using (var request = new HttpRequestMessage(HttpMethod.Get, CreateFakeUri()))
{
(await client.SendAsync(request)).Dispose();
Assert.Throws<InvalidOperationException>(() => { client.SendAsync(request); });
}
}
[Fact]
public async Task SendAsync_RequestContentDisposed()
{
var content = new ByteArrayContent(new byte[1]);
using (var request = new HttpRequestMessage(HttpMethod.Get, CreateFakeUri()) { Content = content })
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
await client.SendAsync(request);
Assert.Throws<ObjectDisposedException>(() => { content.ReadAsStringAsync(); });
}
}
[Fact]
public void Dispose_UseAfterDispose_Throws()
{
var client = new HttpClient();
client.Dispose();
Assert.Throws<ObjectDisposedException>(() => client.BaseAddress = null);
Assert.Throws<ObjectDisposedException>(() => client.CancelPendingRequests());
Assert.Throws<ObjectDisposedException>(() => { client.DeleteAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetByteArrayAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetStreamAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetStringAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])); });
Assert.Throws<ObjectDisposedException>(() => { client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])); });
Assert.Throws<ObjectDisposedException>(() => { client.SendAsync(new HttpRequestMessage(HttpMethod.Get, CreateFakeUri())); });
Assert.Throws<ObjectDisposedException>(() => { client.Timeout = TimeSpan.FromSeconds(1); });
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void CancelAllPending_AllPendingOperationsCanceled(bool withInfiniteTimeout)
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
if (withInfiniteTimeout)
{
client.Timeout = Timeout.InfiniteTimeSpan;
}
Task<HttpResponseMessage>[] tasks = Enumerable.Range(0, 3).Select(_ => client.GetAsync(CreateFakeUri())).ToArray();
client.CancelPendingRequests();
Assert.All(tasks, task => Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult()));
}
}
[Fact]
public void Timeout_TooShort_AllPendingOperationsCanceled()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
client.Timeout = TimeSpan.FromMilliseconds(1);
Task<HttpResponseMessage>[] tasks = Enumerable.Range(0, 3).Select(_ => client.GetAsync(CreateFakeUri())).ToArray();
Assert.All(tasks, task => Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult()));
}
}
[Fact]
[OuterLoop("One second delay in getting server's response")]
public async Task Timeout_SetTo30AndGetResponseFromLoopbackQuickly_Success()
{
using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) })
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task getTask = client.GetStringAsync(url);
await Task.Delay(TimeSpan.FromSeconds(.5));
await TestHelper.WhenAllCompletedOrAnyFailed(
getTask,
LoopbackServer.ReadRequestAndSendResponseAsync(server));
});
}
}
private static string CreateFakeUri() => $"http://{Guid.NewGuid().ToString("N")}";
private static async Task<T> WhenCanceled<T>(CancellationToken cancellationToken)
{
await Task.Delay(-1, cancellationToken).ConfigureAwait(false);
return default(T);
}
private sealed class CustomResponseHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _func;
public CustomResponseHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> func) { _func = func; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return _func(request, cancellationToken);
}
}
private sealed class CustomContent : HttpContent
{
private readonly Func<Stream, Task> _func;
public CustomContent(Func<Stream, Task> func) { _func = func; }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return _func(stream);
}
protected override bool TryComputeLength(out long length)
{
length = 0;
return false;
}
}
}
}
| |
//
// Reflect.cs: Creates Element classes from an instance
//
// Author:
// Miguel de Icaza (miguel@gnome.org)
//
// Copyright 2010, Novell, Inc.
//
// Code licensed under the MIT X11 license
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using MonoTouch.UIKit;
using System.Drawing;
using MonoTouch.Foundation;
namespace MonoTouch.Dialog
{
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class EntryAttribute : Attribute {
public EntryAttribute () : this (null) { }
public EntryAttribute (string placeholder)
{
Placeholder = placeholder;
}
public string Placeholder;
public UIKeyboardType KeyboardType;
public UITextAutocorrectionType AutocorrectionType;
public UITextAutocapitalizationType AutocapitalizationType;
public UITextFieldViewMode ClearButtonMode;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class DateAttribute : Attribute { }
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class TimeAttribute : Attribute { }
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class CheckboxAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class MultilineAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class HtmlAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class SkipAttribute : Attribute {}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class PasswordAttribute : EntryAttribute {
public PasswordAttribute (string placeholder) : base (placeholder) {}
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class AlignmentAttribute : Attribute {
public AlignmentAttribute (UITextAlignment alignment) {
Alignment = alignment;
}
public UITextAlignment Alignment;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class RadioSelectionAttribute : Attribute {
public string Target;
public RadioSelectionAttribute (string target)
{
Target = target;
}
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class OnTapAttribute : Attribute {
public OnTapAttribute (string method)
{
Method = method;
}
public string Method;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class CaptionAttribute : Attribute {
public CaptionAttribute (string caption)
{
Caption = caption;
}
public string Caption;
}
[AttributeUsage (AttributeTargets.Field | AttributeTargets.Property, Inherited=false)]
public class SectionAttribute : Attribute {
public SectionAttribute () {}
public SectionAttribute (string caption)
{
Caption = caption;
}
public SectionAttribute (string caption, string footer)
{
Caption = caption;
Footer = footer;
}
public string Caption, Footer;
}
public class RangeAttribute : Attribute {
public RangeAttribute (float low, float high)
{
Low = low;
High = high;
}
public float Low, High;
public bool ShowCaption;
}
public class BindingContext : IDisposable {
public RootElement Root;
Dictionary<Element,MemberAndInstance> mappings;
class MemberAndInstance {
public MemberAndInstance (MemberInfo mi, object o)
{
Member = mi;
Obj = o;
}
public MemberInfo Member;
public object Obj;
}
static object GetValue (MemberInfo mi, object o)
{
var fi = mi as FieldInfo;
if (fi != null)
return fi.GetValue (o);
var pi = mi as PropertyInfo;
var getMethod = pi.GetGetMethod ();
return getMethod.Invoke (o, new object [0]);
}
static void SetValue (MemberInfo mi, object o, object val)
{
var fi = mi as FieldInfo;
if (fi != null){
fi.SetValue (o, val);
return;
}
var pi = mi as PropertyInfo;
var setMethod = pi.GetSetMethod ();
setMethod.Invoke (o, new object [] { val });
}
static string MakeCaption (string name)
{
var sb = new StringBuilder (name.Length);
bool nextUp = true;
foreach (char c in name){
if (nextUp){
sb.Append (Char.ToUpper (c));
nextUp = false;
} else {
if (c == '_'){
sb.Append (' ');
continue;
}
if (Char.IsUpper (c))
sb.Append (' ');
sb.Append (c);
}
}
return sb.ToString ();
}
// Returns the type for fields and properties and null for everything else
static Type GetTypeForMember (MemberInfo mi)
{
if (mi is FieldInfo)
return ((FieldInfo) mi).FieldType;
else if (mi is PropertyInfo)
return ((PropertyInfo) mi).PropertyType;
return null;
}
public BindingContext (object callbacks, object o, string title)
{
if (o == null)
throw new ArgumentNullException ("o");
mappings = new Dictionary<Element,MemberAndInstance> ();
Root = new RootElement (title);
Populate (callbacks, o, Root);
}
void Populate (object callbacks, object o, RootElement root)
{
MemberInfo last_radio_index = null;
var members = o.GetType ().GetMembers (BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance);
Section section = null;
foreach (var mi in members){
Type mType = GetTypeForMember (mi);
if (mType == null)
continue;
string caption = null;
object [] attrs = mi.GetCustomAttributes (false);
bool skip = false;
foreach (var attr in attrs){
if (attr is SkipAttribute || attr is System.Runtime.CompilerServices.CompilerGeneratedAttribute)
skip = true;
else if (attr is CaptionAttribute)
caption = ((CaptionAttribute) attr).Caption;
else if (attr is SectionAttribute){
if (section != null)
root.Add (section);
var sa = attr as SectionAttribute;
section = new Section (sa.Caption, sa.Footer);
}
}
if (skip)
continue;
if (caption == null)
caption = MakeCaption (mi.Name);
if (section == null)
section = new Section ();
Element element = null;
if (mType == typeof (string)){
PasswordAttribute pa = null;
AlignmentAttribute align = null;
EntryAttribute ea = null;
object html = null;
NSAction invoke = null;
bool multi = false;
foreach (object attr in attrs){
if (attr is PasswordAttribute)
pa = attr as PasswordAttribute;
else if (attr is EntryAttribute)
ea = attr as EntryAttribute;
else if (attr is MultilineAttribute)
multi = true;
else if (attr is HtmlAttribute)
html = attr;
else if (attr is AlignmentAttribute)
align = attr as AlignmentAttribute;
if (attr is OnTapAttribute){
string mname = ((OnTapAttribute) attr).Method;
if (callbacks == null){
throw new Exception ("Your class contains [OnTap] attributes, but you passed a null object for `context' in the constructor");
}
var method = callbacks.GetType ().GetMethod (mname);
if (method == null)
throw new Exception ("Did not find method " + mname);
invoke = delegate {
method.Invoke (method.IsStatic ? null : callbacks, new object [0]);
};
}
}
string value = (string) GetValue (mi, o);
if (pa != null)
element = new EntryElement (caption, pa.Placeholder, value, true);
else if (ea != null)
element = new EntryElement (caption, ea.Placeholder, value) { KeyboardType = ea.KeyboardType, AutocapitalizationType = ea.AutocapitalizationType, AutocorrectionType = ea.AutocorrectionType, ClearButtonMode = ea.ClearButtonMode };
else if (multi)
element = new MultilineElement (caption, value);
else if (html != null)
element = new HtmlElement (caption, value);
else {
var selement = new StringElement (caption, value);
element = selement;
if (align != null)
selement.Alignment = align.Alignment;
}
if (invoke != null)
((StringElement) element).Tapped += invoke;
} else if (mType == typeof (float)){
var floatElement = new FloatElement (null, null, (float) GetValue (mi, o));
floatElement.Caption = caption;
element = floatElement;
foreach (object attr in attrs){
if (attr is RangeAttribute){
var ra = attr as RangeAttribute;
floatElement.MinValue = ra.Low;
floatElement.MaxValue = ra.High;
floatElement.ShowCaption = ra.ShowCaption;
}
}
} else if (mType == typeof (bool)){
bool checkbox = false;
foreach (object attr in attrs){
if (attr is CheckboxAttribute)
checkbox = true;
}
if (checkbox)
element = new CheckboxElement (caption, (bool) GetValue (mi, o));
else
element = new BooleanElement (caption, (bool) GetValue (mi, o));
} else if (mType == typeof (DateTime)){
var dateTime = (DateTime) GetValue (mi, o);
bool asDate = false, asTime = false;
foreach (object attr in attrs){
if (attr is DateAttribute)
asDate = true;
else if (attr is TimeAttribute)
asTime = true;
}
if (asDate)
element = new DateElement (caption, dateTime);
else if (asTime)
element = new TimeElement (caption, dateTime);
else
element = new DateTimeElement (caption, dateTime);
} else if (mType.IsEnum){
var csection = new Section ();
ulong evalue = Convert.ToUInt64 (GetValue (mi, o), null);
int idx = 0;
int selected = 0;
foreach (var fi in mType.GetFields (BindingFlags.Public | BindingFlags.Static)){
ulong v = Convert.ToUInt64 (GetValue (fi, null));
if (v == evalue)
selected = idx;
CaptionAttribute ca = Attribute.GetCustomAttribute(fi, typeof(CaptionAttribute)) as CaptionAttribute;
csection.Add (new RadioElement (ca != null ? ca.Caption : MakeCaption (fi.Name)));
idx++;
}
element = new RootElement (caption, new RadioGroup (null, selected)) { csection };
} else if (mType == typeof (UIImage)){
element = new ImageElement ((UIImage) GetValue (mi, o));
} else if (typeof (System.Collections.IEnumerable).IsAssignableFrom (mType)){
var csection = new Section ();
int count = 0;
if (last_radio_index == null)
throw new Exception ("IEnumerable found, but no previous int found");
foreach (var e in (IEnumerable) GetValue (mi, o)){
csection.Add (new RadioElement (e.ToString ()));
count++;
}
int selected = (int) GetValue (last_radio_index, o);
if (selected >= count || selected < 0)
selected = 0;
element = new RootElement (caption, new MemberRadioGroup (null, selected, last_radio_index)) { csection };
last_radio_index = null;
} else if (typeof (int) == mType){
foreach (object attr in attrs){
if (attr is RadioSelectionAttribute){
last_radio_index = mi;
break;
}
}
} else {
var nested = GetValue (mi, o);
if (nested != null){
var newRoot = new RootElement (caption);
Populate (callbacks, nested, newRoot);
element = newRoot;
}
}
if (element == null)
continue;
section.Add (element);
mappings [element] = new MemberAndInstance (mi, o);
}
root.Add (section);
}
class MemberRadioGroup : RadioGroup {
public MemberInfo mi;
public MemberRadioGroup (string key, int selected, MemberInfo mi) : base (key, selected)
{
this.mi = mi;
}
}
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing){
foreach (var element in mappings.Keys){
element.Dispose ();
}
mappings = null;
}
}
public void Fetch ()
{
foreach (var dk in mappings){
Element element = dk.Key;
MemberInfo mi = dk.Value.Member;
object obj = dk.Value.Obj;
if (element is DateTimeElement)
SetValue (mi, obj, ((DateTimeElement) element).DateValue);
else if (element is FloatElement)
SetValue (mi, obj, ((FloatElement) element).Value);
else if (element is BooleanElement)
SetValue (mi, obj, ((BooleanElement) element).Value);
else if (element is CheckboxElement)
SetValue (mi, obj, ((CheckboxElement) element).Value);
else if (element is EntryElement){
var entry = (EntryElement) element;
entry.FetchValue ();
SetValue (mi, obj, entry.Value);
} else if (element is ImageElement)
SetValue (mi, obj, ((ImageElement) element).Value);
else if (element is RootElement){
var re = element as RootElement;
if (re.group as MemberRadioGroup != null){
var group = re.group as MemberRadioGroup;
SetValue (group.mi, obj, re.RadioSelected);
} else if (re.group as RadioGroup != null){
var mType = GetTypeForMember (mi);
var fi = mType.GetFields (BindingFlags.Public | BindingFlags.Static) [re.RadioSelected];
SetValue (mi, obj, fi.GetValue (null));
}
}
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Dataproc.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedWorkflowTemplateServiceClientTest
{
[xunit::FactAttribute]
public void CreateWorkflowTemplateRequestObject()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateWorkflowTemplateRequest request = new CreateWorkflowTemplateRequest
{
ParentAsRegionName = RegionName.FromProjectRegion("[PROJECT]", "[REGION]"),
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.CreateWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate response = client.CreateWorkflowTemplate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateWorkflowTemplateRequestObjectAsync()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateWorkflowTemplateRequest request = new CreateWorkflowTemplateRequest
{
ParentAsRegionName = RegionName.FromProjectRegion("[PROJECT]", "[REGION]"),
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.CreateWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WorkflowTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate responseCallSettings = await client.CreateWorkflowTemplateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WorkflowTemplate responseCancellationToken = await client.CreateWorkflowTemplateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateWorkflowTemplate()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateWorkflowTemplateRequest request = new CreateWorkflowTemplateRequest
{
ParentAsRegionName = RegionName.FromProjectRegion("[PROJECT]", "[REGION]"),
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.CreateWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate response = client.CreateWorkflowTemplate(request.Parent, request.Template);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateWorkflowTemplateAsync()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateWorkflowTemplateRequest request = new CreateWorkflowTemplateRequest
{
ParentAsRegionName = RegionName.FromProjectRegion("[PROJECT]", "[REGION]"),
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.CreateWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WorkflowTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate responseCallSettings = await client.CreateWorkflowTemplateAsync(request.Parent, request.Template, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WorkflowTemplate responseCancellationToken = await client.CreateWorkflowTemplateAsync(request.Parent, request.Template, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateWorkflowTemplateResourceNames1()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateWorkflowTemplateRequest request = new CreateWorkflowTemplateRequest
{
ParentAsRegionName = RegionName.FromProjectRegion("[PROJECT]", "[REGION]"),
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.CreateWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate response = client.CreateWorkflowTemplate(request.ParentAsRegionName, request.Template);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateWorkflowTemplateResourceNames1Async()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateWorkflowTemplateRequest request = new CreateWorkflowTemplateRequest
{
ParentAsRegionName = RegionName.FromProjectRegion("[PROJECT]", "[REGION]"),
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.CreateWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WorkflowTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate responseCallSettings = await client.CreateWorkflowTemplateAsync(request.ParentAsRegionName, request.Template, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WorkflowTemplate responseCancellationToken = await client.CreateWorkflowTemplateAsync(request.ParentAsRegionName, request.Template, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateWorkflowTemplateResourceNames2()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateWorkflowTemplateRequest request = new CreateWorkflowTemplateRequest
{
ParentAsRegionName = RegionName.FromProjectRegion("[PROJECT]", "[REGION]"),
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.CreateWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate response = client.CreateWorkflowTemplate(request.ParentAsLocationName, request.Template);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateWorkflowTemplateResourceNames2Async()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateWorkflowTemplateRequest request = new CreateWorkflowTemplateRequest
{
ParentAsRegionName = RegionName.FromProjectRegion("[PROJECT]", "[REGION]"),
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.CreateWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WorkflowTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate responseCallSettings = await client.CreateWorkflowTemplateAsync(request.ParentAsLocationName, request.Template, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WorkflowTemplate responseCancellationToken = await client.CreateWorkflowTemplateAsync(request.ParentAsLocationName, request.Template, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkflowTemplateRequestObject()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowTemplateRequest request = new GetWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Version = 271578922,
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.GetWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate response = client.GetWorkflowTemplate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkflowTemplateRequestObjectAsync()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowTemplateRequest request = new GetWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Version = 271578922,
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.GetWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WorkflowTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate responseCallSettings = await client.GetWorkflowTemplateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WorkflowTemplate responseCancellationToken = await client.GetWorkflowTemplateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkflowTemplate()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowTemplateRequest request = new GetWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.GetWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate response = client.GetWorkflowTemplate(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkflowTemplateAsync()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowTemplateRequest request = new GetWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.GetWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WorkflowTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate responseCallSettings = await client.GetWorkflowTemplateAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WorkflowTemplate responseCancellationToken = await client.GetWorkflowTemplateAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkflowTemplateResourceNames()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowTemplateRequest request = new GetWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.GetWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate response = client.GetWorkflowTemplate(request.WorkflowTemplateName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkflowTemplateResourceNamesAsync()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowTemplateRequest request = new GetWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.GetWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WorkflowTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate responseCallSettings = await client.GetWorkflowTemplateAsync(request.WorkflowTemplateName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WorkflowTemplate responseCancellationToken = await client.GetWorkflowTemplateAsync(request.WorkflowTemplateName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateWorkflowTemplateRequestObject()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateWorkflowTemplateRequest request = new UpdateWorkflowTemplateRequest
{
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.UpdateWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate response = client.UpdateWorkflowTemplate(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateWorkflowTemplateRequestObjectAsync()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateWorkflowTemplateRequest request = new UpdateWorkflowTemplateRequest
{
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.UpdateWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WorkflowTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate responseCallSettings = await client.UpdateWorkflowTemplateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WorkflowTemplate responseCancellationToken = await client.UpdateWorkflowTemplateAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateWorkflowTemplate()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateWorkflowTemplateRequest request = new UpdateWorkflowTemplateRequest
{
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.UpdateWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate response = client.UpdateWorkflowTemplate(request.Template);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateWorkflowTemplateAsync()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateWorkflowTemplateRequest request = new UpdateWorkflowTemplateRequest
{
Template = new WorkflowTemplate(),
};
WorkflowTemplate expectedResponse = new WorkflowTemplate
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Id = "id74b70bb8",
Version = 271578922,
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
Placement = new WorkflowTemplatePlacement(),
Jobs = { new OrderedJob(), },
Parameters =
{
new TemplateParameter(),
},
DagTimeout = new wkt::Duration(),
};
mockGrpcClient.Setup(x => x.UpdateWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<WorkflowTemplate>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
WorkflowTemplate responseCallSettings = await client.UpdateWorkflowTemplateAsync(request.Template, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
WorkflowTemplate responseCancellationToken = await client.UpdateWorkflowTemplateAsync(request.Template, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteWorkflowTemplateRequestObject()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkflowTemplateRequest request = new DeleteWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Version = 271578922,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteWorkflowTemplate(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteWorkflowTemplateRequestObjectAsync()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkflowTemplateRequest request = new DeleteWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
Version = 271578922,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteWorkflowTemplateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteWorkflowTemplateAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteWorkflowTemplate()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkflowTemplateRequest request = new DeleteWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteWorkflowTemplate(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteWorkflowTemplateAsync()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkflowTemplateRequest request = new DeleteWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteWorkflowTemplateAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteWorkflowTemplateAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteWorkflowTemplateResourceNames()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkflowTemplateRequest request = new DeleteWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkflowTemplate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteWorkflowTemplate(request.WorkflowTemplateName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteWorkflowTemplateResourceNamesAsync()
{
moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient> mockGrpcClient = new moq::Mock<WorkflowTemplateService.WorkflowTemplateServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteWorkflowTemplateRequest request = new DeleteWorkflowTemplateRequest
{
WorkflowTemplateName = WorkflowTemplateName.FromProjectRegionWorkflowTemplate("[PROJECT]", "[REGION]", "[WORKFLOW_TEMPLATE]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteWorkflowTemplateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowTemplateServiceClient client = new WorkflowTemplateServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteWorkflowTemplateAsync(request.WorkflowTemplateName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteWorkflowTemplateAsync(request.WorkflowTemplateName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache.Store
{
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Resource;
[SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Local")]
public class CacheTestStore : ICacheStore
{
public static readonly IDictionary Map = new ConcurrentDictionary<object, object>();
public static bool LoadMultithreaded;
public static bool LoadObjects;
public static bool ThrowError;
[InstanceResource]
private IIgnite _grid = null;
[StoreSessionResource]
#pragma warning disable 649
private ICacheStoreSession _ses;
#pragma warning restore 649
public static int intProperty;
public static string stringProperty;
public static void Reset()
{
Map.Clear();
LoadMultithreaded = false;
LoadObjects = false;
ThrowError = false;
}
public void LoadCache(Action<object, object> act, params object[] args)
{
ThrowIfNeeded();
Debug.Assert(_grid != null);
if (args == null || args.Length == 0)
return;
if (args.Length == 3 && args[0] == null)
{
// Testing arguments passing.
var key = args[1];
var val = args[2];
act(key, val);
return;
}
if (LoadMultithreaded)
{
int cnt = 0;
TestUtils.RunMultiThreaded(() => {
int i;
while ((i = Interlocked.Increment(ref cnt) - 1) < 1000)
act(i, "val_" + i);
}, 8);
}
else
{
int start = (int)args[0];
int cnt = (int)args[1];
for (int i = start; i < start + cnt; i++)
{
if (LoadObjects)
act(new Key(i), new Value(i));
else
act(i, "val_" + i);
}
}
}
public object Load(object key)
{
ThrowIfNeeded();
Debug.Assert(_grid != null);
return Map[key];
}
public IDictionary LoadAll(ICollection keys)
{
ThrowIfNeeded();
Debug.Assert(_grid != null);
return keys.OfType<object>().ToDictionary(key => key, key => "val_" + key);
}
public void Write(object key, object val)
{
ThrowIfNeeded();
Debug.Assert(_grid != null);
Map[key] = val;
}
public void WriteAll(IDictionary map)
{
ThrowIfNeeded();
Debug.Assert(_grid != null);
foreach (DictionaryEntry e in map)
Map[e.Key] = e.Value;
}
public void Delete(object key)
{
ThrowIfNeeded();
Debug.Assert(_grid != null);
Map.Remove(key);
}
public void DeleteAll(ICollection keys)
{
ThrowIfNeeded();
Debug.Assert(_grid != null);
foreach (object key in keys)
Map.Remove(key);
}
public void SessionEnd(bool commit)
{
Debug.Assert(_grid != null);
Debug.Assert(_ses != null);
}
public int IntProperty
{
get { return intProperty; }
set { intProperty = value; }
}
public string StringProperty
{
get { return stringProperty; }
set { stringProperty = value; }
}
private static void ThrowIfNeeded()
{
if (ThrowError)
throw new CustomStoreException("Exception in cache store");
}
[Serializable]
public class CustomStoreException : Exception, ISerializable
{
public string Details { get; private set; }
public CustomStoreException(string message) : base(message)
{
Details = message;
}
protected CustomStoreException(SerializationInfo info, StreamingContext ctx) : base(info, ctx)
{
Details = info.GetString("details");
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("details", Details);
base.GetObjectData(info, context);
}
}
}
}
| |
/* ****************************************************************************
*
* 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
* dlr@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.Collections;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
namespace IronPython.Compiler {
public delegate object CallTarget0();
internal static class PythonCallTargets {
public static object OriginalCallTargetN(PythonFunction function, params object[] args) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object[], object>)function.__code__.Target)(function, args);
}
#region Generated Python Lazy Call Targets
// *** BEGIN GENERATED CODE ***
// generated by function: gen_lazy_call_targets from: generate_calls.py
public static object OriginalCallTarget0(PythonFunction function) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object>)function.__code__.Target)(function);
}
public static object OriginalCallTarget1(PythonFunction function, object arg0) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object>)function.__code__.Target)(function, arg0);
}
public static object OriginalCallTarget2(PythonFunction function, object arg0, object arg1) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object>)function.__code__.Target)(function, arg0, arg1);
}
public static object OriginalCallTarget3(PythonFunction function, object arg0, object arg1, object arg2) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2);
}
public static object OriginalCallTarget4(PythonFunction function, object arg0, object arg1, object arg2, object arg3) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3);
}
public static object OriginalCallTarget5(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4);
}
public static object OriginalCallTarget6(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5);
}
public static object OriginalCallTarget7(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
}
public static object OriginalCallTarget8(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
}
public static object OriginalCallTarget9(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
}
public static object OriginalCallTarget10(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
}
public static object OriginalCallTarget11(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
}
public static object OriginalCallTarget12(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11);
}
public static object OriginalCallTarget13(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
}
public static object OriginalCallTarget14(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13);
}
public static object OriginalCallTarget15(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14) {
function.__code__.LazyCompileFirstTarget(function);
return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14);
}
// *** END GENERATED CODE ***
#endregion
public const int MaxArgs = 15;
internal static Type GetPythonTargetType(bool wrapper, int parameters, out Delegate originalTarget) {
if (!wrapper) {
switch (parameters) {
#region Generated Python Call Target Switch
// *** BEGIN GENERATED CODE ***
// generated by function: gen_python_switch from: generate_calls.py
case 0:
originalTarget = (Func<PythonFunction, object>)OriginalCallTarget0;
return typeof(Func<PythonFunction, object>);
case 1:
originalTarget = (Func<PythonFunction, object, object>)OriginalCallTarget1;
return typeof(Func<PythonFunction, object, object>);
case 2:
originalTarget = (Func<PythonFunction, object, object, object>)OriginalCallTarget2;
return typeof(Func<PythonFunction, object, object, object>);
case 3:
originalTarget = (Func<PythonFunction, object, object, object, object>)OriginalCallTarget3;
return typeof(Func<PythonFunction, object, object, object, object>);
case 4:
originalTarget = (Func<PythonFunction, object, object, object, object, object>)OriginalCallTarget4;
return typeof(Func<PythonFunction, object, object, object, object, object>);
case 5:
originalTarget = (Func<PythonFunction, object, object, object, object, object, object>)OriginalCallTarget5;
return typeof(Func<PythonFunction, object, object, object, object, object, object>);
case 6:
originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object>)OriginalCallTarget6;
return typeof(Func<PythonFunction, object, object, object, object, object, object, object>);
case 7:
originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object>)OriginalCallTarget7;
return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object>);
case 8:
originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object>)OriginalCallTarget8;
return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object>);
case 9:
originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget9;
return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>);
case 10:
originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget10;
return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>);
case 11:
originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget11;
return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>);
case 12:
originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget12;
return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>);
case 13:
originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget13;
return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>);
case 14:
originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget14;
return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>);
case 15:
originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget15;
return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>);
// *** END GENERATED CODE ***
#endregion
}
}
originalTarget = (Func<PythonFunction, object[], object>)OriginalCallTargetN;
return typeof(Func<PythonFunction, object[], object>);
}
}
internal class PythonFunctionRecursionCheckN {
private readonly Func<PythonFunction, object[], object> _target;
public PythonFunctionRecursionCheckN(Func<PythonFunction, object[], object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object[] args) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, args);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
#region Generated Python Recursion Enforcement
// *** BEGIN GENERATED CODE ***
// generated by function: gen_recursion_checks from: generate_calls.py
internal class PythonFunctionRecursionCheck0 {
private readonly Func<PythonFunction, object> _target;
public PythonFunctionRecursionCheck0(Func<PythonFunction, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck1 {
private readonly Func<PythonFunction, object, object> _target;
public PythonFunctionRecursionCheck1(Func<PythonFunction, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck2 {
private readonly Func<PythonFunction, object, object, object> _target;
public PythonFunctionRecursionCheck2(Func<PythonFunction, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck3 {
private readonly Func<PythonFunction, object, object, object, object> _target;
public PythonFunctionRecursionCheck3(Func<PythonFunction, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck4 {
private readonly Func<PythonFunction, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck4(Func<PythonFunction, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck5 {
private readonly Func<PythonFunction, object, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck5(Func<PythonFunction, object, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3, arg4);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck6 {
private readonly Func<PythonFunction, object, object, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck6(Func<PythonFunction, object, object, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3, arg4, arg5);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck7 {
private readonly Func<PythonFunction, object, object, object, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck7(Func<PythonFunction, object, object, object, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck8 {
private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck8(Func<PythonFunction, object, object, object, object, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck9 {
private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck9(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck10 {
private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck10(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck11 {
private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck11(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck12 {
private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck12(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck13 {
private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck13(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck14 {
private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck14(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
internal class PythonFunctionRecursionCheck15 {
private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target;
public PythonFunctionRecursionCheck15(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) {
_target = target;
}
public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14) {
PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext);
try {
return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14);
} finally {
PythonOps.FunctionPopFrame();
}
}
}
// *** END GENERATED CODE ***
#endregion
}
| |
#if UNITY_WSA
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
#if UNITY_WSA_10_0
using Win10Interface;
#elif UNITY_WP_8_1
using Win81Interface;
#elif UNITY_WSA
using WinWsInterface;
#endif
namespace com.adjust.sdk
{
public class AdjustWindows
{
private const string sdkPrefix = "unity4.29.7";
private static bool appLaunched = false;
public static void Start(AdjustConfig adjustConfig)
{
string logLevelString = null;
string environment = adjustConfig.environment.ToLowercaseString();
Action<Dictionary<string, string>> attributionChangedAction = null;
Action<Dictionary<string, string>> sessionSuccessChangedAction = null;
Action<Dictionary<string, string>> sessionFailureChangedAction = null;
Action<Dictionary<string, string>> eventSuccessChangedAction = null;
Action<Dictionary<string, string>> eventFailureChangedAction = null;
Func<string, bool> deeplinkResponseFunc = null;
if (adjustConfig.logLevel.HasValue)
{
logLevelString = adjustConfig.logLevel.Value.ToLowercaseString();
}
if (adjustConfig.attributionChangedDelegate != null)
{
attributionChangedAction = (attributionMap) =>
{
var attribution = new AdjustAttribution(attributionMap);
adjustConfig.attributionChangedDelegate(attribution);
};
}
if (adjustConfig.sessionSuccessDelegate != null)
{
sessionSuccessChangedAction = (sessionMap) =>
{
var sessionData = new AdjustSessionSuccess(sessionMap);
adjustConfig.sessionSuccessDelegate(sessionData);
};
}
if (adjustConfig.sessionFailureDelegate != null)
{
sessionFailureChangedAction = (sessionMap) =>
{
var sessionData = new AdjustSessionFailure(sessionMap);
adjustConfig.sessionFailureDelegate(sessionData);
};
}
if (adjustConfig.eventSuccessDelegate != null)
{
eventSuccessChangedAction = (eventMap) =>
{
var eventData = new AdjustEventSuccess(eventMap);
adjustConfig.eventSuccessDelegate(eventData);
};
}
if (adjustConfig.eventFailureDelegate != null)
{
eventFailureChangedAction = (eventMap) =>
{
var eventData = new AdjustEventFailure(eventMap);
adjustConfig.eventFailureDelegate(eventData);
};
}
if (adjustConfig.deferredDeeplinkDelegate != null)
{
deeplinkResponseFunc = uri =>
{
if (adjustConfig.launchDeferredDeeplink)
{
adjustConfig.deferredDeeplinkDelegate(uri);
}
return adjustConfig.launchDeferredDeeplink;
};
}
bool sendInBackground = false;
if (adjustConfig.sendInBackground.HasValue)
{
sendInBackground = adjustConfig.sendInBackground.Value;
}
double delayStartSeconds = 0;
if (adjustConfig.delayStart.HasValue)
{
delayStartSeconds = adjustConfig.delayStart.Value;
}
AdjustConfigDto adjustConfigDto = new AdjustConfigDto {
AppToken = adjustConfig.appToken,
Environment = environment,
SdkPrefix = sdkPrefix,
SendInBackground = sendInBackground,
DelayStart = delayStartSeconds,
UserAgent = adjustConfig.userAgent,
DefaultTracker = adjustConfig.defaultTracker,
EventBufferingEnabled = adjustConfig.eventBufferingEnabled,
LaunchDeferredDeeplink = adjustConfig.launchDeferredDeeplink,
LogLevelString = logLevelString,
LogDelegate = adjustConfig.logDelegate,
ActionAttributionChangedData = attributionChangedAction,
ActionSessionSuccessData = sessionSuccessChangedAction,
ActionSessionFailureData = sessionFailureChangedAction,
ActionEventSuccessData = eventSuccessChangedAction,
ActionEventFailureData = eventFailureChangedAction,
FuncDeeplinkResponseData = deeplinkResponseFunc,
IsDeviceKnown = adjustConfig.isDeviceKnown,
SecretId = adjustConfig.secretId,
Info1 = adjustConfig.info1,
Info2 = adjustConfig.info2,
Info3 = adjustConfig.info3,
Info4 = adjustConfig.info4
};
AdjustWinInterface.ApplicationLaunching(adjustConfigDto);
AdjustWinInterface.ApplicationActivated();
appLaunched = true;
}
public static void TrackEvent(AdjustEvent adjustEvent)
{
AdjustWinInterface.TrackEvent(
eventToken: adjustEvent.eventToken,
revenue: adjustEvent.revenue,
currency: adjustEvent.currency,
purchaseId: adjustEvent.transactionId,
callbackId: adjustEvent.callbackId,
callbackList: adjustEvent.callbackList,
partnerList: adjustEvent.partnerList
);
}
public static bool IsEnabled()
{
return AdjustWinInterface.IsEnabled();
}
public static void OnResume()
{
if (!appLaunched)
{
return;
}
AdjustWinInterface.ApplicationActivated();
}
public static void OnPause()
{
AdjustWinInterface.ApplicationDeactivated();
}
public static void SetEnabled(bool enabled)
{
AdjustWinInterface.SetEnabled(enabled);
}
public static void SetOfflineMode(bool offlineMode)
{
AdjustWinInterface.SetOfflineMode(offlineMode);
}
public static void SendFirstPackages()
{
AdjustWinInterface.SendFirstPackages();
}
public static void SetDeviceToken(string deviceToken)
{
AdjustWinInterface.SetDeviceToken(deviceToken);
}
public static void AppWillOpenUrl(string url)
{
AdjustWinInterface.AppWillOpenUrl(url);
}
public static void AddSessionPartnerParameter(string key, string value)
{
AdjustWinInterface.AddSessionPartnerParameter(key, value);
}
public static void AddSessionCallbackParameter(string key, string value)
{
AdjustWinInterface.AddSessionCallbackParameter(key, value);
}
public static void RemoveSessionPartnerParameter(string key)
{
AdjustWinInterface.RemoveSessionPartnerParameter(key);
}
public static void RemoveSessionCallbackParameter(string key)
{
AdjustWinInterface.RemoveSessionCallbackParameter(key);
}
public static void ResetSessionPartnerParameters()
{
AdjustWinInterface.ResetSessionPartnerParameters();
}
public static void ResetSessionCallbackParameters()
{
AdjustWinInterface.ResetSessionCallbackParameters();
}
public static string GetAdid()
{
return AdjustWinInterface.GetAdid();
}
public static string GetSdkVersion()
{
return sdkPrefix + "@" + AdjustWinInterface.GetSdkVersion();
}
public static AdjustAttribution GetAttribution()
{
var attributionMap = AdjustWinInterface.GetAttribution();
if (attributionMap == null)
{
return new AdjustAttribution();
}
return new AdjustAttribution(attributionMap);
}
public static void GdprForgetMe()
{
AdjustWinInterface.GdprForgetMe();
}
public static string GetWinAdId()
{
return AdjustWinInterface.GetWindowsAdId();
}
public static void SetTestOptions(Dictionary<string, string> testOptions)
{
string basePath = testOptions.ContainsKey(AdjustUtils.KeyTestOptionsBasePath) ?
testOptions[AdjustUtils.KeyTestOptionsBasePath] : null;
string gdprPath = testOptions.ContainsKey(AdjustUtils.KeyTestOptionsGdprPath) ?
testOptions[AdjustUtils.KeyTestOptionsGdprPath] : null;
long timerIntervalMls = -1;
long timerStartMls = -1;
long sessionIntMls = -1;
long subsessionIntMls = -1;
bool teardown = false;
bool deleteState = false;
bool noBackoffWait = false;
if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsTimerIntervalInMilliseconds))
{
timerIntervalMls = long.Parse(testOptions[AdjustUtils.KeyTestOptionsTimerIntervalInMilliseconds]);
}
if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsTimerStartInMilliseconds))
{
timerStartMls = long.Parse(testOptions[AdjustUtils.KeyTestOptionsTimerStartInMilliseconds]);
}
if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsSessionIntervalInMilliseconds))
{
sessionIntMls = long.Parse(testOptions[AdjustUtils.KeyTestOptionsSessionIntervalInMilliseconds]);
}
if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsSubsessionIntervalInMilliseconds))
{
subsessionIntMls = long.Parse(testOptions[AdjustUtils.KeyTestOptionsSubsessionIntervalInMilliseconds]);
}
if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsTeardown))
{
teardown = testOptions[AdjustUtils.KeyTestOptionsTeardown].ToLower() == "true";
}
if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsDeleteState))
{
deleteState = testOptions[AdjustUtils.KeyTestOptionsDeleteState].ToLower() == "true";
}
if (testOptions.ContainsKey(AdjustUtils.KeyTestOptionsNoBackoffWait))
{
noBackoffWait = testOptions[AdjustUtils.KeyTestOptionsNoBackoffWait].ToLower() == "true";
}
Type testLibInterfaceType = Type.GetType("TestLibraryInterface.TestLibraryInterface, TestLibraryInterface");
Type adjustTestOptionsDtoType = Type.GetType("TestLibraryInterface.AdjustTestOptionsDto, TestLibraryInterface");
if (testLibInterfaceType == null || adjustTestOptionsDtoType == null)
{
return;
}
PropertyInfo baseUrlInfo = adjustTestOptionsDtoType.GetProperty("BaseUrl");
PropertyInfo gdprUrlInfo = adjustTestOptionsDtoType.GetProperty("GdprUrl");
PropertyInfo basePathInfo = adjustTestOptionsDtoType.GetProperty("BasePath");
PropertyInfo gdprPathInfo = adjustTestOptionsDtoType.GetProperty("GdprPath");
PropertyInfo sessionIntervalInMillisecondsInfo = adjustTestOptionsDtoType.GetProperty("SessionIntervalInMilliseconds");
PropertyInfo subsessionIntervalInMillisecondsInfo = adjustTestOptionsDtoType.GetProperty("SubsessionIntervalInMilliseconds");
PropertyInfo timerIntervalInMillisecondsInfo = adjustTestOptionsDtoType.GetProperty("TimerIntervalInMilliseconds");
PropertyInfo timerStartInMillisecondsInfo = adjustTestOptionsDtoType.GetProperty("TimerStartInMilliseconds");
PropertyInfo deleteStateInfo = adjustTestOptionsDtoType.GetProperty("DeleteState");
PropertyInfo teardownInfo = adjustTestOptionsDtoType.GetProperty("Teardown");
PropertyInfo noBackoffWaitInfo = adjustTestOptionsDtoType.GetProperty("NoBackoffWait");
object adjustTestOptionsDtoInstance = Activator.CreateInstance(adjustTestOptionsDtoType);
baseUrlInfo.SetValue(adjustTestOptionsDtoInstance, testOptions[AdjustUtils.KeyTestOptionsBaseUrl], null);
gdprUrlInfo.SetValue(adjustTestOptionsDtoInstance, testOptions[AdjustUtils.KeyTestOptionsGdprUrl], null);
basePathInfo.SetValue(adjustTestOptionsDtoInstance, basePath, null);
gdprPathInfo.SetValue(adjustTestOptionsDtoInstance, gdprPath, null);
sessionIntervalInMillisecondsInfo.SetValue(adjustTestOptionsDtoInstance, sessionIntMls, null);
subsessionIntervalInMillisecondsInfo.SetValue(adjustTestOptionsDtoInstance, subsessionIntMls, null);
timerIntervalInMillisecondsInfo.SetValue(adjustTestOptionsDtoInstance, timerIntervalMls, null);
timerStartInMillisecondsInfo.SetValue(adjustTestOptionsDtoInstance, timerStartMls, null);
deleteStateInfo.SetValue(adjustTestOptionsDtoInstance, deleteState, null);
teardownInfo.SetValue(adjustTestOptionsDtoInstance, teardown, null);
noBackoffWaitInfo.SetValue(adjustTestOptionsDtoInstance, noBackoffWait, null);
MethodInfo setTestOptionsMethodInfo = testLibInterfaceType.GetMethod("SetTestOptions");
setTestOptionsMethodInfo.Invoke(null, new object[] { adjustTestOptionsDtoInstance });
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Newtonsoft.Json;
using NFluent;
using WireMock.Admin.Mappings;
using WireMock.Matchers;
using WireMock.Net.Tests.Serialization;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests
{
public partial class WireMockServerTests
{
[Fact]
public async Task WireMockServer_Should_reset_requestlogs()
{
// given
var server = WireMockServer.Start();
// when
await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false);
server.ResetLogEntries();
// then
Check.That(server.LogEntries).IsEmpty();
server.Stop();
}
[Fact]
public void WireMockServer_Should_reset_mappings()
{
// given
string path = $"/foo_{Guid.NewGuid()}";
var server = WireMockServer.Start();
server
.Given(Request.Create()
.WithPath(path)
.UsingGet())
.RespondWith(Response.Create()
.WithBody(@"{ msg: ""Hello world!""}"));
// when
server.ResetMappings();
// then
Check.That(server.Mappings).IsEmpty();
Check.ThatAsyncCode(() => new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path)).ThrowsAny();
server.Stop();
}
[Fact]
public async Task WireMockServer_Should_respond_a_redirect_without_body()
{
// Assign
string path = $"/foo_{Guid.NewGuid()}";
string pathToRedirect = $"/bar_{Guid.NewGuid()}";
var server = WireMockServer.Start();
server
.Given(Request.Create()
.WithPath(path)
.UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(307)
.WithHeader("Location", pathToRedirect));
server
.Given(Request.Create()
.WithPath(pathToRedirect)
.UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody("REDIRECT SUCCESSFUL"));
// Act
var response = await new HttpClient().GetStringAsync($"http://localhost:{server.Ports[0]}{path}").ConfigureAwait(false);
// Assert
Check.That(response).IsEqualTo("REDIRECT SUCCESSFUL");
server.Stop();
}
#if NETCOREAPP3_1_OR_GREATER
[Fact]
public async Task WireMockServer_WithCorsPolicyOptions_Should_Work_Correct()
{
// Arrange
var settings = new WireMockServerSettings
{
CorsPolicyOptions = CorsPolicyOptions.AllowAll
};
var server = WireMockServer.Start(settings);
server.Given(Request.Create().WithPath("/*")).RespondWith(Response.Create().WithBody("x"));
// Act
var response = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false);
// Asser.
response.Should().Be("x");
server.Stop();
}
#endif
[Fact]
public async Task WireMockServer_Should_delay_responses_for_a_given_route()
{
// Arrange
var server = WireMockServer.Start();
server
.Given(Request.Create()
.WithPath("/*"))
.RespondWith(Response.Create()
.WithBody(@"{ msg: ""Hello world!""}")
.WithDelay(TimeSpan.FromMilliseconds(200)));
// Act
var watch = new Stopwatch();
watch.Start();
await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false);
watch.Stop();
// Asser.
watch.ElapsedMilliseconds.Should().BeGreaterOrEqualTo(0);
server.Stop();
}
[Fact]
public async Task WireMockServer_Should_randomly_delay_responses_for_a_given_route()
{
// Arrange
var server = WireMockServer.Start();
server
.Given(Request.Create()
.WithPath("/*"))
.RespondWith(Response.Create()
.WithBody(@"{ msg: ""Hello world!""}")
.WithRandomDelay(10, 1000));
var watch = new Stopwatch();
watch.Start();
var httClient = new HttpClient();
async Task<long> ExecuteTimedRequestAsync()
{
watch.Reset();
await httClient.GetStringAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false);
return watch.ElapsedMilliseconds;
}
// Act
await ExecuteTimedRequestAsync().ConfigureAwait(false);
await ExecuteTimedRequestAsync().ConfigureAwait(false);
await ExecuteTimedRequestAsync().ConfigureAwait(false);
server.Stop();
}
[Fact]
public async Task WireMockServer_Should_delay_responses()
{
// Arrange
var server = WireMockServer.Start();
server.AddGlobalProcessingDelay(TimeSpan.FromMilliseconds(200));
server
.Given(Request.Create().WithPath("/*"))
.RespondWith(Response.Create().WithBody(@"{ msg: ""Hello world!""}"));
// Act
var watch = new Stopwatch();
watch.Start();
await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false);
watch.Stop();
// Assert
watch.ElapsedMilliseconds.Should().BeGreaterOrEqualTo(0);
server.Stop();
}
//Leaving commented as this requires an actual certificate with password, along with a service that expects a client certificate
//[Fact]
//public async Task Should_proxy_responses_with_client_certificate()
//{
// // given
// var _server = WireMockServer.Start();
// _server
// .Given(Request.Create().WithPath("/*"))
// .RespondWith(Response.Create().WithProxy("https://server-that-expects-a-client-certificate", @"\\yourclientcertificatecontainingprivatekey.pfx", "yourclientcertificatepassword"));
// // when
// var result = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/someurl?someQuery=someValue");
// // then
// Check.That(result).Contains("google");
//}
[Fact]
public async Task WireMockServer_Should_exclude_restrictedResponseHeader()
{
// Assign
string path = $"/foo_{Guid.NewGuid()}";
var server = WireMockServer.Start();
server
.Given(Request.Create().WithPath(path).UsingGet())
.RespondWith(Response.Create().WithHeader("Transfer-Encoding", "chunked").WithHeader("test", "t"));
// Act
var response = await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false);
// Assert
Check.That(response.Headers.Contains("test")).IsTrue();
Check.That(response.Headers.Contains("Transfer-Encoding")).IsFalse();
server.Stop();
}
#if !NET452 && !NET461
[Theory]
[InlineData("TRACE")]
[InlineData("GET")]
public async Task WireMockServer_Should_exclude_body_for_methods_where_body_is_definitely_disallowed(string method)
{
// Assign
string content = "hello";
var server = WireMockServer.Start();
server
.Given(Request.Create().WithBody((byte[] bodyBytes) => bodyBytes != null))
.AtPriority(0)
.RespondWith(Response.Create().WithStatusCode(400));
server
.Given(Request.Create())
.AtPriority(1)
.RespondWith(Response.Create().WithStatusCode(200));
// Act
var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost:" + server.Ports[0] + "/");
request.Content = new StringContent(content);
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
// Assert
Check.That(response.StatusCode).Equals(HttpStatusCode.OK);
server.Stop();
}
#endif
[Theory]
[InlineData("POST")]
[InlineData("PUT")]
[InlineData("OPTIONS")]
[InlineData("REPORT")]
[InlineData("DELETE")]
[InlineData("SOME-UNKNOWN-METHOD")] // default behavior for unknown methods is to allow a body (see BodyParser.ShouldParseBody)
public async Task WireMockServer_Should_not_exclude_body_for_supported_methods(string method)
{
// Assign
string content = "hello";
var server = WireMockServer.Start();
server
.Given(Request.Create().WithBody(content))
.AtPriority(0)
.RespondWith(Response.Create().WithStatusCode(200));
server
.Given(Request.Create())
.AtPriority(1)
.RespondWith(Response.Create().WithStatusCode(400));
// Act
var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost:" + server.Ports[0] + "/");
request.Content = new StringContent(content);
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
// Assert
Check.That(response.StatusCode).Equals(HttpStatusCode.OK);
server.Stop();
}
[Theory]
[InlineData("application/json")]
[InlineData("application/json; charset=ascii")]
[InlineData("application/json; charset=utf-8")]
[InlineData("application/json; charset=UTF-8")]
public async Task WireMockServer_Should_AcceptPostMappingsWithContentTypeJsonAndAnyCharset(string contentType)
{
// Arrange
string message = @"{
""request"": {
""method"": ""GET"",
""url"": ""/some/thing""
},
""response"": {
""status"": 200,
""body"": ""Hello world!"",
""headers"": {
""Content-Type"": ""text/plain""
}
}
}";
var stringContent = new StringContent(message);
stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
var server = WireMockServer.StartWithAdminInterface();
// Act
var response = await new HttpClient().PostAsync($"{server.Urls[0]}/__admin/mappings", stringContent).ConfigureAwait(false);
// Assert
Check.That(response.StatusCode).Equals(HttpStatusCode.Created);
Check.That(await response.Content.ReadAsStringAsync().ConfigureAwait(false)).Contains("Mapping added");
server.Stop();
}
[Theory]
[InlineData("gzip")]
[InlineData("deflate")]
public async Task WireMockServer_Should_SupportRequestGZipAndDeflate(string contentEncoding)
{
// Arrange
const string body = "hello wiremock";
byte[] compressed = CompressionUtils.Compress(contentEncoding, Encoding.UTF8.GetBytes(body));
var server = WireMockServer.Start();
server.Given(
Request.Create()
.WithPath("/foo")
.WithBody("hello wiremock")
)
.RespondWith(
Response.Create().WithBody("OK")
);
var content = new StreamContent(new MemoryStream(compressed));
content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
content.Headers.ContentEncoding.Add(contentEncoding);
// Act
var response = await new HttpClient().PostAsync($"{server.Urls[0]}/foo", content).ConfigureAwait(false);
// Assert
Check.That(await response.Content.ReadAsStringAsync().ConfigureAwait(false)).Contains("OK");
server.Stop();
}
#if !NET452
[Fact]
public async Task WireMockServer_Should_respond_to_ipv4_loopback()
{
// Assign
var server = WireMockServer.Start();
server
.Given(Request.Create()
.WithPath("/*"))
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody("from ipv4 loopback"));
// Act
var response = await new HttpClient().GetStringAsync($"http://127.0.0.1:{server.Ports[0]}/foo").ConfigureAwait(false);
// Assert
Check.That(response).IsEqualTo("from ipv4 loopback");
server.Stop();
}
[Fact]
public async Task WireMockServer_Should_respond_to_ipv6_loopback()
{
// Assign
var server = WireMockServer.Start();
server
.Given(Request.Create()
.WithPath("/*"))
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody("from ipv6 loopback"));
// Act
var response = await new HttpClient().GetStringAsync($"http://[::1]:{server.Ports[0]}/foo").ConfigureAwait(false);
// Assert
Check.That(response).IsEqualTo("from ipv6 loopback");
server.Stop();
}
[Fact]
public async Task WireMockServer_Using_JsonMapping_And_CustomMatcher_WithCorrectParams_ShouldMatch()
{
// Arrange
var settings = new WireMockServerSettings();
settings.WatchStaticMappings = true;
settings.WatchStaticMappingsInSubdirectories = true;
settings.CustomMatcherMappings = new Dictionary<string, Func<MatcherModel, IMatcher>>();
settings.CustomMatcherMappings[nameof(CustomPathParamMatcher)] = matcherModel =>
{
var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)matcherModel.Pattern);
return new CustomPathParamMatcher(
matcherModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch,
matcherParams.Path, matcherParams.PathParams,
settings.ThrowExceptionWhenMatcherFails == true
);
};
var server = WireMockServer.Start(settings);
server.WithMapping(@"{
""Request"": {
""Path"": {
""Matchers"": [
{
""Name"": ""CustomPathParamMatcher"",
""Pattern"": ""{\""path\"":\""/customer/{customerId}/document/{documentId}\"",\""pathParams\"":{\""customerId\"":\""^[0-9]+$\"",\""documentId\"":\""^[0-9a-zA-Z\\\\-_]+\\\\.[a-zA-Z]+$\""}}""
}
]
}
},
""Response"": {
""StatusCode"": 200,
""Headers"": {
""Content-Type"": ""application/json""
},
""Body"": ""OK""
}
}");
// Act
var response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/customer/132/document/pic.jpg", new StringContent("{ Hi = \"Hello World\" }")).ConfigureAwait(false);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
server.Stop();
}
[Fact]
public async Task WireMockServer_Using_JsonMapping_And_CustomMatcher_WithIncorrectParams_ShouldNotMatch()
{
// Arrange
var settings = new WireMockServerSettings();
settings.WatchStaticMappings = true;
settings.WatchStaticMappingsInSubdirectories = true;
settings.CustomMatcherMappings = new Dictionary<string, Func<MatcherModel, IMatcher>>();
settings.CustomMatcherMappings[nameof(CustomPathParamMatcher)] = matcherModel =>
{
var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)matcherModel.Pattern);
return new CustomPathParamMatcher(
matcherModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch,
matcherParams.Path, matcherParams.PathParams,
settings.ThrowExceptionWhenMatcherFails == true
);
};
var server = WireMockServer.Start(settings);
server.WithMapping(@"{
""Request"": {
""Path"": {
""Matchers"": [
{
""Name"": ""CustomPathParamMatcher"",
""Pattern"": ""{\""path\"":\""/customer/{customerId}/document/{documentId}\"",\""pathParams\"":{\""customerId\"":\""^[0-9]+$\"",\""documentId\"":\""^[0-9a-zA-Z\\\\-_]+\\\\.[a-zA-Z]+$\""}}""
}
]
}
},
""Response"": {
""StatusCode"": 200,
""Headers"": {
""Content-Type"": ""application/json""
},
""Body"": ""OK""
}
}");
// Act
var response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/customer/132/document/pic", new StringContent("{ Hi = \"Hello World\" }")).ConfigureAwait(false);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
server.Stop();
}
#endif
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.AzureStack.Management.Fabric.Admin
{
using Microsoft.AzureStack;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Fabric;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
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>
/// VolumesOperations operations.
/// </summary>
internal partial class VolumesOperations : IServiceOperations<FabricAdminClient>, IVolumesOperations
{
/// <summary>
/// Initializes a new instance of the VolumesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VolumesOperations(FabricAdminClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the FabricAdminClient
/// </summary>
public FabricAdminClient Client { get; private set; }
/// <summary>
/// Get a volume.
/// </summary>
/// <param name='location'>
/// Location of the resource.
/// </param>
/// <param name='storageSubSystem'>
/// Name of the storage system.
/// </param>
/// <param name='storagePool'>
/// Storage pool name.
/// </param>
/// <param name='volume'>
/// Name of the volume.
/// </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<Volume>> GetWithHttpMessagesAsync(string location, string storageSubSystem, string storagePool, string volume, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (storageSubSystem == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "storageSubSystem");
}
if (storagePool == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "storagePool");
}
if (volume == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "volume");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("location", location);
tracingParameters.Add("storageSubSystem", storageSubSystem);
tracingParameters.Add("storagePool", storagePool);
tracingParameters.Add("volume", volume);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/storageSubSystems/{storageSubSystem}/storagePools/{storagePool}/volumes/{volume}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{storageSubSystem}", System.Uri.EscapeDataString(storageSubSystem));
_url = _url.Replace("{storagePool}", System.Uri.EscapeDataString(storagePool));
_url = _url.Replace("{volume}", System.Uri.EscapeDataString(volume));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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<Volume>();
_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<Volume>(_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>
/// Get a list of all volumes at a location.
/// </summary>
/// <param name='location'>
/// Location of the resource.
/// </param>
/// <param name='storageSubSystem'>
/// Name of the storage system.
/// </param>
/// <param name='storagePool'>
/// Storage pool name.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the 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<Volume>>> ListWithHttpMessagesAsync(string location, string storageSubSystem, string storagePool, ODataQuery<Volume> odataQuery = default(ODataQuery<Volume>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (location == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "location");
}
if (storageSubSystem == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "storageSubSystem");
}
if (storagePool == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "storagePool");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("location", location);
tracingParameters.Add("storageSubSystem", storageSubSystem);
tracingParameters.Add("storagePool", storagePool);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/storageSubSystems/{storageSubSystem}/storagePools/{storagePool}/volumes").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{storageSubSystem}", System.Uri.EscapeDataString(storageSubSystem));
_url = _url.Replace("{storagePool}", System.Uri.EscapeDataString(storagePool));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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<Volume>>();
_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<Page<Volume>>(_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>
/// Get a list of all volumes at a location.
/// </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<Volume>>> ListNextWithHttpMessagesAsync(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, "ListNext", 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<Volume>>();
_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<Page<Volume>>(_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 2008-2009 Louis DeJardin - http://whereslou.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections;
using System.Globalization;
using System.Security.Permissions;
using System.Security.Principal;
using System.Web;
using System.Web.Caching;
using System.Web.Profile;
namespace Spark.Web.Mvc.Wrappers
{
[AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class HttpContextWrapper : HttpContextBase
{
// Fields
private readonly HttpContextBase _context;
private readonly ITextWriterContainer _textWriterContainer;
// Methods
public HttpContextWrapper(HttpContextBase httpContext, ITextWriterContainer textWriterContainer)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
if (textWriterContainer == null)
{
throw new ArgumentNullException("textWriterContainer");
}
_context = httpContext;
_textWriterContainer = textWriterContainer;
}
// Properties
public override Exception[] AllErrors
{
get { return _context.AllErrors; }
}
public override HttpApplicationStateBase Application
{
get { return _context.Application; }
}
public override HttpApplication ApplicationInstance
{
get { return _context.ApplicationInstance; }
set { _context.ApplicationInstance = value; }
}
public override Cache Cache
{
get { return _context.Cache; }
}
public override IHttpHandler CurrentHandler
{
get { return _context.CurrentHandler; }
}
public override RequestNotification CurrentNotification
{
get { return _context.CurrentNotification; }
}
public override Exception Error
{
get { return _context.Error; }
}
public override IHttpHandler Handler
{
get { return _context.Handler; }
set { _context.Handler = value; }
}
public override bool IsCustomErrorEnabled
{
get { return _context.IsCustomErrorEnabled; }
}
public override bool IsDebuggingEnabled
{
get { return _context.IsDebuggingEnabled; }
}
public override bool IsPostNotification
{
get { return _context.IsDebuggingEnabled; }
}
public override IDictionary Items
{
get { return _context.Items; }
}
public override IHttpHandler PreviousHandler
{
get { return _context.PreviousHandler; }
}
public override ProfileBase Profile
{
get { return _context.Profile; }
}
public override HttpRequestBase Request
{
get { return _context.Request; }
}
public override HttpResponseBase Response
{
get { return new HttpResponseWrapper(_context.Response, _textWriterContainer); }
}
public override HttpServerUtilityBase Server
{
get { return _context.Server; }
}
public override HttpSessionStateBase Session
{
get { return _context.Session; }
}
public override bool SkipAuthorization
{
get { return _context.SkipAuthorization; }
set { _context.SkipAuthorization = value; }
}
public override DateTime Timestamp
{
get { return _context.Timestamp; }
}
public override TraceContext Trace
{
get { return _context.Trace; }
}
public override IPrincipal User
{
get { return _context.User; }
set { _context.User = value; }
}
public override void AddError(Exception errorInfo)
{
_context.AddError(errorInfo);
}
public override void ClearError()
{
_context.ClearError();
}
public override object GetGlobalResourceObject(string classKey, string resourceKey)
{
return _context.GetGlobalResourceObject(classKey, resourceKey);
}
public override object GetGlobalResourceObject(string classKey, string resourceKey, CultureInfo culture)
{
return _context.GetGlobalResourceObject(classKey, resourceKey, culture);
}
public override object GetLocalResourceObject(string virtualPath, string resourceKey)
{
return _context.GetLocalResourceObject(virtualPath, resourceKey);
}
public override object GetLocalResourceObject(string virtualPath, string resourceKey, CultureInfo culture)
{
return _context.GetLocalResourceObject(virtualPath, resourceKey, culture);
}
public override object GetSection(string sectionName)
{
return _context.GetSection(sectionName);
}
public override object GetService(Type serviceType)
{
return ((IServiceProvider) _context).GetService(serviceType);
}
public override void RewritePath(string path)
{
_context.RewritePath(path);
}
public override void RewritePath(string path, bool rebaseClientPath)
{
_context.RewritePath(path, rebaseClientPath);
}
public override void RewritePath(string filePath, string pathInfo, string queryString)
{
_context.RewritePath(filePath, pathInfo, queryString);
}
public override void RewritePath(string filePath, string pathInfo, string queryString, bool setClientFilePath)
{
_context.RewritePath(filePath, pathInfo, queryString, setClientFilePath);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class ObjectCreationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public ObjectCreationExpressionSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new ObjectCreationExpressionSignatureHelpProvider();
}
#region "Regular tests"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParameters()
{
var markup = @"
class C
{
void foo()
{
var c = [|new C($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for C
/// </summary>
C() { }
void Foo()
{
C c = [|new C($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C()", "Summary for C", null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn1()
{
var markup = @"
class C
{
C(int a, int b) { }
void Foo()
{
C c = [|new C($$2, 3|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class C
{
/// <summary>
/// Summary for C
/// </summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
C(int a, int b) { }
void Foo()
{
C c = [|new C($$2, 3|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param a", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn2()
{
var markup = @"
class C
{
C(int a, int b) { }
void Foo()
{
C c = [|new C(2, $$3|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class C
{
/// <summary>
/// Summary for C
/// </summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
C(int a, int b) { }
void Foo()
{
C c = [|new C(2, $$3|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", "Summary for C", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParen()
{
var markup = @"
class C
{
void foo()
{
var c = [|new C($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParenWithParameters()
{
var markup = @"
class C
{
C(int a, int b) { }
void Foo()
{
C c = [|new C($$2, 3
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParenWithParametersOn2()
{
var markup = @"
class C
{
C(int a, int b) { }
void Foo()
{
C c = [|new C(2, $$3
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnLambda()
{
var markup = @"
using System;
class C
{
void foo()
{
var bar = [|new Action<int, int>($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("Action<int, int>(void (int, int) target)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
#endregion
#region "Current Parameter Name"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestCurrentParameterName()
{
var markup = @"
class C
{
C(int a, string b)
{
}
void foo()
{
var c = [|new C(b: string.Empty, $$a: 2|]);
}
}";
await VerifyCurrentParameterNameAsync(markup, "a");
}
#endregion
#region "Trigger tests"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerParens()
{
var markup = @"
class C
{
void foo()
{
var c = [|new C($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class C
{
C(int a, string b)
{
}
void foo()
{
var c = [|new C(2,$$string.Empty|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("C(int a, string b)", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnSpace()
{
var markup = @"
class C
{
C(int a, string b)
{
}
void foo()
{
var c = [|new C(2, $$string.Empty|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '(' };
char[] unexpectedCharacters = { ' ', '[', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Constructor_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new Foo($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public Foo(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Constructor_BrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Foo(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Constructor_BrowsableAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Foo($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Constructor_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new Foo($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public Foo(int x)
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Foo(long y)
{
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("Foo(long y)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class D
{
}
#endif
void foo()
{
var x = new D($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class D
{
}
#endif
#if BAR
void foo()
{
var x = new D($$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"D()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WorkItem(1067933)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// new foo($$";
await TestAsync(markup);
}
[WorkItem(1078993)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestSigHelpInIncorrectObjectCreationExpression()
{
var markup = @"
class C
{
void foo(C c)
{
foo([|new C{$$|]
}
}";
await TestAsync(markup);
}
}
}
| |
using System;
using System.Linq;
using NUnit.Framework;
using Newtonsoft.Json;
using SalesforceSharp.Security;
using SalesforceSharp.Serialization;
using TestSharp;
using SalesforceSharp.FunctionalTests.Stubs;
namespace SalesforceSharp.FunctionalTests
{
[TestFixture]
public class SalesforceClientTest
{
#region Authenticate
[Test]
public void Authenticate_InvalidUsername_AuthenticationFailure()
{
var target = new SalesforceClient();
ExceptionAssert.IsThrowing(new SalesforceException(SalesforceError.AuthenticationFailure, "authentication failure"), () =>
{
target.Authenticate(CreateAuthenticationFlow(TestConfig.ClientId, TestConfig.ClientSecret, "invalid user name", TestConfig.Password));
});
Assert.IsFalse(target.IsAuthenticated);
}
[Test]
public void Authenticate_InvalidPassword_InvalidPassword()
{
var target = new SalesforceClient();
ExceptionAssert.IsThrowing(new SalesforceException(SalesforceError.InvalidPassword, "authentication failure"), () =>
{
target.Authenticate(CreateAuthenticationFlow(TestConfig.ClientId, TestConfig.ClientSecret, TestConfig.Username, "invalid password"));
});
Assert.IsFalse(target.IsAuthenticated);
}
[Test]
public void Authenticate_InvalidClientId_InvalidClientId()
{
var target = new SalesforceClient();
ExceptionAssert.IsThrowing(new SalesforceException(SalesforceError.InvalidClient, "client identifier invalid"), () =>
{
target.Authenticate(CreateAuthenticationFlow("Invalid client id", TestConfig.ClientSecret, "invalid user name", TestConfig.Password));
});
Assert.IsFalse(target.IsAuthenticated);
}
[Test]
public void Authenticate_InvalidClientSecret_InvalidClientSecret()
{
var target = new SalesforceClient();
ExceptionAssert.IsThrowing(new SalesforceException(SalesforceError.InvalidClient, "invalid client credentials"), () =>
{
target.Authenticate(CreateAuthenticationFlow(TestConfig.ClientId, "invalid client secret", "invalid user name", TestConfig.Password));
});
Assert.IsFalse(target.IsAuthenticated);
}
[Test]
public void Authenticate_ValidCredentials_Authenticated()
{
var target = new SalesforceClient();
target.Authenticate(CreateAuthenticationFlow(TestConfig.ClientId, TestConfig.ClientSecret, TestConfig.Username, TestConfig.Password));
Assert.IsTrue(target.IsAuthenticated);
}
#endregion
#region Query
[Test]
public void Query_InvalidQuery_Exception()
{
var target = CreateClientAndAuth();
ExceptionAssert.IsThrowing(typeof(SalesforceException), () =>
{
target.Query<RecordStub>("SELECT id, name, FROM " + TestConfig.ObjectName);
});
}
[Test]
public void Query_ValidQueryWithObject_Result()
{
var target = CreateClientAndAuth();
var actual = target.Query<RecordStub>("SELECT id, name FROM Account");
Assert.IsNotNull(actual);
if (actual.Count > 0)
{
Assert.IsNotNull(actual[0].Id);
Assert.IsNotNull(actual[0].Name);
}
actual = target.Query<RecordStub>("SELECT id, name FROM Account WHERE LastModifiedDate = 2013-12-01T12:00:00+00:00");
Assert.IsNotNull(actual);
}
[Test]
public void Query_ValidQueryWithJsonAttributeObject_Result()
{
var target = CreateClientAndAuth();
var actual = target.QueryActionBatch<RecordStub>("SELECT id, name, Phone from Account where Phone != '' LIMIT 3 ",
(a) => { });
Assert.IsNotNull(actual);
if (actual.Count > 0)
{
Assert.IsNotNull (actual[0].Id);
Assert.IsNotNull (actual[0].Name);
Assert.IsNotNull (actual[0].PhoneCustom);
}
}
/// <summary>
/// To validate this issue: https://github.com/giacomelli/SalesforceSharp/issues/4.
/// </summary>
[Test]
public void Query_ValidQueryWithSpecialChars_Result()
{
var target = CreateClientAndAuth();
var actual = target.Query<RecordStub>("SELECT id, name, description FROM Account WHERE LastModifiedDate >= 2013-12-01T12:00:00+00:00");
Assert.IsNotNull(actual);
}
/// <summary>
/// To validate this issue: https://github.com/giacomelli/SalesforceSharp/issues/6.
/// </summary>
[Test]
public void Query_ValidQueryClassWithFields_ResultNoFieldsBind()
{
var target = CreateClientAndAuth();
// Public FIELDS are supported.
var actual1 = target.Query<ContactStubWithFields>("SELECT Id, Name, Email FROM Contact LIMIT 1 OFFSET 0");
Assert.AreEqual(1, actual1.Count);
var first1 = actual1 [0];
TextAssert.IsNotNullOrEmpty (first1.Id);
TextAssert.IsNotNullOrEmpty (first1.Name);
// Public PROPERTIES are supported.
var actual2 = target.Query<ContactStub>("SELECT Id, Name, Email FROM Contact LIMIT 1 OFFSET 0");
Assert.AreEqual(1, actual2.Count);
var first2 = actual2 [0];
TextAssert.IsNotNullOrEmpty (first2.Id);
TextAssert.IsNotNullOrEmpty (first2.Name);
}
[Test]
public void Query_ValidQueryWithObjectWrongPropertyTypes_Exception()
{
var target = CreateClientAndAuth();
ExceptionAssert.IsThrowing(typeof(JsonReaderException), () =>
{
target.Query<WrongRecordStub>("SELECT IsDeleted FROM Account");
});
}
#endregion
#region
[Test]
public void QueryActionBatch_ValidQuery_AllRecords()
{
var target = CreateClientAndAuth();
var queryString = "SELECT id, name, description ";
queryString += " FROM Account";
var totalRecords = 0;
var actual = target.QueryActionBatch<RecordStub>(queryString, s =>
{
totalRecords += s.Count;
});
Assert.IsNotNull(totalRecords);
Assert.AreNotEqual(0, totalRecords);
Assert.AreEqual (totalRecords, actual.Count);
}
#endregion
#region GetSOjbect
[Test]
public void Get_SOjbectDetail_work()
{
var target = CreateClientAndAuth();
var accObject = target.GetSObjectDetail("account");
Assert.IsNotNull(accObject);
Assert.AreEqual(accObject.Name, "Account");
Assert.IsNotNull(accObject.Fields);
Assert.IsNotEmpty(accObject.Fields);
Assert.IsNotNull(accObject.Fields.FirstOrDefault(x=> x.Name =="Id"));
var industryField = accObject.Fields.FirstOrDefault(x => x.Name == "Industry");
Assert.IsNotNull(industryField);
Assert.IsNotNull(industryField.PicklistValues);
Assert.IsNotEmpty(industryField.PicklistValues);
Assert.IsNotNull(industryField.PicklistValues.FirstOrDefault(y => y.Value == "Engineering"));
}
#endregion
#region GetRaw
[Test]
public void GetRawContent_ValidRecord()
{
var target = CreateClientAndAuth();
var record = new
{
FirstName = "Name " + DateTime.Now.Ticks,
LastName = "Last name"
};
var id = target.Create("Contact", record);
var actual = target.GetRawContent("Contact", id);
Assert.IsNotNull(actual);
Assert.That(actual.Contains(string.Format("\"FirstName\":\"{0}\"", record.FirstName)));
Assert.That(actual.Contains(string.Format("\"LastName\":\"{0}\"", record.LastName)));
}
[Test]
public void GetRawBytes_ValidRecord()
{
var target = CreateClientAndAuth();
var record = new
{
FirstName = "Name " + DateTime.Now.Ticks,
LastName = "Last name"
};
var id = target.Create("Contact", record);
var bytes = target.GetRawBytes("Contact", id);
string actual = System.Text.Encoding.UTF8.GetString(bytes);
Assert.IsNotNull(actual);
Assert.That(actual.Contains(string.Format("\"FirstName\":\"{0}\"", record.FirstName)));
Assert.That(actual.Contains(string.Format("\"LastName\":\"{0}\"", record.LastName)));
Assert.AreNotEqual(target.ApiCallsUsed, 0);
Assert.AreEqual(target.ApiCallsLimit, 15000);
}
#endregion
#region FindById
[Test]
public void FindById_NotExistingID_Null()
{
var target = CreateClientAndAuth();
Assert.IsNull(target.FindById<RecordStub>("Contact", "003i000000K2BP0AAM"));
}
[Test]
public void FindById_ValidId_Record()
{
var target = CreateClientAndAuth();
var record = new
{
FirstName = "Name " + DateTime.Now.Ticks,
LastName = "Last name"
};
var id = target.Create("Contact", record);
var actual = target.FindById<ContactStub>("Contact", id);
Assert.IsNotNull(actual);
Assert.AreEqual(record.FirstName, actual.FirstName);
Assert.AreEqual(record.LastName, actual.LastName);
}
#endregion
#region ReadMetaData
[Test]
public void ReadMetaData_ValidObjectName_Metadata()
{
var target = CreateClientAndAuth();
string result = target.ReadMetaData("Account");
Assert.IsNotEmpty(result);
}
#endregion
#region Create
[Test]
public void Create_ValidRecordWithAnonymous_Created()
{
var target = CreateClientAndAuth();
var record = new
{
FirstName = "Name " + DateTime.Now.Ticks,
LastName = "Last name"
};
var id = target.Create("Contact", record);
Assert.IsFalse(String.IsNullOrWhiteSpace(id));
}
[Test]
public void Create_ValidRecordWithClassWithWrongProperties_Exception()
{
var target = CreateClientAndAuth();
var record = new
{
FirstName1 = "Name " + DateTime.Now.Ticks,
LastName = "Last name"
};
ExceptionAssert.IsThrowing(new SalesforceException(SalesforceError.InvalidField, "No such column 'FirstName1' on sobject of type Contact"), () =>
{
target.Create("Contact", record);
});
}
#endregion
#region Update
[Test]
public void Update_InvalidId_Exception()
{
var target = CreateClientAndAuth();
ExceptionAssert.IsThrowing(new SalesforceException(SalesforceError.NotFound, "Provided external ID field does not exist or is not accessible: INVALID ID"), () =>
{
target.Update(TestConfig.ObjectName, "INVALID ID", new { Name = "TEST" });
});
}
[Test]
public void Update_ValidRecordWithAnonymous_Updated()
{
var target = CreateClientAndAuth();
var actual = target.Query<RecordStub>("SELECT id, name, description FROM Account");
Assert.IsNotNull(actual);
if (actual.Count > 0)
{
Assert.IsTrue(target.Update("Account", actual[0].Id, new { Description = DateTime.Now + " UPDATED" }));
}
}
[Test]
public void Update_ValidRecordWithClass_Updated()
{
var target = CreateClientAndAuth();
var actual = target.Query<RecordStub>("SELECT id, name, Phone, FirstName, LastName, description FROM Contact LIMIT 10");
Assert.IsNotNull(actual);
if (actual.Count > 0)
{
Assert.IsTrue(target.Update("Contact", actual[0].Id, new RecordStub { FirstName = actual[0].FirstName, LastName = actual[0].LastName, PhoneCustom = actual[0].PhoneCustom, Description = DateTime.Now + " UPDATED" }));
}
}
[Test]
public void Update_ValidRecordWithClassWithWrongProperties_Exception()
{
var target = CreateClientAndAuth();
var actual = target.Query<RecordStub>("SELECT id, name, description FROM Account");
Assert.IsNotNull(actual);
if (actual.Count > 0)
{
ExceptionAssert.IsThrowing(new SalesforceException(SalesforceError.InvalidFieldForInsertUpdate, "Unable to create/update fields: IsDeleted. Please check the security settings of this field and verify that it is read/write for your profile or permission set."), () =>
{
target.Update("Account", actual[0].Id, new WrongRecordStub { Name = actual[0].Name, Description = DateTime.Now + " UPDATED" });
});
}
}
#endregion
#region Delete
[Test]
public void Delete_MalFormedId_Exception()
{
var target = CreateClientAndAuth();
ExceptionAssert.IsThrowing(new SalesforceException(SalesforceError.EntityIsDeleted, "malformed id 003i000000K27rxAAC"), () =>
{
target.Delete("Contact", "003i000000K27rxAAC");
});
}
[Test]
public void Delete_AlreadyDeleted_Exception()
{
var target = CreateClientAndAuth();
var record = new
{
FirstName = "Name " + DateTime.Now.Ticks,
LastName = "Last name"
};
var id = target.Create("Contact", record);
Assert.IsTrue(target.Delete("Contact", id));
ExceptionAssert.IsThrowing(new SalesforceException(SalesforceError.EntityIsDeleted, "Entity is deleted"), () =>
{
target.Delete("Contact", id);
});
}
[Test]
public void Delete_ExistingId_Deleted()
{
var target = CreateClientAndAuth();
var record = new
{
FirstName = "Name " + DateTime.Now.Ticks,
LastName = "Last name"
};
var id = target.Create("Contact", record);
Assert.IsTrue(target.Delete("Contact", id));
}
#endregion
#region ClassHelper
[Test]
public void GetRecordProjection_Result()
{
var jSonPropertyString = SalesforceClient.GetRecordProjection(typeof(TestJson));
Assert.IsTrue(jSonPropertyString.Contains("Id"));
Assert.IsTrue(jSonPropertyString.Contains("JsonName"));
Assert.IsFalse(jSonPropertyString.Contains("JsonIgnoreMe"));
}
#endregion
#region Helpers
private SalesforceClient CreateClientAndAuth()
{
return CreateClientAndAuth(TestConfig.ClientId, TestConfig.ClientSecret, TestConfig.Username, TestConfig.Password);
}
private UsernamePasswordAuthenticationFlow CreateAuthenticationFlow(string clientId, string clientSecret, string username, string password)
{
var flow = new UsernamePasswordAuthenticationFlow(clientId, clientSecret, username, password);
flow.TokenRequestEndpointUrl = TestConfig.TokenRequestEndpointUrl;
return flow;
}
private SalesforceClient CreateClientAndAuth(
string clientId,
string clientSecret,
string username,
string password)
{
var client = new SalesforceClient();
var authenticationFlow = CreateAuthenticationFlow(clientId, clientSecret, username, password);
client.Authenticate(authenticationFlow);
return client;
}
public class TestJson
{
public int Id { get; set; }
[Salesforce(Ignore = true)]
public string JsonIgnoreMe { get; set; }
[Salesforce(FieldName = "JsonName")]
public string JsonRenameMe { get; set; }
}
#endregion
}
}
| |
/*
* Copyright 2005 OpenXRI Foundation
* Subsequently ported and altered by Andrew Arnott
*
* 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 DotNetXri.Loggers;
using DotNetXri.Client.Util;
using DotNetXri.Client.Xml;
using System.Xml;
using System;
namespace DotNetXri.Client.Saml {
//using org.apache.xerces.dom.XmlDocument;
//using org.apache.xml.security.signature.XMLSignature;
//using org.openxri.util.DOMUtils;
//using org.openxri.xml.Tags;
//using org.w3c.dom.XmlDocument;
//using org.w3c.dom.XmlElement;
//using org.w3c.dom.XmlNode;
/*
********************************************************************************
* Class: Assertion
********************************************************************************
*/ /**
* This class provides encapsulation of a SAML 2.0 Assertion
* @author =chetan
*/
public class Assertion
{
private static ILog soLog = Logger.Create(typeof(Assertion));
private string msXmlID = "";
private string msIssueInstant = "";
private XmlElement moElem;
private NameID moIssuer;
private XMLSignature moSignature;
private Subject moSubject;
private Conditions moConditions;
private AttributeStatement moAttrStatement;
/*
****************************************************************************
* Constructor()
****************************************************************************
*/ /**
* Contructs a SAML 2.0 assertion and generates an id for it
*/
public Assertion()
{
genXmlID();
} // Constructor()
/*
****************************************************************************
* Constructor()
****************************************************************************
*/ /**
* Contructs a SAML 2.0 assertion from the specified DOM
*/
public Assertion(XmlElement oElem)
{
fromDOM(oElem);
} // Constructor()
/*
****************************************************************************
* getIssueInstant()
****************************************************************************
*/ /**
* Returns the issueInstant attribute
*/
public string getIssueInstant()
{
return msIssueInstant;
} // getIssueInstant()
/*
****************************************************************************
* setIssueInstant()
****************************************************************************
*/ /**
* Sets the issueInstant attribute
*/
public void setIssueInstant(string sVal)
{
msIssueInstant = sVal;
} // setIssueInstant()
/*
****************************************************************************
* getXmlID()
****************************************************************************
*/ /**
* Returns the id attribute
*/
public string getXmlID()
{
return msXmlID;
} // getXmlID()
/*
****************************************************************************
* setXmlID()
****************************************************************************
*/ /**
* Sets the id attribute
*/
public void setXmlID(string sVal)
{
msXmlID = sVal;
} // setXmlID()
/*
****************************************************************************
* genXmlID()
****************************************************************************
*/ /**
* Sets the id attribute with a newly generated id
*/
public void genXmlID()
{
msXmlID = "_" + XMLUtils.genXmlID();
} // genXmlID()
/*
****************************************************************************
* setDOM()
****************************************************************************
*/ /**
* This method will import from DOM, and hold on to it, as
* retrievable by getDOM. The fromDOM method, on the otherhand, will not keep
* a copy of the DOM.
*/
public void setDOM(XmlElement oElem)
{
fromDOM(oElem);
moElem = oElem;
} // setDOM()
/*
****************************************************************************
* reset()
****************************************************************************
*/ /**
* Resets the internal state of this obj
*/
public void reset()
{
msXmlID = "";
msIssueInstant = "";
moElem = null;
moIssuer = null;
moSignature = null;
moSubject = null;
moConditions = null;
moAttrStatement = null;
} // reset()
/*
****************************************************************************
* fromDOM()
****************************************************************************
*/ /**
* This method populates the obj from DOM. It does not keep a
* copy of the DOM around. Whitespace information is lost in this process.
*/
public void fromDOM(XmlElement oElem)
{
reset();
// get the id attribute
if (oElem.hasAttributeNS(null, Tags.ATTR_ID_CAP))
{
msXmlID = oElem.getAttributeNS(null, Tags.ATTR_ID_CAP);
}
if (oElem.hasAttributeNS(null, Tags.ATTR_ISSUEINSTANT))
{
msIssueInstant = oElem.getAttributeNS(null, Tags.ATTR_ISSUEINSTANT);
}
for (
XmlNode oChild = oElem.FirstChild; oChild != null;
oChild = oChild.NextSibling)
{
if (oChild.LocalName.Equals(Tags.TAG_ISSUER))
{
// only accept the first XRIAuthority
if (moIssuer == null)
{
moIssuer = new NameID((XmlElement) oChild);
}
}
else if (oChild.LocalName.Equals(Tags.TAG_SIGNATURE))
{
// only accept the first XRIAuthority
if (moSignature == null)
{
try
{
XmlDocument oDoc = new XmlDocument();
XmlElement oChildCopy =
(XmlElement) oDoc.ImportNode(oChild, true);
moSignature = new XMLSignature(oChildCopy, null);
}
catch (Exception oEx)
{
soLog.Warn(
"Caught exception while parsing Signature", oEx);
}
}
}
else if (oChild.LocalName.Equals(Tags.TAG_SUBJECT))
{
// only accept the first XRIAuthority
if (moSubject == null)
{
moSubject = new Subject((XmlElement) oChild);
}
}
else if (oChild.LocalName.Equals(Tags.TAG_CONDITIONS))
{
// only accept the first XRIAuthority
if (moConditions == null)
{
moConditions = new Conditions((XmlElement) oChild);
}
}
else if (oChild.LocalName.Equals(Tags.TAG_ATTRIBUTESTATEMENT))
{
// only accept the first XRIAuthority
if (moAttrStatement == null)
{
moAttrStatement = new AttributeStatement((XmlElement) oChild);
}
}
}
} // fromDOM()
/*
****************************************************************************
* getDOM()
****************************************************************************
*/ /**
* This method returns DOM stored with this obj. It may be cached and
* there is no guarantee as to which document it was created from
*/
public XmlElement getDOM()
{
if (moElem == null)
{
moElem = toDOM(new XmlDocument());
moElem.getOwnerDocument().AppendChild(moElem);
}
return moElem;
} // getDOM()
/*
****************************************************************************
* isValid()
****************************************************************************
*/ /**
* Returns true of the assertion is valid. Checks validity period in
* conditions and required fields and attributes
*/
public bool isValid()
{
if (
(msIssueInstant.Equals("")) || (msXmlID.Equals("")) ||
(moIssuer == null))
{
return false;
}
if ((moConditions != null) && (!moConditions.isValid()))
{
return false;
}
return true;
} // isValid()
/*
****************************************************************************
* getAttributeStatement()
****************************************************************************
*/ /**
* Returns the first attribute statement in the assertion
*/
public AttributeStatement getAttributeStatement()
{
return moAttrStatement;
} // getAttributeStatement()
/*
****************************************************************************
* toDOM()
****************************************************************************
*/ /**
* This method will make DOM using the specified document. If any DOM state
* has been stored with the obj, it will not be used in this method.
* This method generates a reference-free copy of new DOM.
* @param oDoc - The document to use for generating DOM
*/
public XmlElement toDOM(XmlDocument oDoc)
{
// for this particular toDOM implementation, oDoc must not be null
if (oDoc == null)
{
return null;
}
XmlElement oElem = oDoc.createElementNS(Tags.NS_SAML, Tags.TAG_ASSERTION);
oElem.setAttributeNS(Tags.NS_XMLNS, "xmlns", Tags.NS_SAML);
oElem.setAttributeNS(Tags.NS_XMLNS, "xmlns:saml", Tags.NS_SAML);
oElem.setPrefix("saml");
oElem.setAttributeNS(null, Tags.ATTR_VERSION, "2.0");
oElem.setAttributeNS(null, Tags.ATTR_ID_CAP, msXmlID);
oElem.setAttributeNS(null, Tags.ATTR_ISSUEINSTANT, msIssueInstant);
if (moIssuer != null)
{
XmlElement oChildElem = (XmlElement) moIssuer.toDOM(oDoc);
oElem.AppendChild(oChildElem);
}
if (moSignature != null)
{
XmlElement oChildElem = moSignature.getElement();
// import the node, we want a copy
oChildElem = (XmlElement) oDoc.importNode(oChildElem, true);
oElem.AppendChild(oChildElem);
}
if (moSubject != null)
{
XmlElement oChildElem = (XmlElement) moSubject.toDOM(oDoc);
oElem.AppendChild(oChildElem);
}
if (moConditions != null)
{
XmlElement oChildElem = (XmlElement) moConditions.toDOM(oDoc);
oElem.AppendChild(oChildElem);
}
if (moAttrStatement != null)
{
XmlElement oChildElem = (XmlElement) moAttrStatement.toDOM(oDoc);
oElem.AppendChild(oChildElem);
}
return oElem;
} // toDOM()
/*
****************************************************************************
* getSubject()
****************************************************************************
*/ /**
* Returns the subject of this assertion
*/
public Subject getSubject()
{
return moSubject;
} // getSubject()
/*
****************************************************************************
* ToString()
****************************************************************************
*/ /**
* Returns formatted obj. Do not use if signature needs to be preserved.
*/
public override string ToString()
{
return dump();
} // ToString()
/*
****************************************************************************
* dump()
****************************************************************************
*/ /**
* Returns obj as a formatted XML string.
* @param sTab - The characters to prepend before each new line
*/
public string dump()
{
XmlDocument doc = new XmlDocument();
XmlElement elm = this.toDOM(doc);
doc.AppendChild(elm);
return DOMUtils.ToString(doc);
} // dump()
/*
****************************************************************************
* getIssuer()
****************************************************************************
*/ /**
*Returns the issuer element of the assertion
*/
public NameID getIssuer()
{
return moIssuer;
} // getIssuer()
/*
****************************************************************************
* setIssuer()
****************************************************************************
*/ /**
* Sets the issuer element of the assertion
*/
public void setIssuer(NameID oIssuer)
{
moIssuer = oIssuer;
} // setIssuer()
/*
****************************************************************************
* getConditions()
****************************************************************************
*/ /**
* Returns the conditions element of the assertion
*/
public Conditions getConditions()
{
return moConditions;
} // getConditions()
/*
****************************************************************************
* setConditions()
****************************************************************************
*/ /**
* Sets the conditions element of the assertion
*/
public void setConditions(Conditions oVal)
{
moConditions = oVal;
} // setConditions()
/*
****************************************************************************
* setAttrStatement()
****************************************************************************
*/ /**
* Sets the attribute statement element of the assertion. Only one
* attribute statement is supported per assertion.
*/
public void setAttrStatement(AttributeStatement oVal)
{
moAttrStatement = oVal;
} // setAttrStatement()
/*
****************************************************************************
* setSubject()
****************************************************************************
*/ /**
* Sets the subject element of the assertion
*/
public void setSubject(Subject oVal)
{
moSubject = oVal;
} // setSubject()
} // Class: Assertion
}
| |
//-----------------------------------------------------------------------
// <copyright file="TangoDynamicMesh.cs" company="Google">
//
// Copyright 2016 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.
//
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Tango;
using UnityEngine;
using UnityEngine.Rendering;
/// <summary>
/// Updates a mesh dynamically based on the ITango3DReconstruction callbacks.
///
/// The "mesh" that is updated by TangoDynamicMesh is actually a collection of children split along grid boundaries.
/// If you want these children to draw or participate in physics, attach a MeshRenderer or MeshCollider to this object.
/// Any generated children will get copies of the MeshRenderer or MeshCollider or both.
/// </summary>
public class TangoDynamicMesh : MonoBehaviour, ITango3DReconstruction
{
/// <summary>
/// If set, debugging info is displayed.
/// </summary>
public bool m_enableDebugUI = true;
/// <summary>
/// How much the dynamic mesh should grow its internal arrays.
/// </summary>
private const float GROWTH_FACTOR = 1.5f;
/// <summary>
/// Maximum amount of time to spend each frame extracting meshes.
/// </summary>
private const int TIME_BUDGET_MS = 10;
/// <summary>
/// The initial amount of vertices for a single dynamic mesh.
/// </summary>
private const int INITIAL_VERTEX_COUNT = 100;
/// <summary>
/// The initial amount of indexes for a single dynamic mesh.
/// </summary>
private const int INITIAL_INDEX_COUNT = 99;
/// <summary>
/// How much the texture coordinates change relative to the actual distance.
/// </summary>
private const float UV_PER_METERS = 10;
/// <summary>
/// The TangoApplication for the scene.
/// </summary>
private TangoApplication m_tangoApplication;
/// <summary>
/// The mesh renderer on this object. This mesh renderer will get used on all the DynamicMesh objects created.
/// </summary>
private MeshRenderer m_meshRenderer;
/// <summary>
/// The mesh collider on this object. This mesh collider will get used on all the DynamicMesh objects created.
/// </summary>
private MeshCollider m_meshCollider;
/// <summary>
/// Hash table to quickly get access to a dynamic mesh based on its position.
/// </summary>
private Dictionary<Tango3DReconstruction.GridIndex, TangoSingleDynamicMesh> m_meshes;
/// <summary>
/// List of grid indexes that need to get extracted.
/// </summary>
private List<Tango3DReconstruction.GridIndex> m_gridIndexToUpdate;
/// <summary>
/// Debug info: Total number of vertices in the dynamic mesh.
/// </summary>
private int m_debugTotalVertices;
/// <summary>
/// Debug info: Total number of triangle indexes in the dynamic mesh.
/// </summary>
private int m_debugTotalTriangles;
/// <summary>
/// Debug info: Amount of time spent most recently updating the meshes.
/// </summary>
private float m_debugRemeshingTime;
/// <summary>
/// Debug info: Amount of meshes updated most recently.
/// </summary>
private int m_debugRemeshingCount;
/// <summary>
/// Unity Awake callback.
/// </summary>
public void Awake()
{
m_tangoApplication = GameObject.FindObjectOfType<TangoApplication>();
if (m_tangoApplication != null)
{
m_tangoApplication.Register(this);
}
m_meshes = new Dictionary<Tango3DReconstruction.GridIndex, TangoSingleDynamicMesh>(100);
m_gridIndexToUpdate = new List<Tango3DReconstruction.GridIndex>(100);
// Cache the renderer and collider on this object.
m_meshRenderer = GetComponent<MeshRenderer>();
if (m_meshRenderer != null)
{
m_meshRenderer.enabled = false;
}
m_meshCollider = GetComponent<MeshCollider>();
if (m_meshCollider != null)
{
m_meshCollider.enabled = false;
}
}
/// <summary>
/// Unity Update callback.
/// </summary>
public void Update()
{
List<Tango3DReconstruction.GridIndex> needsResize = new List<Tango3DReconstruction.GridIndex>();
int it;
int startTimeMS = (int)(Time.realtimeSinceStartup * 1000);
for (it = 0; it < m_gridIndexToUpdate.Count; ++it)
{
Tango3DReconstruction.GridIndex gridIndex = m_gridIndexToUpdate[it];
if ((Time.realtimeSinceStartup * 1000) - startTimeMS > TIME_BUDGET_MS)
{
Debug.Log(string.Format(
"TangoDynamicMesh.Update() ran over budget with {0}/{1} grid indexes processed.",
it, m_gridIndexToUpdate.Count));
break;
}
TangoSingleDynamicMesh dynamicMesh;
if (!m_meshes.TryGetValue(gridIndex, out dynamicMesh))
{
// build a dynamic mesh as a child of this game object.
GameObject newObj = new GameObject();
newObj.transform.parent = transform;
newObj.name = string.Format("{0},{1},{2}", gridIndex.x, gridIndex.y, gridIndex.z);
dynamicMesh = newObj.AddComponent<TangoSingleDynamicMesh>();
dynamicMesh.m_vertices = new Vector3[INITIAL_VERTEX_COUNT];
if (m_tangoApplication.m_3drGenerateTexCoord)
{
dynamicMesh.m_uv = new Vector2[INITIAL_VERTEX_COUNT];
}
if (m_tangoApplication.m_3drGenerateColor)
{
dynamicMesh.m_colors = new Color32[INITIAL_VERTEX_COUNT];
}
dynamicMesh.m_triangles = new int[INITIAL_INDEX_COUNT];
// Update debug info too.
m_debugTotalVertices = dynamicMesh.m_vertices.Length;
m_debugTotalTriangles = dynamicMesh.m_triangles.Length;
// Add the other necessary objects
MeshFilter meshFilter = newObj.AddComponent<MeshFilter>();
dynamicMesh.m_mesh = meshFilter.mesh;
if (m_meshRenderer != null)
{
MeshRenderer meshRenderer = newObj.AddComponent<MeshRenderer>();
#if UNITY_5
meshRenderer.shadowCastingMode = m_meshRenderer.shadowCastingMode;
meshRenderer.receiveShadows = m_meshRenderer.receiveShadows;
meshRenderer.sharedMaterials = m_meshRenderer.sharedMaterials;
meshRenderer.useLightProbes = m_meshRenderer.useLightProbes;
meshRenderer.reflectionProbeUsage = m_meshRenderer.reflectionProbeUsage;
meshRenderer.probeAnchor = m_meshRenderer.probeAnchor;
#elif UNITY_4_6
meshRenderer.castShadows = m_meshRenderer.castShadows;
meshRenderer.receiveShadows = m_meshRenderer.receiveShadows;
meshRenderer.sharedMaterials = m_meshRenderer.sharedMaterials;
meshRenderer.useLightProbes = m_meshRenderer.useLightProbes;
meshRenderer.lightProbeAnchor = m_meshRenderer.lightProbeAnchor;
#endif
}
if (m_meshCollider != null)
{
MeshCollider meshCollider = newObj.AddComponent<MeshCollider>();
meshCollider.convex = m_meshCollider.convex;
meshCollider.isTrigger = m_meshCollider.isTrigger;
meshCollider.sharedMaterial = m_meshCollider.sharedMaterial;
meshCollider.sharedMesh = dynamicMesh.m_mesh;
dynamicMesh.m_meshCollider = meshCollider;
}
m_meshes.Add(gridIndex, dynamicMesh);
}
// Last frame the mesh needed more space. Give it more room now.
if (dynamicMesh.m_needsToGrow)
{
int newVertexSize = (int)(dynamicMesh.m_vertices.Length * GROWTH_FACTOR);
int newTriangleSize = (int)(dynamicMesh.m_triangles.Length * GROWTH_FACTOR);
newTriangleSize -= newTriangleSize % 3;
// Remove the old size, add the new size.
m_debugTotalVertices += newVertexSize - dynamicMesh.m_vertices.Length;
m_debugTotalTriangles += newTriangleSize - dynamicMesh.m_triangles.Length;
dynamicMesh.m_vertices = new Vector3[newVertexSize];
if (m_tangoApplication.m_3drGenerateTexCoord)
{
dynamicMesh.m_uv = new Vector2[newVertexSize];
}
if (m_tangoApplication.m_3drGenerateColor)
{
dynamicMesh.m_colors = new Color32[newVertexSize];
}
dynamicMesh.m_triangles = new int[newTriangleSize];
dynamicMesh.m_needsToGrow = false;
}
int numVertices;
int numTriangles;
Tango3DReconstruction.Status status = m_tangoApplication.Tango3DRExtractMeshSegment(
gridIndex, dynamicMesh.m_vertices, null, dynamicMesh.m_colors, dynamicMesh.m_triangles,
out numVertices, out numTriangles);
if (status != Tango3DReconstruction.Status.INSUFFICIENT_SPACE
&& status != Tango3DReconstruction.Status.SUCCESS)
{
Debug.Log("Tango3DR extraction failed, status code = " + status + Environment.StackTrace);
continue;
}
else if (status == Tango3DReconstruction.Status.INSUFFICIENT_SPACE)
{
// We already spent the time extracting this mesh, let's not spend any more time this frame
// to extract the mesh.
Debug.Log(string.Format(
"TangoDynamicMesh.Update() extraction ran out of space with room for {0} vertexes, {1} indexes.",
dynamicMesh.m_vertices.Length, dynamicMesh.m_triangles.Length));
dynamicMesh.m_needsToGrow = true;
needsResize.Add(gridIndex);
}
// Make any leftover triangles degenerate.
for (int triangleIt = numTriangles * 3; triangleIt < dynamicMesh.m_triangles.Length; ++triangleIt)
{
dynamicMesh.m_triangles[triangleIt] = 0;
}
if (dynamicMesh.m_uv != null)
{
// Add texture coordinates.
for (int vertexIt = 0; vertexIt < numVertices; ++vertexIt)
{
Vector3 vertex = dynamicMesh.m_vertices[vertexIt];
dynamicMesh.m_uv[vertexIt].x = vertex.x * UV_PER_METERS;
dynamicMesh.m_uv[vertexIt].y = (vertex.z + vertex.y) * UV_PER_METERS;
}
}
dynamicMesh.m_mesh.Clear();
dynamicMesh.m_mesh.vertices = dynamicMesh.m_vertices;
dynamicMesh.m_mesh.uv = dynamicMesh.m_uv;
dynamicMesh.m_mesh.colors32 = dynamicMesh.m_colors;
dynamicMesh.m_mesh.triangles = dynamicMesh.m_triangles;
if (m_tangoApplication.m_3drGenerateNormal)
{
dynamicMesh.m_mesh.RecalculateNormals();
}
if (dynamicMesh.m_meshCollider != null)
{
// Force the mesh collider to update too.
dynamicMesh.m_meshCollider.sharedMesh = null;
dynamicMesh.m_meshCollider.sharedMesh = dynamicMesh.m_mesh;
}
}
m_debugRemeshingTime = Time.realtimeSinceStartup - (startTimeMS * 0.001f);
m_debugRemeshingCount = it;
// Any leftover grid indices also need to get processed next frame.
while (it < m_gridIndexToUpdate.Count)
{
needsResize.Add(m_gridIndexToUpdate[it]);
++it;
}
m_gridIndexToUpdate = needsResize;
}
/// <summary>
/// Displays statistics and diagnostics information about the meshing cubes.
/// </summary>
public void OnGUI()
{
if (!m_enableDebugUI)
{
return;
}
GUI.color = Color.black;
string str = string.Format(
"<size=30>Total Verts/Triangles: {0}/{1} Volumes: {2} UpdateQueue: {3}</size>",
m_debugTotalVertices, m_debugTotalTriangles, m_meshes.Count, m_gridIndexToUpdate.Count);
GUI.Label(new Rect(40, 40, 1000, 40), str);
str = string.Format("<size=30>Remeshing Time: {0:F6} Remeshing Count: {1}</size>",
m_debugRemeshingTime, m_debugRemeshingCount);
GUI.Label(new Rect(40, 80, 1000, 40), str);
}
/// <summary>
/// Called when the 3D reconstruction is dirty.
/// </summary>
/// <param name="gridIndexList">List of GridIndex objects that are dirty and should be updated.</param>
public void OnTango3DReconstructionGridIndicesDirty(List<Tango3DReconstruction.GridIndex> gridIndexList)
{
// It's more important to be responsive than to handle all indexes. Clear the current list if we have
// fallen behind in processing.
m_gridIndexToUpdate.Clear();
m_gridIndexToUpdate.AddRange(gridIndexList);
}
/// <summary>
/// Clear the dynamic mesh's internal meshes.
///
/// NOTE: This does not clear the 3D Reconstruction's state. To do that call TangoApplication.Tango3DRClear().
/// </summary>
public void Clear()
{
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
m_meshes.Clear();
}
/// <summary>
/// Component for a dynamic, resizable mesh.
///
/// This caches the arrays for vertices, normals, colors, etc. to avoid putting extra pressure on the
/// garbage collector.
/// </summary>
private class TangoSingleDynamicMesh : MonoBehaviour
{
/// <summary>
/// The single mesh.
/// </summary>
public Mesh m_mesh = null;
/// <summary>
/// If set, the mesh collider for this mesh.
/// </summary>
public MeshCollider m_meshCollider = null;
/// <summary>
/// If true, then this should grow all arrays at some point in the future.
/// </summary>
public bool m_needsToGrow;
/// <summary>
/// Cache for Mesh.vertices.
/// </summary>
[HideInInspector]
public Vector3[] m_vertices;
/// <summary>
/// Cache for Mesh.uv.
/// </summary>
[HideInInspector]
public Vector2[] m_uv;
/// <summary>
/// Cache for Mesh.colors.
/// </summary>
[HideInInspector]
public Color32[] m_colors;
/// <summary>
/// Cache to Mesh.triangles.
/// </summary>
[HideInInspector]
public int[] m_triangles;
}
}
| |
/*
**
** electrifier
**
** Copyright 2017-19 Thorsten Jung, www.electrifier.org
**
** 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.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace electrifier
{
/// <summary>
/// SplashScreenForm, electrifier's splash screen.
/// </summary>
public class SplashScreenForm : Form
{
public Bitmap SplashScreenBitmap { get; private set; }
protected bool splashIsShown = false;
protected bool splashIsFadedOut = false;
protected byte opacity = 0xFF;
public new byte Opacity {
get => this.opacity;
set {
this.opacity = value;
this.UpdateWindowLayer();
}
}
public SplashScreenForm(bool splashIsShown, bool splashIsFadedOut, byte initialOpacity)
: this(splashIsShown, splashIsFadedOut) => this.opacity = initialOpacity;
public SplashScreenForm(bool splashIsShown, bool splashIsFadedOut)
{
this.TopMost = true;
this.FormBorderStyle = FormBorderStyle.None;
this.StartPosition = FormStartPosition.CenterScreen;
this.ShowInTaskbar = false;
if (splashIsShown)
{
this.SplashScreenBitmap = new Bitmap(Assembly.GetEntryAssembly().
GetManifestResourceStream("electrifier.SplashScreenForm.png"));
this.Size = this.SplashScreenBitmap.Size;
// Change window mode to layered window
User32.SetWindowLong(this.Handle, User32.GWL.EXSTYLE, User32.WS.EX_LAYERED);
// Show the splash screen form
this.splashIsShown = true;
this.Show();
}
}
// TODO: Fade out splash screen when closing...
public new void Show()
{
if (this.splashIsShown)
{
base.Show();
this.UpdateWindowLayer();
}
}
protected override void Dispose(bool disposing)
{
if (disposing && (this.SplashScreenBitmap != null))
this.SplashScreenBitmap.Dispose();
base.Dispose(disposing);
}
/// <summary>
/// WM_NCHITTEST message
///
/// Sent to a window in order to determine what part of the window corresponds to a particular screen coordinate.
/// </summary>
protected readonly int NCHITTEST = 0x84;
/// <summary>
/// The return value of the DefWindowProc function is one of the following values, indicating the position of
/// the cursor hot spot.
///
/// HTCAPTION = In a title bar.
/// </summary>
protected readonly IntPtr HTCAPTION = (IntPtr)2;
protected override void WndProc(ref Message m)
{
if (m.Msg == this.NCHITTEST)
{
m.Result = this.HTCAPTION;
return;
}
base.WndProc(ref m);
}
protected void UpdateWindowLayer()
{
if (!this.splashIsShown)
return;
IntPtr screenDC = IntPtr.Zero;
IntPtr memoryDC = IntPtr.Zero;
IntPtr bitmapHandle = IntPtr.Zero;
IntPtr oldBitmapHandle = IntPtr.Zero;
WinDef.SIZE splashScreenSize = new WinDef.SIZE(this.SplashScreenBitmap.Size);
try
{
WinDef.POINT destinationPosition = new WinDef.POINT(this.Left, this.Top);
WinDef.POINT sourcePosition = new WinDef.POINT(0, 0);
User32.BLENDFUNCTION blendFunction =
new User32.BLENDFUNCTION(User32.AC.SRC_OVER, 0, this.opacity, User32.AC.SRC_ALPHA);
screenDC = User32.GetDC(IntPtr.Zero);
memoryDC = Gdi32.CreateCompatibleDC(screenDC);
bitmapHandle = this.SplashScreenBitmap.GetHbitmap(Color.FromArgb(0x00000000));
oldBitmapHandle = Gdi32.SelectObject(memoryDC, bitmapHandle);
User32.UpdateLayeredWindow(this.Handle, screenDC, ref destinationPosition, ref splashScreenSize,
memoryDC, ref sourcePosition, 0, ref blendFunction, User32.ULW.ALPHA);
}
finally
{
User32.ReleaseDC(IntPtr.Zero, screenDC);
if (bitmapHandle != IntPtr.Zero)
{
Gdi32.SelectObject(memoryDC, oldBitmapHandle);
Gdi32.DeleteObject(bitmapHandle);
}
Gdi32.DeleteDC(memoryDC);
}
}
}
/// <summary>
/// Gdi32 contains the P/Invoke imports for GDI32.dll
/// </summary>
public static class Gdi32
{
/// <summary>
/// The CreateCompatibleDC function creates a memory device context (DC) compatible with the specified device.
/// </summary>
/// <param name="hDC">A handle to an existing DC. If this handle is NULL, the function creates a memory DC compatible
/// with the application's current screen.</param>
/// <returns>If the function succeeds, the return value is the handle to a memory DC.
/// If the function fails, the return value is NULL.</returns>
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
/// <summary>
/// The DeleteDC function deletes the specified device context (DC).
/// </summary>
/// <param name="hdc">A handle to the device context.</param>
/// <returns>If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero.</returns>
[DllImport("gdi32.dll")]
public static extern bool DeleteDC(IntPtr hdc);
/// <summary>
/// The DeleteObject function deletes a logical pen, brush, font, bitmap, region, or palette, freeing all system
/// resources associated with the object. After the object is deleted, the specified handle is no longer valid.
/// </summary>
/// <param name="hObject">A handle to a logical pen, brush, font, bitmap, region, or palette.</param>
/// <returns>If the function succeeds, the return value is nonzero.
/// If the specified handle is not valid or is currently selected into a DC, the return value is zero.</returns>
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
/// <summary>
/// The SelectObject function selects an object into the specified device context (DC).
/// The new object replaces the previous object of the same type.
/// </summary>
/// <param name="hDC">A handle to the DC.</param>
/// <param name="hObject">A handle to the object to be selected.</param>
/// <returns>If the selected object is not a region and the function succeeds, the return value is a handle
/// to the object being replaced.</returns>
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
}
/// <summary>
/// User32 contains the P/Invoke imports for User32.dll
/// </summary>
public static class User32
{
/// <summary>
/// The GetDC function retrieves a handle to a device context (DC) for the client area of a specified window or for
/// the entire screen. You can use the returned handle in subsequent GDI functions to draw in the DC.
/// The device context is an opaque data structure, whose values are used internally by GDI.
/// </summary>
/// <param name="hWnd">
/// A handle to the window whose DC is to be retrieved.
/// If this value is NULL, GetDC retrieves the DC for the entire screen.
/// </param>
/// <returns>
/// If the function succeeds, the return value is a handle to the DC for the specified window's client area.
/// If the function fails, the return value is NULL.
/// </returns>
[DllImport("user32.dll")]
public static extern IntPtr GetDC(IntPtr hWnd);
/// <summary>
/// The ReleaseDC function releases a device context (DC), freeing it for use by other applications.
/// The effect of the ReleaseDC function depends on the type of DC. It frees only common and window DCs.
/// It has no effect on class or private DCs.
/// </summary>
/// <param name="hWnd">A handle to the window whose DC is to be released.</param>
/// <param name="hDC">A handle to the DC to be released.</param>
/// <returns>
/// The return value indicates whether the DC was released. If the DC was released, the return value is 1.
/// If the DC was not released, the return value is zero.</returns>
[DllImport("user32.dll")]
public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
/// <summary>
/// Valid 'nIndex' parameter values for GetWindowLong and SetWindowLong.
///
/// The zero-based offset to the value to be set. Valid values are in the range zero through
/// the number of bytes of extra window memory, minus the size of an integer.
/// </summary>
/// <remarks>
/// <b>This is only an excerpt of those values used in electrifier!</b>
/// </remarks>
public enum GWL : int
{
/// <summary>
/// Sets a new extended window style.
/// </summary>
EXSTYLE = -20,
}
/// <summary>
/// Window Styles
/// The following are the window styles.
/// After the window has been created, these styles cannot be modified, except as noted.
/// </summary>
/// <remarks>
/// <b>This is only an excerpt of those values used in electrifier!</b>
/// </remarks>
public enum WS : uint
{
/// <summary>
/// The window is a layered window. This style cannot be used if the window has a class style of either
/// CS_OWNDC or CS_CLASSDC.
///
/// Windows 8: The WS_EX_LAYERED style is supported for top-level windows and child windows.
/// Previous Windows versions support WS_EX_LAYERED only for top-level windows.
/// </summary>
EX_LAYERED = 0x00080000,
}
/// <summary>
/// Changes an attribute of the specified window. The function also sets the
/// 32-bit (long) value at the specified offset into the extra window memory.
/// </summary>
/// <remarks>
/// <see href="https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setwindowlonga"/>
/// </remarks>
/// <param name="hWnd">A handle to the window and, indirectly, the class to which the window belongs.</param>
/// <param name="nIndex">The zero-based offset to the value to be set. Valid values are in the range zero through
/// the number of bytes of extra window memory, minus the size of an integer.</param>
/// <param name="dwNewLong">The replacement value.</param>
/// <returns>
/// If the function succeeds, the return value is the previous value of the specified 32-bit integer.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
[DllImport("user32.dll")]
public static extern Int32 SetWindowLong(IntPtr hWnd, GWL nIndex, WS dwNewLong);
/// <summary>
/// The BLENDFUNCTION structure controls blending by specifying
/// the blending functions for source and destination bitmaps.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BLENDFUNCTION
{
/// <summary>
/// The source blend operation. Currently, the only source and destination blend operation
/// that has been defined is AC_SRC_OVER. For details, see the following Remarks section.
/// </summary>
public AC BlendOp;
/// <summary>
/// Must be zero.
/// </summary>
public byte BlendFlags;
/// <summary>
/// Specifies an alpha transparency value to be used on the entire source bitmap.
/// The SourceConstantAlpha value is combined with any per-pixel alpha values in the source bitmap.
/// If you set SourceConstantAlpha to 0, it is assumed that your image is transparent.
/// Set the SourceConstantAlpha value to 255 (opaque) when you only want to use per-pixel alpha values.
/// </summary>
public byte SourceConstantAlpha;
/// <summary>
/// This member controls the way the source and destination bitmaps are interpreted.
/// AlphaFormat has the following value. <see cref="AC"/>
/// </summary>
public AC AlphaFormat;
public BLENDFUNCTION(AC blendOp, byte blendFlags, byte sourceConstantAlpha, AC alphaFormat)
{
this.BlendOp = blendOp;
this.BlendFlags = blendFlags;
this.SourceConstantAlpha = sourceConstantAlpha;
this.AlphaFormat = alphaFormat;
}
}
public enum AC : byte
{
SRC_OVER = 0x00,
/// <summary>
/// This flag is set when the bitmap has an Alpha channel (that is, per-pixel alpha).
/// Note that the APIs use premultiplied alpha, which means that the red, green and blue channel values in
/// the bitmap must be premultiplied with the alpha channel value. For example, if the alpha channel value
/// is x, the red, green and blue channels must be multiplied by x and divided by 0xff prior to the call.
/// </summary>
SRC_ALPHA = 0x01,
}
public enum ULW : uint
{
/// <summary>
/// Use crKey as the transparency color.
/// </summary>
COLORKEY = 1,
/// <summary>
/// Use pblend as the blend function.
/// If the display mode is 256 colors or less, the effect of this value is the same as the effect of ULW_OPAQUE.
/// </summary>
ALPHA = 2,
/// <summary>
/// Draw an opaque layered window.
/// </summary>
OPAQUE = 4,
}
/// <summary>
/// Updates the position, size, shape, content, and translucency of a layered window.
/// </summary>
/// <param name="hwnd">A handle to a layered window. A layered window is created by specifying WS_EX_LAYERED when
/// creating the window with the CreateWindowEx function.</param>
/// <param name="hdcDst">A handle to a DC for the screen. This handle is obtained by specifying NULL when calling
/// the function. It is used for palette color matching when the window contents are updated.
/// If hdcDst is NULL, the default palette will be used.</param>
/// <param name="pptDst">A pointer to a structure that specifies the new screen position of the layered window.
/// If the current position is not changing, pptDst can be NULL.</param>
/// <param name="psize">A pointer to a structure that specifies the new size of the layered window.
/// If the size of the window is not changing, psize can be NULL. If hdcSrc is NULL, psize must be NULL.</param>
/// <param name="hdcSrc">A handle to a DC for the surface that defines the layered window. This handle can be
/// obtained by calling the CreateCompatibleDC function.
/// If the shape and visual context of the window are not changing, hdcSrc can be NULL.</param>
/// <param name="pprSrc">A pointer to a structure that specifies the location of the layer in the device context.
/// If hdcSrc is NULL, pptSrc should be NULL.</param>
/// <param name="crKey">A structure that specifies the color key to be used when composing the layered window.
/// To generate a COLORREF, use the RGB macro.</param>
/// <param name="pBlend">A pointer to a structure that specifies the transparency value to be used when composing
/// the layered window.</param>
/// <param name="dwFlags">This parameter can be one of the following values: <see cref="ULW"/>.
/// If hdcSrc is NULL, dwFlags should be zero.</param>
/// <returns>If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero.To get extended error information, call GetLastError.</returns>
[DllImport("user32.dll")]
public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref WinDef.POINT pptDst,
ref WinDef.SIZE psize, IntPtr hdcSrc, ref WinDef.POINT pprSrc, int crKey, ref BLENDFUNCTION pBlend, ULW dwFlags);
}
/// <summary>
/// WinDef contains the P/Invoke imports for Windows GDI
/// </summary>
public static class WinDef
{
/// <summary>
/// The POINT structure defines the x- and y- coordinates of a point.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public Int32 X;
public Int32 Horizontal {
get { return this.X; }
set { this.X = value; }
}
public Int32 Y;
public Int32 Vertical {
get { return this.Y; }
set { this.Y = value; }
}
public POINT(Int32 x, Int32 y)
{
this.X = x;
this.Y = y;
}
public POINT(POINT point)
{
this.X = point.X;
this.Y = point.Y;
}
public POINT(System.Drawing.Point point)
{
this.X = point.X;
this.Y = point.Y;
}
public override string ToString()
{
return "(" + this.X + "," + this.Y + ")";
}
}
/// <summary>
/// The SIZE structure defines the width and height of a rectangle.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct SIZE
{
public Int32 Cx;
public Int32 Width {
get {
return this.Cx;
}
set {
this.Cx = value;
}
}
public Int32 Cy;
public Int32 Height {
get {
return this.Cy;
}
set {
this.Cy = value;
}
}
public SIZE(Int32 width, Int32 height)
{
this.Cx = width;
this.Cy = height;
}
public SIZE(System.Drawing.Size size)
{
this.Cx = size.Width;
this.Cy = size.Height;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using NSubstitute;
using Xunit;
namespace Octokit.Tests.Clients
{
/// <summary>
/// Client tests mostly just need to make sure they call the IApiConnection with the correct
/// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs.
/// </summary>
public class RepositoryBranchesClientTests
{
public class TheCtor
{
[Fact]
public void EnsuresNonNullArguments()
{
Assert.Throws<ArgumentNullException>(() => new RepositoryBranchesClient(null));
}
}
public class TheGetAllMethod
{
[Fact]
public async Task RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.GetAll("owner", "name");
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json", Args.ApiOptions);
}
[Fact]
public async Task RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.GetAll(1);
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json", Args.ApiOptions);
}
[Fact]
public async Task RequestsTheCorrectUrlWithApiOptions()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var options = new ApiOptions
{
PageCount = 1,
StartPage = 1,
PageSize = 1
};
await client.GetAll("owner", "name", options);
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json", options);
}
[Fact]
public async Task RequestsTheCorrectUrlWithRepositoryIdWithApiOptions()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var options = new ApiOptions
{
PageCount = 1,
StartPage = 1,
PageSize = 1
};
await client.GetAll(1, options);
connection.Received()
.GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json", options);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "name"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "name", ApiOptions.None));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null, ApiOptions.None));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", "name", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "name"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "name", ApiOptions.None));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", "", ApiOptions.None));
}
}
public class TheGetMethod
{
[Fact]
public async Task RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.Get("owner", "repo", "branch");
connection.Received()
.Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null, "application/vnd.github.loki-preview+json");
}
[Fact]
public async Task RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
await client.Get(1, "branch");
connection.Received()
.Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch"), null, "application/vnd.github.loki-preview+json");
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "repo", ""));
}
}
public class TheEditMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchUpdate();
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.Edit("owner", "repo", "branch", update);
connection.Received()
.Patch<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), Arg.Any<BranchUpdate>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchUpdate();
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.Edit(1, "branch", update);
connection.Received()
.Patch<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch"), Arg.Any<BranchUpdate>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new BranchUpdate();
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.Edit(1, "", update));
}
}
public class TheGetBranchProtectectionMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetBranchProtection("owner", "repo", "branch");
connection.Received()
.Get<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetBranchProtection(1, "branch");
connection.Received()
.Get<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranchProtection(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranchProtection(1, ""));
}
}
public class TheUpdateBranchProtectionMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionSettingsUpdate(
new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }));
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateBranchProtection("owner", "repo", "branch", update);
connection.Received()
.Put<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), Arg.Any<BranchProtectionSettingsUpdate>(), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionSettingsUpdate(
new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }));
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateBranchProtection(1, "branch", update);
connection.Received()
.Put<BranchProtectionSettings>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), Arg.Any<BranchProtectionSettingsUpdate>(), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new BranchProtectionSettingsUpdate(
new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" }));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateBranchProtection(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateBranchProtection(1, "", update));
}
}
public class TheDeleteBranchProtectectionMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteBranchProtection("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteBranchProtection(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteBranchProtection(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteBranchProtection(1, ""));
}
}
public class TheGetRequiredStatusChecksMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetRequiredStatusChecks("owner", "repo", "branch");
connection.Received()
.Get<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetRequiredStatusChecks(1, "branch");
connection.Received()
.Get<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecks(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecks(1, ""));
}
}
public class TheUpdateRequiredStatusChecksMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" });
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateRequiredStatusChecks("owner", "repo", "branch", update);
connection.Received()
.Patch<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), Arg.Any<BranchProtectionRequiredStatusChecksUpdate>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" });
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateRequiredStatusChecks(1, "branch", update);
connection.Received()
.Patch<BranchProtectionRequiredStatusChecks>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), Arg.Any<BranchProtectionRequiredStatusChecksUpdate>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new BranchProtectionRequiredStatusChecksUpdate(true, new[] { "test" });
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecks(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecks(1, "", update));
}
}
public class TheDeleteRequiredStatusChecksMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteRequiredStatusChecks("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteRequiredStatusChecks(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecks(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecks(1, ""));
}
}
public class TheGetRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetRequiredStatusChecksContexts("owner", "repo", "branch");
connection.Received()
.Get<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetRequiredStatusChecksContexts(1, "branch");
connection.Received()
.Get<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecksContexts(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecksContexts("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecksContexts("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetRequiredStatusChecksContexts(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecksContexts("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecksContexts("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecksContexts("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetRequiredStatusChecksContexts(1, ""));
}
}
public class TheUpdateRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateRequiredStatusChecksContexts("owner", "repo", "branch", update);
connection.Received()
.Put<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var update = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateRequiredStatusChecksContexts(1, "branch", update);
connection.Received()
.Put<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var update = new List<string>() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(null, "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", null, "branch", update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(1, null, update));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateRequiredStatusChecksContexts(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("", "repo", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("owner", "", "branch", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts("owner", "repo", "", update));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateRequiredStatusChecksContexts(1, "", update));
}
}
public class TheAddRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newContexts = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddRequiredStatusChecksContexts("owner", "repo", "branch", newContexts);
connection.Received()
.Post<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newContexts = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddRequiredStatusChecksContexts(1, "branch", newContexts);
connection.Received()
.Post<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newContexts = new List<string>() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(null, "repo", "branch", newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", null, "branch", newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", null, newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(1, null, newContexts));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddRequiredStatusChecksContexts(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("", "repo", "branch", newContexts));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("owner", "", "branch", newContexts));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts("owner", "repo", "", newContexts));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddRequiredStatusChecksContexts(1, "", newContexts));
}
}
public class TheDeleteRequiredStatusChecksContextsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var contextsToRemove = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteRequiredStatusChecksContexts("owner", "repo", "branch", contextsToRemove);
connection.Received()
.Delete<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var contextsToRemove = new List<string>() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteRequiredStatusChecksContexts(1, "branch", contextsToRemove);
connection.Received()
.Delete<IReadOnlyList<string>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/required_status_checks/contexts"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var contextsToRemove = new List<string>() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(null, "repo", "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", null, "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", null, contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(1, null, contextsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteRequiredStatusChecksContexts(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("", "repo", "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("owner", "", "branch", contextsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts("owner", "repo", "", contextsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteRequiredStatusChecksContexts(1, "", contextsToRemove));
}
}
public class TheGetAdminEnforcementMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetAdminEnforcement("owner", "repo", "branch");
connection.Received()
.Get<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetAdminEnforcement(1, "branch");
connection.Received()
.Get<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAdminEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetAdminEnforcement(1, ""));
}
}
public class TheAddAdminEnforcement
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddAdminEnforcement("owner", "repo", "branch");
connection.Received()
.Post<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddAdminEnforcement(1, "branch");
connection.Received()
.Post<EnforceAdmins>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddAdminEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddAdminEnforcement(1, ""));
}
}
public class TheRemoveAdminEnforcement
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.RemoveAdminEnforcement("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.RemoveAdminEnforcement(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/enforce_admins"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.RemoveAdminEnforcement(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.RemoveAdminEnforcement(1, ""));
}
}
public class TheGetProtectedBranchRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetProtectedBranchRestrictions("owner", "repo", "branch");
connection.Received()
.Get<BranchProtectionPushRestrictions>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetProtectedBranchRestrictions(1, "branch");
connection.Received()
.Get<BranchProtectionPushRestrictions>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchRestrictions(1, ""));
}
}
public class TheDeleteProtectedBranchRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchRestrictions("owner", "repo", "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchRestrictions(1, "branch");
connection.Connection.Received()
.Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions"), Arg.Any<object>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchRestrictions(1, ""));
}
}
public class TheGetProtectedBranchTeamRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetProtectedBranchTeamRestrictions("owner", "repo", "branch");
connection.Received()
.Get<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetProtectedBranchTeamRestrictions(1, "branch");
connection.Received()
.Get<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchTeamRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchTeamRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchTeamRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchTeamRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchTeamRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchTeamRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchTeamRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchTeamRestrictions(1, ""));
}
}
public class TheSetProtectedBranchTeamRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "branch", newTeams);
connection.Received()
.Put<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateProtectedBranchTeamRestrictions(1, "branch", newTeams);
connection.Received()
.Put<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newTeams = new BranchProtectionTeamCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(null, "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", null, "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(1, null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchTeamRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("", "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions("owner", "repo", "", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchTeamRestrictions(1, "", newTeams));
}
}
public class TheAddProtectedBranchTeamRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddProtectedBranchTeamRestrictions("owner", "repo", "branch", newTeams);
connection.Received()
.Post<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newTeams = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddProtectedBranchTeamRestrictions(1, "branch", newTeams);
connection.Received()
.Post<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newTeams = new BranchProtectionTeamCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(null, "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", null, "branch", newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(1, null, newTeams));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchTeamRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("", "repo", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("owner", "", "branch", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions("owner", "repo", "", newTeams));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchTeamRestrictions(1, "", newTeams));
}
}
public class TheDeleteProtectedBranchTeamRestrictions
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var teamsToRemove = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "branch", teamsToRemove);
connection.Received()
.Delete<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var teamsToRemove = new BranchProtectionTeamCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchTeamRestrictions(1, "branch", teamsToRemove);
connection.Received()
.Delete<IReadOnlyList<Team>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/teams"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var teamsToRemove = new BranchProtectionTeamCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(null, "repo", "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", null, "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", null, teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(1, null, teamsToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchTeamRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("", "repo", "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "", "branch", teamsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions("owner", "repo", "", teamsToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchTeamRestrictions(1, "", teamsToRemove));
}
}
public class TheGetProtectedBranchUserRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetProtectedBranchUserRestrictions("owner", "repo", "branch");
connection.Received()
.Get<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.GetProtectedBranchUserRestrictions(1, "branch");
connection.Received()
.Get<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchUserRestrictions(null, "repo", "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchUserRestrictions("owner", null, "branch"));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchUserRestrictions("owner", "repo", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetProtectedBranchUserRestrictions(1, null));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchUserRestrictions("", "repo", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchUserRestrictions("owner", "", "branch"));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchUserRestrictions("owner", "repo", ""));
await Assert.ThrowsAsync<ArgumentException>(() => client.GetProtectedBranchUserRestrictions(1, ""));
}
}
public class TheSetProtectedBranchUserRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateProtectedBranchUserRestrictions("owner", "repo", "branch", newUsers);
connection.Received()
.Put<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.UpdateProtectedBranchUserRestrictions(1, "branch", newUsers);
connection.Received()
.Put<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), null, previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newUsers = new BranchProtectionUserCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(null, "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", null, "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(1, null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.UpdateProtectedBranchUserRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("", "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions("owner", "repo", "", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.UpdateProtectedBranchUserRestrictions(1, "", newUsers));
}
}
public class TheAddProtectedBranchUserRestrictionsMethod
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddProtectedBranchUserRestrictions("owner", "repo", "branch", newUsers);
connection.Received()
.Post<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var newUsers = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.AddProtectedBranchUserRestrictions(1, "branch", newUsers);
connection.Received()
.Post<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var newUsers = new BranchProtectionUserCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(null, "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", null, "branch", newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(1, null, newUsers));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.AddProtectedBranchUserRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("", "repo", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("owner", "", "branch", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions("owner", "repo", "", newUsers));
await Assert.ThrowsAsync<ArgumentException>(() => client.AddProtectedBranchUserRestrictions(1, "", newUsers));
}
}
public class TheDeleteProtectedBranchUserRestrictions
{
[Fact]
public void RequestsTheCorrectUrl()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var usersToRemove = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchUserRestrictions("owner", "repo", "branch", usersToRemove);
connection.Received()
.Delete<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public void RequestsTheCorrectUrlWithRepositoryId()
{
var connection = Substitute.For<IApiConnection>();
var client = new RepositoryBranchesClient(connection);
var usersToRemove = new BranchProtectionUserCollection() { "test" };
const string previewAcceptsHeader = "application/vnd.github.loki-preview+json";
client.DeleteProtectedBranchUserRestrictions(1, "branch", usersToRemove);
connection.Received()
.Delete<IReadOnlyList<User>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch/protection/restrictions/users"), Arg.Any<IReadOnlyList<string>>(), previewAcceptsHeader);
}
[Fact]
public async Task EnsuresNonNullArguments()
{
var client = new RepositoryBranchesClient(Substitute.For<IApiConnection>());
var usersToRemove = new BranchProtectionUserCollection() { "test" };
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(null, "repo", "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", null, "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", null, usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", "branch", null));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(1, null, usersToRemove));
await Assert.ThrowsAsync<ArgumentNullException>(() => client.DeleteProtectedBranchUserRestrictions(1, "branch", null));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("", "repo", "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "", "branch", usersToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions("owner", "repo", "", usersToRemove));
await Assert.ThrowsAsync<ArgumentException>(() => client.DeleteProtectedBranchUserRestrictions(1, "", usersToRemove));
}
}
}
}
| |
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Cms.Web.Common.DependencyInjection;
namespace Umbraco.Cms.Core.Configuration
{
public class JsonConfigManipulator : IConfigManipulator
{
private readonly IConfiguration _configuration;
private readonly ILogger<JsonConfigManipulator> _logger;
private readonly object _locker = new object();
[Obsolete]
public JsonConfigManipulator(IConfiguration configuration)
: this(configuration, StaticServiceProvider.Instance.GetRequiredService<ILogger<JsonConfigManipulator>>())
{ }
public JsonConfigManipulator(
IConfiguration configuration,
ILogger<JsonConfigManipulator> logger)
{
_configuration = configuration;
_logger = logger;
}
public string UmbracoConnectionPath { get; } = $"ConnectionStrings:{Cms.Core.Constants.System.UmbracoConnectionName}";
public void RemoveConnectionString()
{
var provider = GetJsonConfigurationProvider(UmbracoConnectionPath);
var json = GetJson(provider);
if (json is null)
{
_logger.LogWarning("Failed to remove connection string from JSON configuration.");
return;
}
RemoveJsonKey(json, UmbracoConnectionPath);
SaveJson(provider, json);
}
public void SaveConnectionString(string connectionString, string providerName)
{
var provider = GetJsonConfigurationProvider();
var json = GetJson(provider);
if (json is null)
{
_logger.LogWarning("Failed to save connection string in JSON configuration.");
return;
}
var item = GetConnectionItem(connectionString, providerName);
json.Merge(item, new JsonMergeSettings());
SaveJson(provider, json);
}
public void SaveConfigValue(string key, object value)
{
var provider = GetJsonConfigurationProvider();
var json = GetJson(provider);
if (json is null)
{
_logger.LogWarning("Failed to save configuration key \"{Key}\" in JSON configuration.", key);
return;
}
JToken token = json;
foreach (var propertyName in key.Split(new[] { ':' }))
{
if (token is null)
break;
token = CaseSelectPropertyValues(token, propertyName);
}
if (token is null)
return;
var writer = new JTokenWriter();
writer.WriteValue(value);
token.Replace(writer.Token);
SaveJson(provider, json);
}
public void SaveDisableRedirectUrlTracking(bool disable)
{
var provider = GetJsonConfigurationProvider();
var json = GetJson(provider);
if (json is null)
{
_logger.LogWarning("Failed to save enabled/disabled state for redirect URL tracking in JSON configuration.");
return;
}
var item = GetDisableRedirectUrlItem(disable);
json.Merge(item, new JsonMergeSettings());
SaveJson(provider, json);
}
public void SetGlobalId(string id)
{
var provider = GetJsonConfigurationProvider();
var json = GetJson(provider);
if (json is null)
{
_logger.LogWarning("Failed to save global identifier in JSON configuration.");
return;
}
var item = GetGlobalIdItem(id);
json.Merge(item, new JsonMergeSettings());
SaveJson(provider, json);
}
private object GetGlobalIdItem(string id)
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("Umbraco");
writer.WriteStartObject();
writer.WritePropertyName("CMS");
writer.WriteStartObject();
writer.WritePropertyName("Global");
writer.WriteStartObject();
writer.WritePropertyName("Id");
writer.WriteValue(id);
writer.WriteEndObject();
writer.WriteEndObject();
writer.WriteEndObject();
writer.WriteEndObject();
return writer.Token;
}
private JToken GetDisableRedirectUrlItem(bool value)
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("Umbraco");
writer.WriteStartObject();
writer.WritePropertyName("CMS");
writer.WriteStartObject();
writer.WritePropertyName("WebRouting");
writer.WriteStartObject();
writer.WritePropertyName("DisableRedirectUrlTracking");
writer.WriteValue(value);
writer.WriteEndObject();
writer.WriteEndObject();
writer.WriteEndObject();
writer.WriteEndObject();
return writer.Token;
}
private JToken GetConnectionItem(string connectionString, string providerName)
{
JTokenWriter writer = new JTokenWriter();
writer.WriteStartObject();
writer.WritePropertyName("ConnectionStrings");
writer.WriteStartObject();
writer.WritePropertyName(Cms.Core.Constants.System.UmbracoConnectionName);
writer.WriteValue(connectionString);
writer.WriteEndObject();
writer.WriteEndObject();
return writer.Token;
}
private static void RemoveJsonKey(JObject json, string key)
{
JToken token = json;
foreach (var propertyName in key.Split(new[] { ':' }))
{
token = CaseSelectPropertyValues(token, propertyName);
}
token?.Parent?.Remove();
}
private void SaveJson(JsonConfigurationProvider provider, JObject json)
{
lock (_locker)
{
if (provider.Source.FileProvider is PhysicalFileProvider physicalFileProvider)
{
var jsonFilePath = Path.Combine(physicalFileProvider.Root, provider.Source.Path);
try
{
using (var sw = new StreamWriter(jsonFilePath, false))
using (var jsonTextWriter = new JsonTextWriter(sw)
{
Formatting = Formatting.Indented,
})
{
json?.WriteTo(jsonTextWriter);
}
}
catch (IOException exception)
{
_logger.LogWarning(exception, "JSON configuration could not be written: {path}", jsonFilePath);
}
}
}
}
private JObject GetJson(JsonConfigurationProvider provider)
{
lock (_locker)
{
if (provider.Source.FileProvider is not PhysicalFileProvider physicalFileProvider)
{
return null;
}
var jsonFilePath = Path.Combine(physicalFileProvider.Root, provider.Source.Path);
try
{
var serializer = new JsonSerializer();
using var sr = new StreamReader(jsonFilePath);
using var jsonTextReader = new JsonTextReader(sr);
return serializer.Deserialize<JObject>(jsonTextReader);
}
catch (IOException exception)
{
_logger.LogWarning(exception, "JSON configuration could not be read: {path}", jsonFilePath);
return null;
}
}
}
private JsonConfigurationProvider GetJsonConfigurationProvider(string requiredKey = null)
{
if (_configuration is IConfigurationRoot configurationRoot)
{
foreach (var provider in configurationRoot.Providers)
{
if (provider is JsonConfigurationProvider jsonConfigurationProvider)
{
if (requiredKey is null || provider.TryGet(requiredKey, out _))
{
return jsonConfigurationProvider;
}
}
}
}
throw new InvalidOperationException("Could not find a writable json config source");
}
/// <summary>
/// Returns the property value when case insensative
/// </summary>
/// <remarks>
/// This method is required because keys are case insensative in IConfiguration.
/// JObject[..] do not support case insensative and JObject.Property(...) do not return a new JObject.
/// </remarks>
private static JToken CaseSelectPropertyValues(JToken token, string name)
{
if (token is JObject obj)
{
foreach (var property in obj.Properties())
{
if (name is null)
return property.Value;
if (string.Equals(property.Name, name, StringComparison.OrdinalIgnoreCase))
return property.Value;
}
}
return null;
}
}
}
| |
// 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,
// 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.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
using VSLangProj;
namespace Microsoft.PythonTools.Project {
[ComVisible(true)]
internal class WebPiReferenceNode : ReferenceNode {
private readonly string _feed; // The name of the assembly this refernce represents
private readonly string _productId, _friendlyName;
private Automation.OAWebPiReference _automationObject;
private bool _isDisposed;
internal WebPiReferenceNode(ProjectNode root, string filename, string productId, string friendlyName)
: this(root, null, filename, productId, friendlyName) {
}
internal WebPiReferenceNode(ProjectNode root, ProjectElement element, string filename, string productId, string friendlyName)
: base(root, element) {
Utilities.ArgumentNotNullOrEmpty("filename", filename);
_feed = filename;
_productId = productId;
_friendlyName = friendlyName;
}
public override string Url {
get {
return _feed + "?" + _productId;
}
}
public override string Caption {
get {
return _friendlyName;
}
}
internal override object Object {
get {
if (null == _automationObject) {
_automationObject = new Automation.OAWebPiReference(this);
}
return _automationObject;
}
}
protected override bool SupportsIconMonikers {
get { return true; }
}
protected override ImageMoniker GetIconMoniker(bool open) {
return KnownMonikers.XWorldFile;
}
protected override NodeProperties CreatePropertiesObject() {
return new WebPiReferenceNodeProperties(this);
}
#region methods
public override Guid ItemTypeGuid {
get {
return VSConstants.ItemTypeGuid.VirtualFolder_guid;
}
}
/// <summary>
/// Links a reference node to the project and hierarchy.
/// </summary>
protected override void BindReferenceData() {
Debug.Assert(_feed != null, "The _feed field has not been initialized");
// If the item has not been set correctly like in case of a new reference added it now.
// The constructor for the AssemblyReference node will create a default project item. In that case the Item is null.
// We need to specify here the correct project element.
if (ItemNode == null || ItemNode is VirtualProjectElement) {
ItemNode = new MsBuildProjectElement(
ProjectMgr,
_feed + "?" + _productId,
ProjectFileConstants.WebPiReference
);
}
// Set the basic information we know about
ItemNode.SetMetadata("Feed", _feed);
ItemNode.SetMetadata("ProductId", _productId);
ItemNode.SetMetadata("FriendlyName", _friendlyName);
}
/// <summary>
/// Disposes the node
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing) {
if (_isDisposed) {
return;
}
base.Dispose(disposing);
_isDisposed = true;
}
/// <summary>
/// Checks if an assembly is already added. The method parses all references and compares the full assemblynames, or the location of the assemblies to decide whether two assemblies are the same.
/// </summary>
/// <returns>true if the assembly has already been added.</returns>
protected override bool IsAlreadyAdded() {
ReferenceContainerNode referencesFolder = ProjectMgr.GetReferenceContainer() as ReferenceContainerNode;
Debug.Assert(referencesFolder != null, "Could not find the References node");
if (referencesFolder == null) {
// Return true so that our caller does not try and add us.
return true;
}
for (HierarchyNode n = referencesFolder.FirstChild; n != null; n = n.NextSibling) {
var extensionRefNode = n as WebPiReferenceNode;
if (null != extensionRefNode) {
// We will check if Url of the assemblies is the same.
// TODO: Check full assembly name?
if (PathUtils.IsSamePath(extensionRefNode.Url, Url)) {
return true;
}
}
}
return false;
}
/// <summary>
/// Determines if this is node a valid node for painting the default reference icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon() {
return true;
}
/// <summary>
/// Overridden method. The method updates the build dependency list before removing the node from the hierarchy.
/// </summary>
public override bool Remove(bool removeFromStorage) {
if (ProjectMgr == null) {
return false;
}
ItemNode.RemoveFromProjectFile();
return base.Remove(removeFromStorage);
}
#endregion
}
[CLSCompliant(false), ComVisible(true)]
public class WebPiReferenceNodeProperties : NodeProperties {
#region properties
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.RefName)]
[SRDescriptionAttribute(SR.RefNameDescription)]
[Browsable(true)]
[AutomationBrowsable(true)]
public override string Name {
get {
return this.HierarchyNode.Caption;
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.WebPiFeed)]
[SRDescriptionAttribute(SR.WebPiFeedDescription)]
[Browsable(true)]
public string Feed {
get {
return this.GetProperty("Feed", "");
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.WebPiProduct)]
[SRDescriptionAttribute(SR.WebPiProductDescription)]
[Browsable(true)]
public virtual string ProductId {
get {
return this.GetProperty("ProductID", "");
}
}
[SRCategoryAttribute(SR.Advanced)]
[SRDisplayName(SR.BuildAction)]
[SRDescriptionAttribute(SR.BuildActionDescription)]
[TypeConverter(typeof(BuildActionTypeConverter))]
public prjBuildAction BuildAction {
get {
return prjBuildAction.prjBuildActionNone;
}
}
#endregion
#region ctors
internal WebPiReferenceNodeProperties(WebPiReferenceNode node)
: base(node) {
}
#endregion
#region overridden methods
public override string GetClassName() {
return SR.GetString(SR.WebPiReferenceProperties);
}
#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;
using System.Text;
using System.Collections.Generic;
using System.Composition;
using System.Composition.Hosting;
using System.Composition.Hosting.Providers;
using System.Linq;
using Xunit;
namespace System.Composition.UnitTests
{
public interface ISharedTestingClass
{
void Method();
}
[Export(typeof(ISharedTestingClass))]
public class NonSharedClass : ISharedTestingClass
{
[ImportingConstructor]
public NonSharedClass()
{
}
public void Method() { }
}
[Export(typeof(ISharedTestingClass))]
[Shared]
public class SharedClass : ISharedTestingClass
{
[ImportingConstructor]
public SharedClass()
{
}
public void Method()
{
}
}
[Export]
[Shared]
public class ClassWithExportFactoryShared
{
private readonly ExportFactory<ISharedTestingClass> _fact;
[ImportingConstructor]
public ClassWithExportFactoryShared(ExportFactory<ISharedTestingClass> factory)
{
_fact = factory;
}
public ISharedTestingClass Method()
{
using (var b = _fact.CreateExport())
{
return b.Value;
}
}
}
[Export]
public class ClassWithExportFactoryNonShared
{
private readonly ExportFactory<ISharedTestingClass> _fact;
[ImportingConstructor]
public ClassWithExportFactoryNonShared(ExportFactory<ISharedTestingClass> factory)
{
_fact = factory;
}
public ISharedTestingClass Method()
{
using (var b = _fact.CreateExport())
{
return b.Value;
}
}
}
[Export]
public class ClassWithExportFactoryAsAProperty
{
[Import]
public ExportFactory<ISharedTestingClass> _fact { get; set; }
public ClassWithExportFactoryAsAProperty()
{
}
public ISharedTestingClass Method()
{
using (var b = _fact.CreateExport())
{
return b.Value;
}
}
}
internal interface IX { }
internal interface IY { }
[Export]
[Shared("Boundary")]
public class A
{
public int SharedState { get; set; }
}
[Export]
public class B
{
public A InstanceA { get; set; }
public D InstanceD { get; set; }
[ImportingConstructor]
public B(A a, D d)
{
InstanceA = a;
InstanceD = d;
}
}
[Export]
public class D
{
public A InstanceA;
[ImportingConstructor]
public D(A a)
{
InstanceA = a;
}
}
[Export]
public class C
{
private readonly ExportFactory<B> _fact;
[ImportingConstructor]
public C([SharingBoundary("Boundary")]ExportFactory<B> fact)
{
_fact = fact;
}
public B CreateInstance()
{
using (var b = _fact.CreateExport())
{
return b.Value;
}
}
}
[Export]
public class CPrime
{
private readonly ExportFactory<B> _fact;
[ImportingConstructor]
public CPrime(ExportFactory<B> fact)
{
_fact = fact;
}
public B CreateInstance()
{
using (var b = _fact.CreateExport())
{
return b.Value;
}
}
}
[Export]
[Shared("Boundary")]
public class CirC
{
public CirA DepA { get; private set; }
[ImportingConstructor]
public CirC(CirA a)
{
DepA = a;
}
}
[Export]
[Shared]
public class CirA
{
public int SharedState;
private readonly ExportFactory<CirB> _fact;
[ImportingConstructor]
public CirA([SharingBoundary("Boundary")]ExportFactory<CirB> b)
{
_fact = b;
}
public CirB CreateInstance()
{
using (var ins = _fact.CreateExport())
{
return ins.Value;
}
}
}
[Export]
public class CirB
{
public CirC DepC { get; private set; }
[ImportingConstructor]
public CirB(CirC c)
{
DepC = c;
}
}
public interface IProj { }
[Export]
public class SolA
{
private readonly IEnumerable<ExportFactory<IProj>> _fact;
public List<IProj> Projects { get; private set; }
[ImportingConstructor]
public SolA([ImportMany][SharingBoundary("B1", "B2")] IEnumerable<ExportFactory<IProj>> c)
{
Projects = new List<IProj>();
_fact = c;
}
public void SetupProject()
{
foreach (var fact in _fact)
{
using (var instance = fact.CreateExport())
{
Projects.Add(instance.Value);
}
}
}
}
[Export(typeof(IProj))]
public class ProjA : IProj
{
[ImportingConstructor]
public ProjA(DocA docA, ColA colA)
{
}
}
[Export(typeof(IProj))]
public class ProjB : IProj
{
[ImportingConstructor]
public ProjB(DocB docA, ColB colA)
{
}
}
[Export]
public class DocA
{
[ImportingConstructor]
public DocA(ColA colA)
{
}
}
[Export]
public class DocB
{
[ImportingConstructor]
public DocB(ColB colB)
{
}
}
[Export]
[Shared("B1")]
public class ColA
{
public ColA()
{ }
}
[Export]
[Shared("B2")]
public class ColB
{
public ColB()
{ }
}
public interface ICol { }
[Export(typeof(IX)), Export(typeof(IY)), Shared]
public class XY : IX, IY { }
public class SharingTest : ContainerTests
{
/// <summary>
/// Two issues here One is that the message could be improved
/// "The component (unknown) cannot be created outside the Boundary sharing boundary."
/// Second is we don`t fail when we getExport for CPrime
/// we fail only when we create instance of B.. is that correct.
/// </summary>
[Fact]
public void BoundaryExposedBoundaryButNoneImported()
{
try
{
var cc = CreateContainer(typeof(A), typeof(B), typeof(CPrime), typeof(D));
var cInstance = cc.GetExport<CPrime>();
var bIn1 = cInstance.CreateInstance();
}
catch (Exception ex)
{
Assert.True(ex.Message.Contains("The component (unknown) cannot be created outside the Boundary sharing boundary"));
}
}
/// <summary>
/// Need a partcreationpolicy currently.
/// Needs to be fixed so that specifying boundary would automatically create the shared
/// </summary>
[Fact]
public void BoundarySharingTest()
{
var cc = CreateContainer(typeof(A), typeof(B), typeof(C), typeof(D));
var cInstance = cc.GetExport<C>();
var bIn1 = cInstance.CreateInstance();
var bIn2 = cInstance.CreateInstance();
bIn1.InstanceA.SharedState = 1;
var val1 = bIn1.InstanceD.InstanceA;
bIn2.InstanceA.SharedState = 5;
var val2 = bIn2.InstanceD.InstanceA;
Assert.True(val1.SharedState == 1);
Assert.True(val2.SharedState == 5);
}
/// <summary>
/// CirA root of the composition has to be shared explcitly.
/// </summary>
[Fact]
public void CircularBoundarySharingTest()
{
var cc = CreateContainer(typeof(CirA), typeof(CirB), typeof(CirC));
var cInstance = cc.GetExport<CirA>();
cInstance.SharedState = 1;
var bInstance1 = cInstance.CreateInstance();
Assert.Equal(bInstance1.DepC.DepA.SharedState, 1);
bInstance1.DepC.DepA.SharedState = 10;
cInstance.CreateInstance();
Assert.Equal(bInstance1.DepC.DepA.SharedState, 10);
}
/// <summary>
/// Something is badly busted here.. I am getting a null ref exception
/// </summary>
[Fact]
public void MultipleBoundarySpecified()
{
var cc = CreateContainer(typeof(ProjA), typeof(ProjB), typeof(SolA), typeof(DocA), typeof(DocB), typeof(ColA), typeof(ColB));
var solInstance = cc.GetExport<SolA>();
solInstance.SetupProject();
}
[Fact]
public void SharedPartExportingMultipleContractsSharesAnInstance()
{
var cc = CreateContainer(typeof(XY));
var x = cc.GetExport<IX>();
var y = cc.GetExport<IY>();
Assert.Same(x, y);
}
[Fact]
public void GetExportsCreatesInstancedObjectByDefault()
{
var cc = CreateContainer(typeof(NonSharedClass));
var val1 = cc.GetExport<ISharedTestingClass>();
var val2 = cc.GetExport<ISharedTestingClass>();
Assert.NotSame(val1, val2);
}
[Fact]
public void GetExportsCreatesSharedObjectsWhenSpecified()
{
var cc = CreateContainer(typeof(SharedClass));
var val1 = cc.GetExport<ISharedTestingClass>();
var val2 = cc.GetExport<ISharedTestingClass>();
Assert.Same(val1, val2);
}
/// <summary>
/// Class with export factory that, which is shared that has a part that is non shared
/// verify that GetExport returns only one instance regardless of times it is called
/// verify that On Method call different instances are returned.
/// </summary>
[Fact]
public void ExportFactoryCreatesNewInstances()
{
var cc = CreateContainer(typeof(ClassWithExportFactoryShared), typeof(NonSharedClass));
var b1 = cc.GetExport<ClassWithExportFactoryShared>();
var b2 = cc.GetExport<ClassWithExportFactoryShared>();
var inst1 = b1.Method();
var inst2 = b1.Method();
Assert.Same(b1, b2);
Assert.NotSame(inst1, inst2);
}
/// <summary>
/// ExportFactory should be importable as a property
/// </summary>
[Fact]
public void ClassWithExportFactoryAsAProperty()
{
var cc = CreateContainer(typeof(ClassWithExportFactoryAsAProperty), typeof(NonSharedClass));
var b1 = cc.GetExport<ClassWithExportFactoryAsAProperty>();
var inst1 = b1.Method();
var inst2 = b1.Method();
Assert.NotNull(b1._fact);
Assert.NotSame(inst1, inst2);
}
/// <summary>
/// ExportFactory class is itself shared and
/// will still respect the CreationPolicyAttribute on a part. If the export factory
/// is creating a part which is shared, it will return back the same instance of the part.
/// </summary>
[Fact]
public void ClassWithExportFactoryAndSharedExport()
{
var cc = CreateContainer(typeof(ClassWithExportFactoryShared), typeof(SharedClass));
var b1 = cc.GetExport<ClassWithExportFactoryShared>();
var b2 = cc.GetExport<ClassWithExportFactoryShared>();
var inst1 = b1.Method();
var inst2 = b2.Method();
Assert.Same(b1, b2);
Assert.Same(inst1, inst2);
}
/// <summary>
/// Class which is nonShared has an exportFactory in it for a shared part.
/// Two instances of the root class are created , the part created using export factory should not be shared
/// </summary>
[Fact]
public void ClassWithNonSharedExportFactoryCreatesSharedInstances()
{
var cc = CreateContainer(typeof(ClassWithExportFactoryNonShared), typeof(SharedClass));
var b1 = cc.GetExport<ClassWithExportFactoryNonShared>();
var b2 = cc.GetExport<ClassWithExportFactoryNonShared>();
var inst1 = b1.Method();
var inst2 = b2.Method();
Assert.NotSame(b1, b2);
Assert.Same(inst1, inst2);
}
[Shared, Export]
public class ASharedPart { }
[Fact]
public void ConsistentResultsAreReturneWhenResolvingLargeNumbersOfSharedParts()
{
var config = new ContainerConfiguration();
// Chosen to cause overflows in SmallSparseInitOnlyArray
for (var i = 0; i < 1000; ++i)
config.WithPart<ASharedPart>();
Assert.NotEqual(new ASharedPart(), new ASharedPart());
var container = config.CreateContainer();
var first = container.GetExports<ASharedPart>().ToList();
var second = container.GetExports<ASharedPart>().ToList();
Assert.Equal(first, second);
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Oculus.VR.Editor
{
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoad]
#endif
public sealed class OVRPlatformToolSettings : ScriptableObject
{
private const string DEFAULT_RELEASE_CHANNEL = "Alpha";
public enum GamepadType
{
OFF,
TWINSTICK,
RIGHT_D_PAD,
LEFT_D_PAD,
};
public static string AppID
{
get
{
return Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None ? Instance.appIDs[(int)Instance.targetPlatform] : "";
}
set
{
if (Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None)
{
Instance.appIDs[(int)Instance.targetPlatform] = value;
}
}
}
public static string ReleaseNote
{
get
{
return Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None ? Instance.releaseNotes[(int)Instance.targetPlatform] : "";
}
set
{
if (Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None)
{
Instance.releaseNotes[(int)Instance.targetPlatform] = value;
}
}
}
public static string ReleaseChannel
{
get
{
return Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None ? Instance.releaseChannels[(int)Instance.targetPlatform] : "";
}
set
{
if (Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None)
{
Instance.releaseChannels[(int)Instance.targetPlatform] = value;
}
}
}
public static string ApkBuildPath
{
get
{
return Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None ? Instance.apkBuildPaths[(int)Instance.targetPlatform] : "";
}
set
{
if (Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None)
{
Instance.apkBuildPaths[(int)Instance.targetPlatform] = value;
}
}
}
public static string ObbFilePath
{
get
{
return Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None ? Instance.obbFilePaths[(int)Instance.targetPlatform] : "";
}
set
{
if (Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None)
{
Instance.obbFilePaths[(int)Instance.targetPlatform] = value;
}
}
}
public static string AssetsDirectory
{
get
{
return Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None ? Instance.assetsDirectorys[(int)Instance.targetPlatform] : "";
}
set
{
if (Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None)
{
Instance.assetsDirectorys[(int)Instance.targetPlatform] = value;
}
}
}
public static string RiftBuildDirectory
{
get { return Instance.riftBuildDiretory; }
set { Instance.riftBuildDiretory = value; }
}
public static string RiftBuildVersion
{
get { return Instance.riftBuildVersion; }
set { Instance.riftBuildVersion = value; }
}
public static string RiftLaunchFile
{
get { return Instance.riftLaunchFile; }
set { Instance.riftLaunchFile = value; }
}
public static string RiftLaunchParams
{
get { return Instance.riftLaunchParams; }
set { Instance.riftLaunchParams = value; }
}
public static string Rift2DLaunchFile
{
get { return Instance.rift2DLaunchFile; }
set { Instance.rift2DLaunchFile = value; }
}
public static string Rift2DLaunchParams
{
get { return Instance.rift2DLaunchParams; }
set { Instance.rift2DLaunchParams = value; }
}
public static bool RiftFirewallException
{
get { return Instance.riftFirewallException; }
set { Instance.riftFirewallException = value; }
}
public static GamepadType RiftGamepadEmulation
{
get { return Instance.riftGamepadEmulation; }
set { Instance.riftGamepadEmulation = value; }
}
public static List<RedistPackage> RiftRedistPackages
{
get { return Instance.riftRedistPackages; }
set { Instance.riftRedistPackages = value; }
}
public static string LanguagePackDirectory
{
get { return Instance.languagePackDirectory; }
set { Instance.languagePackDirectory = value; }
}
public static List<AssetConfig> AssetConfigs
{
get
{
return Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None ? Instance.assetConfigs[(int)Instance.targetPlatform].configList : new List<AssetConfig>();
}
set
{
if (Instance.targetPlatform < OVRPlatformTool.TargetPlatform.None)
{
Instance.assetConfigs[(int)Instance.targetPlatform].configList = value;
}
}
}
public static OVRPlatformTool.TargetPlatform TargetPlatform
{
get { return Instance.targetPlatform; }
set { Instance.targetPlatform = value; }
}
public static bool RunOvrLint
{
get { return Instance.runOvrLint; }
set { Instance.runOvrLint = value; }
}
[SerializeField]
private string[] appIDs = new string[(int)OVRPlatformTool.TargetPlatform.None];
[SerializeField]
private string[] releaseNotes = new string[(int)OVRPlatformTool.TargetPlatform.None];
[SerializeField]
private string[] releaseChannels = new string[(int)OVRPlatformTool.TargetPlatform.None];
[SerializeField]
private string riftBuildDiretory = "";
[SerializeField]
private string riftBuildVersion = "";
[SerializeField]
private string riftLaunchFile = "";
[SerializeField]
private string riftLaunchParams = "";
[SerializeField]
private string rift2DLaunchFile = "";
[SerializeField]
private string rift2DLaunchParams = "";
[SerializeField]
private bool riftFirewallException = false;
[SerializeField]
private GamepadType riftGamepadEmulation = GamepadType.OFF;
[SerializeField]
private List<RedistPackage> riftRedistPackages;
[SerializeField]
private string languagePackDirectory = "";
[SerializeField]
private string[] apkBuildPaths = new string[(int)OVRPlatformTool.TargetPlatform.None];
[SerializeField]
private string[] obbFilePaths = new string[(int)OVRPlatformTool.TargetPlatform.None];
[SerializeField]
private string[] assetsDirectorys = new string[(int)OVRPlatformTool.TargetPlatform.None];
[SerializeField]
private AssetConfigList[] assetConfigs = new AssetConfigList[(int)OVRPlatformTool.TargetPlatform.None];
[SerializeField]
private OVRPlatformTool.TargetPlatform targetPlatform = OVRPlatformTool.TargetPlatform.None;
[SerializeField]
private bool runOvrLint = true;
private static OVRPlatformToolSettings instance;
public static OVRPlatformToolSettings Instance
{
get
{
if (instance == null)
{
instance = Resources.Load<OVRPlatformToolSettings>("OVRPlatformToolSettings");
if (instance == null)
{
instance = ScriptableObject.CreateInstance<OVRPlatformToolSettings>();
string properPath = System.IO.Path.Combine(UnityEngine.Application.dataPath, "Resources");
if (!System.IO.Directory.Exists(properPath))
{
UnityEditor.AssetDatabase.CreateFolder("Assets", "Resources");
}
string fullPath = System.IO.Path.Combine(
System.IO.Path.Combine("Assets", "Resources"),
"OVRPlatformToolSettings.asset"
);
UnityEditor.AssetDatabase.CreateAsset(instance, fullPath);
// Initialize cross platform default values for the new instance of OVRPlatformToolSettings here
if (instance != null)
{
for (int i = 0; i < (int)OVRPlatformTool.TargetPlatform.None; i++)
{
instance.releaseChannels[i] = DEFAULT_RELEASE_CHANNEL;
instance.assetConfigs[i] = new AssetConfigList();
}
instance.riftRedistPackages = new List<RedistPackage>();
}
}
}
return instance;
}
set
{
instance = value;
}
}
}
// Wrapper for asset config list so that it can be serialized properly
[System.Serializable]
public class AssetConfigList
{
public List<AssetConfig> configList;
public AssetConfigList()
{
configList = new List<AssetConfig>();
}
}
[System.Serializable]
public class AssetConfig
{
public enum AssetType
{
DEFAULT,
STORE,
LANGUAGE_PACK,
};
public string name;
public bool required;
public AssetType type;
public string sku;
private bool foldout;
public AssetConfig(string assetName)
{
name = assetName;
}
public bool GetFoldoutState()
{
return foldout;
}
public void SetFoldoutState(bool state)
{
foldout = state;
}
}
[System.Serializable]
public class RedistPackage
{
public bool include = false;
public string name;
public string id;
public RedistPackage(string pkgName, string pkgId)
{
name = pkgName;
id = pkgId;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class UShortKeywordRecommenderTests : KeywordRecommenderTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClass_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalStatement_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalVariableDeclaration_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStackAlloc()
{
VerifyKeyword(
@"class C {
int* foo = stackalloc $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InFixedStatement()
{
VerifyKeyword(
@"fixed ($$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InDelegateReturnType()
{
VerifyKeyword(
@"public delegate $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCastType()
{
VerifyKeyword(AddInsideMethod(
@"var str = (($$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCastType2()
{
VerifyKeyword(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOuterConst()
{
VerifyKeyword(
@"class C {
const $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterInnerConst()
{
VerifyKeyword(AddInsideMethod(
@"const $$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InEmptyStatement()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void EnumBaseTypes()
{
VerifyKeyword(
@"enum E : $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType1()
{
VerifyKeyword(AddInsideMethod(
@"IList<$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType2()
{
VerifyKeyword(AddInsideMethod(
@"IList<int,$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType3()
{
VerifyKeyword(AddInsideMethod(
@"IList<int[],$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType4()
{
VerifyKeyword(AddInsideMethod(
@"IList<IFoo<int?,byte*>,$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInBaseList()
{
VerifyAbsence(
@"class C : $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InGenericType_InBaseList()
{
VerifyKeyword(
@"class C : IList<$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIs()
{
VerifyKeyword(AddInsideMethod(
@"var v = foo is $$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAs()
{
VerifyKeyword(AddInsideMethod(
@"var v = foo as $$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethod()
{
VerifyKeyword(
@"class C {
void Foo() {}
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterField()
{
VerifyKeyword(
@"class C {
int i;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterProperty()
{
VerifyKeyword(
@"class C {
int i { get; }
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAttribute()
{
VerifyKeyword(
@"class C {
[foo]
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideStruct()
{
VerifyKeyword(
@"struct S {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideInterface()
{
VerifyKeyword(
@"interface I {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideClass()
{
VerifyKeyword(
@"class C {
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPartial()
{
VerifyAbsence(@"partial $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterNestedPartial()
{
VerifyAbsence(
@"class C {
partial $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAbstract()
{
VerifyKeyword(
@"class C {
abstract $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedInternal()
{
VerifyKeyword(
@"class C {
internal $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedStaticPublic()
{
VerifyKeyword(
@"class C {
static public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPublicStatic()
{
VerifyKeyword(
@"class C {
public static $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterVirtualPublic()
{
VerifyKeyword(
@"class C {
virtual public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPublic()
{
VerifyKeyword(
@"class C {
public $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedPrivate()
{
VerifyKeyword(
@"class C {
private $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedProtected()
{
VerifyKeyword(
@"class C {
protected $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedSealed()
{
VerifyKeyword(
@"class C {
sealed $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedStatic()
{
VerifyKeyword(
@"class C {
static $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InLocalVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InForVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"for ($$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InForeachVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"foreach ($$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InUsingVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"using ($$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InFromVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"var q = from $$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InJoinVariableDeclaration()
{
VerifyKeyword(AddInsideMethod(
@"var q = from a in b
join $$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodOpenParen()
{
VerifyKeyword(
@"class C {
void Foo($$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodComma()
{
VerifyKeyword(
@"class C {
void Foo(int i, $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodAttribute()
{
VerifyKeyword(
@"class C {
void Foo(int i, [Foo]$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorOpenParen()
{
VerifyKeyword(
@"class C {
public C($$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorComma()
{
VerifyKeyword(
@"class C {
public C(int i, $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterConstructorAttribute()
{
VerifyKeyword(
@"class C {
public C(int i, [Foo]$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateOpenParen()
{
VerifyKeyword(
@"delegate void D($$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateComma()
{
VerifyKeyword(
@"delegate void D(int i, $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateAttribute()
{
VerifyKeyword(
@"delegate void D(int i, [Foo]$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterThis()
{
VerifyKeyword(
@"static class C {
public static void Foo(this $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterRef()
{
VerifyKeyword(
@"class C {
void Foo(ref $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterOut()
{
VerifyKeyword(
@"class C {
void Foo(out $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterLambdaRef()
{
VerifyKeyword(
@"class C {
void Foo() {
System.Func<int, int> f = (ref $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterLambdaOut()
{
VerifyKeyword(
@"class C {
void Foo() {
System.Func<int, int> f = (out $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterParams()
{
VerifyKeyword(
@"class C {
void Foo(params $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InImplicitOperator()
{
VerifyKeyword(
@"class C {
public static implicit operator $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InExplicitOperator()
{
VerifyKeyword(
@"class C {
public static explicit operator $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIndexerBracket()
{
VerifyKeyword(
@"class C {
int this[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterIndexerBracketComma()
{
VerifyKeyword(
@"class C {
int this[int i, $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNewInExpression()
{
VerifyKeyword(AddInsideMethod(
@"new $$"));
}
[WorkItem(538804)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InTypeOf()
{
VerifyKeyword(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InDefault()
{
VerifyKeyword(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InSizeOf()
{
VerifyKeyword(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInObjectInitializerMemberContext()
{
VerifyAbsence(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCrefContext()
{
VerifyKeyword(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCrefContextNotAfterDot()
{
VerifyAbsence(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[WorkItem(18374)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAsync()
{
VerifyKeyword(@"class c { async $$ }");
}
[WorkItem(18374)]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterAsyncAsType()
{
VerifyAbsence(@"class c { async async $$ }");
}
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInCrefTypeParameter()
{
VerifyAbsence(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.11.1: Information about environmental effects and processes. This requires manual cleanup. the environmental record is variable, as is the padding. UNFINISHED
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
[XmlInclude(typeof(EntityType))]
[XmlInclude(typeof(Environment))]
public partial class EnvironmentalProcessPdu : SyntheticEnvironmentFamilyPdu, IEquatable<EnvironmentalProcessPdu>
{
/// <summary>
/// Environmental process ID
/// </summary>
private EntityID _environementalProcessID = new EntityID();
/// <summary>
/// Environment type
/// </summary>
private EntityType _environmentType = new EntityType();
/// <summary>
/// model type
/// </summary>
private byte _modelType;
/// <summary>
/// Environment status
/// </summary>
private byte _environmentStatus;
/// <summary>
/// number of environment records
/// </summary>
private byte _numberOfEnvironmentRecords;
/// <summary>
/// PDU sequence number for the environmentla process if pdu sequencing required
/// </summary>
private ushort _sequenceNumber;
/// <summary>
/// environemt records
/// </summary>
private List<Environment> _environmentRecords = new List<Environment>();
/// <summary>
/// Initializes a new instance of the <see cref="EnvironmentalProcessPdu"/> class.
/// </summary>
public EnvironmentalProcessPdu()
{
PduType = (byte)41;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(EnvironmentalProcessPdu left, EnvironmentalProcessPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(EnvironmentalProcessPdu left, EnvironmentalProcessPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._environementalProcessID.GetMarshalledSize(); // this._environementalProcessID
marshalSize += this._environmentType.GetMarshalledSize(); // this._environmentType
marshalSize += 1; // this._modelType
marshalSize += 1; // this._environmentStatus
marshalSize += 1; // this._numberOfEnvironmentRecords
marshalSize += 2; // this._sequenceNumber
for (int idx = 0; idx < this._environmentRecords.Count; idx++)
{
Environment listElement = (Environment)this._environmentRecords[idx];
marshalSize += listElement.GetMarshalledSize();
}
return marshalSize;
}
/// <summary>
/// Gets or sets the Environmental process ID
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "environementalProcessID")]
public EntityID EnvironementalProcessID
{
get
{
return this._environementalProcessID;
}
set
{
this._environementalProcessID = value;
}
}
/// <summary>
/// Gets or sets the Environment type
/// </summary>
[XmlElement(Type = typeof(EntityType), ElementName = "environmentType")]
public EntityType EnvironmentType
{
get
{
return this._environmentType;
}
set
{
this._environmentType = value;
}
}
/// <summary>
/// Gets or sets the model type
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "modelType")]
public byte ModelType
{
get
{
return this._modelType;
}
set
{
this._modelType = value;
}
}
/// <summary>
/// Gets or sets the Environment status
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "environmentStatus")]
public byte EnvironmentStatus
{
get
{
return this._environmentStatus;
}
set
{
this._environmentStatus = value;
}
}
/// <summary>
/// Gets or sets the number of environment records
/// </summary>
/// <remarks>
/// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose.
/// The getnumberOfEnvironmentRecords method will also be based on the actual list length rather than this value.
/// The method is simply here for completeness and should not be used for any computations.
/// </remarks>
[XmlElement(Type = typeof(byte), ElementName = "numberOfEnvironmentRecords")]
public byte NumberOfEnvironmentRecords
{
get
{
return this._numberOfEnvironmentRecords;
}
set
{
this._numberOfEnvironmentRecords = value;
}
}
/// <summary>
/// Gets or sets the PDU sequence number for the environmentla process if pdu sequencing required
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "sequenceNumber")]
public ushort SequenceNumber
{
get
{
return this._sequenceNumber;
}
set
{
this._sequenceNumber = value;
}
}
/// <summary>
/// Gets the environemt records
/// </summary>
[XmlElement(ElementName = "environmentRecordsList", Type = typeof(List<Environment>))]
public List<Environment> EnvironmentRecords
{
get
{
return this._environmentRecords;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._environementalProcessID.Marshal(dos);
this._environmentType.Marshal(dos);
dos.WriteUnsignedByte((byte)this._modelType);
dos.WriteUnsignedByte((byte)this._environmentStatus);
dos.WriteUnsignedByte((byte)this._environmentRecords.Count);
dos.WriteUnsignedShort((ushort)this._sequenceNumber);
for (int idx = 0; idx < this._environmentRecords.Count; idx++)
{
Environment aEnvironment = (Environment)this._environmentRecords[idx];
aEnvironment.Marshal(dos);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._environementalProcessID.Unmarshal(dis);
this._environmentType.Unmarshal(dis);
this._modelType = dis.ReadUnsignedByte();
this._environmentStatus = dis.ReadUnsignedByte();
this._numberOfEnvironmentRecords = dis.ReadUnsignedByte();
this._sequenceNumber = dis.ReadUnsignedShort();
for (int idx = 0; idx < this.NumberOfEnvironmentRecords; idx++)
{
Environment anX = new Environment();
anX.Unmarshal(dis);
this._environmentRecords.Add(anX);
}
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<EnvironmentalProcessPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<environementalProcessID>");
this._environementalProcessID.Reflection(sb);
sb.AppendLine("</environementalProcessID>");
sb.AppendLine("<environmentType>");
this._environmentType.Reflection(sb);
sb.AppendLine("</environmentType>");
sb.AppendLine("<modelType type=\"byte\">" + this._modelType.ToString(CultureInfo.InvariantCulture) + "</modelType>");
sb.AppendLine("<environmentStatus type=\"byte\">" + this._environmentStatus.ToString(CultureInfo.InvariantCulture) + "</environmentStatus>");
sb.AppendLine("<environmentRecords type=\"byte\">" + this._environmentRecords.Count.ToString(CultureInfo.InvariantCulture) + "</environmentRecords>");
sb.AppendLine("<sequenceNumber type=\"ushort\">" + this._sequenceNumber.ToString(CultureInfo.InvariantCulture) + "</sequenceNumber>");
for (int idx = 0; idx < this._environmentRecords.Count; idx++)
{
sb.AppendLine("<environmentRecords" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"Environment\">");
Environment aEnvironment = (Environment)this._environmentRecords[idx];
aEnvironment.Reflection(sb);
sb.AppendLine("</environmentRecords" + idx.ToString(CultureInfo.InvariantCulture) + ">");
}
sb.AppendLine("</EnvironmentalProcessPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as EnvironmentalProcessPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(EnvironmentalProcessPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._environementalProcessID.Equals(obj._environementalProcessID))
{
ivarsEqual = false;
}
if (!this._environmentType.Equals(obj._environmentType))
{
ivarsEqual = false;
}
if (this._modelType != obj._modelType)
{
ivarsEqual = false;
}
if (this._environmentStatus != obj._environmentStatus)
{
ivarsEqual = false;
}
if (this._numberOfEnvironmentRecords != obj._numberOfEnvironmentRecords)
{
ivarsEqual = false;
}
if (this._sequenceNumber != obj._sequenceNumber)
{
ivarsEqual = false;
}
if (this._environmentRecords.Count != obj._environmentRecords.Count)
{
ivarsEqual = false;
}
if (ivarsEqual)
{
for (int idx = 0; idx < this._environmentRecords.Count; idx++)
{
if (!this._environmentRecords[idx].Equals(obj._environmentRecords[idx]))
{
ivarsEqual = false;
}
}
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._environementalProcessID.GetHashCode();
result = GenerateHash(result) ^ this._environmentType.GetHashCode();
result = GenerateHash(result) ^ this._modelType.GetHashCode();
result = GenerateHash(result) ^ this._environmentStatus.GetHashCode();
result = GenerateHash(result) ^ this._numberOfEnvironmentRecords.GetHashCode();
result = GenerateHash(result) ^ this._sequenceNumber.GetHashCode();
if (this._environmentRecords.Count > 0)
{
for (int idx = 0; idx < this._environmentRecords.Count; idx++)
{
result = GenerateHash(result) ^ this._environmentRecords[idx].GetHashCode();
}
}
return result;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.