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.Globalization;
using System.Reflection;
using Xunit;
namespace System.Tests
{
public partial class ActivatorTests
{
[Fact]
public static void CreateInstance()
{
// Passing null args is equivalent to an empty array of args.
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), null));
Assert.Equal(1, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { }));
Assert.Equal(1, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { 42 }));
Assert.Equal(2, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { "Hello" }));
Assert.Equal(3, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { 5.1, "Hello" }));
Assert.Equal(4, c.I);
Activator.CreateInstance(typeof(StructTypeWithoutReflectionMetadata));
}
[Fact]
public static void CreateInstance_ConstructorWithPrimitive_PerformsPrimitiveWidening()
{
// Primitive widening is allowed by the binder, but not by Dynamic.DelegateInvoke().
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { (short)-2 }));
Assert.Equal(2, c.I);
}
[Fact]
public static void CreateInstance_ConstructorWithParamsParameter()
{
// C# params arguments are honored by Activator.CreateInstance()
Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs() }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs(), "P1" }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs(), "P1", "P2" }));
Assert.Equal(5, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs() }));
Assert.Equal(6, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), "P1" }));
Assert.Equal(6, c.I);
c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), "P1", "P2" }));
Assert.Equal(6, c.I);
}
[Fact]
public void CreateInstance_ValueTypeWithPublicDefaultConstructor_Success()
{
// Activator holds a cache of constructors and the types to which they belong.
// Test caching behaviour by activating multiple times.
Assert.IsType<ValueTypeWithDefaultConstructor>(Activator.CreateInstance(typeof(ValueTypeWithDefaultConstructor)));
Assert.IsType<ValueTypeWithDefaultConstructor>(Activator.CreateInstance(typeof(ValueTypeWithDefaultConstructor), nonPublic: true));
Assert.IsType<ValueTypeWithDefaultConstructor>(Activator.CreateInstance(typeof(ValueTypeWithDefaultConstructor), nonPublic: false));
}
[Fact]
public void CreateInstance_NonPublicTypeWithPrivateDefaultConstructor_Success()
{
// Activator holds a cache of constructors and the types to which they belong.
// Test caching behaviour by activating multiple times.
TypeWithPrivateDefaultConstructor c1 = (TypeWithPrivateDefaultConstructor)Activator.CreateInstance(typeof(TypeWithPrivateDefaultConstructor), nonPublic: true);
Assert.Equal(-1, c1.Property);
TypeWithPrivateDefaultConstructor c2 = (TypeWithPrivateDefaultConstructor)Activator.CreateInstance(typeof(TypeWithPrivateDefaultConstructor), nonPublic: true);
Assert.Equal(-1, c2.Property);
}
[Fact]
public void CreateInstance_PublicOnlyTypeWithPrivateDefaultConstructor_ThrowsMissingMethodException()
{
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(TypeWithPrivateDefaultConstructor)));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(TypeWithPrivateDefaultConstructor), nonPublic: false));
// Put the private default constructor into the cache and make sure we still throw if public only.
Assert.NotNull(Activator.CreateInstance(typeof(TypeWithPrivateDefaultConstructor), nonPublic: true));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(TypeWithPrivateDefaultConstructor)));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(TypeWithPrivateDefaultConstructor), nonPublic: false));
}
[Fact]
public void CreateInstance_NullableType_ReturnsNull()
{
Assert.Null(Activator.CreateInstance(typeof(int?)));
}
[Fact]
public void CreateInstance_NullType_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Activator.CreateInstance((Type)null));
AssertExtensions.Throws<ArgumentNullException>("type", () => Activator.CreateInstance(null, new object[0]));
}
[Fact]
public static void CreateInstance_MultipleMatchingConstructors_ThrowsAmbiguousMatchException()
{
Assert.Throws<AmbiguousMatchException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { null }));
}
#if netcoreapp
[Fact]
public void CreateInstance_NotRuntimeType_ThrowsArgumentException()
{
// This cannot be a [Theory] due to https://github.com/xunit/xunit/issues/1325.
foreach (Type nonRuntimeType in Helpers.NonRuntimeTypes)
{
AssertExtensions.Throws<ArgumentException>("type", () => Activator.CreateInstance(nonRuntimeType));
AssertExtensions.Throws<ArgumentException>("type", () => Activator.CreateInstance(nonRuntimeType, new object[0]));
}
}
#endif // netcoreapp
public static IEnumerable<object[]> CreateInstance_ContainsGenericParameters_TestData()
{
yield return new object[] { typeof(List<>) };
yield return new object[] { typeof(List<>).GetTypeInfo().GenericTypeParameters[0] };
}
[Theory]
[MemberData(nameof(CreateInstance_ContainsGenericParameters_TestData))]
public void CreateInstance_ContainsGenericParameters_ThrowsArgumentException(Type type)
{
AssertExtensions.Throws<ArgumentException>(null, () => Activator.CreateInstance(type));
AssertExtensions.Throws<ArgumentException>(null, () => Activator.CreateInstance(type, new object[0]));
}
public static IEnumerable<object[]> CreateInstance_InvalidType_TestData()
{
yield return new object[] { typeof(void) };
yield return new object[] { typeof(void).MakeArrayType() };
yield return new object[] { Type.GetType("System.ArgIterator") };
// Fails with TypeLoadException in .NET Core as array types of ref structs
// are not supported.
if (!PlatformDetection.IsNetCore)
{
yield return new object[] { Type.GetType("System.ArgIterator").MakeArrayType() };
}
}
[Theory]
[MemberData(nameof(CreateInstance_InvalidType_TestData))]
public void CreateInstance_InvalidType_ThrowsNotSupportedException(Type type)
{
Assert.Throws<NotSupportedException>(() => Activator.CreateInstance(type));
Assert.Throws<NotSupportedException>(() => Activator.CreateInstance(type, new object[0]));
}
[Fact]
public void CreateInstance_DesignatedOptionalParameters_ThrowsMissingMemberException()
{
// C# designated optional parameters are not optional as far as Activator.CreateInstance() is concerned.
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { 5.1 }));
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { 5.1, Type.Missing }));
}
[Fact]
public void CreateInstance_InvalidParamArgs_ThrowsMissingMemberException()
{
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), 5, 6 }));
}
[Fact]
public void CreateInstance_PrimitiveWidening_ThrowsInvalidCastException()
{
// Primitive widening not supported for "params" arguments.
//
// (This is probably an accidental behavior on the desktop as the default binder specifically checks to see if the params arguments are widenable to the
// params array element type and gives it the go-ahead if it is. Unfortunately, the binder then bollixes itself by using Array.Copy() to copy
// the params arguments. Since Array.Copy() doesn't tolerate this sort of type mismatch, it throws an InvalidCastException which bubbles out
// out of Activator.CreateInstance. Accidental or not, we'll inherit that behavior on .NET Native.)
Assert.Throws<InvalidCastException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { new VarIntArgs(), 1, (short)2 }));
}
public static IEnumerable<object[]> CreateInstance_NoDefaultConstructor_TestData()
{
yield return new object[] { typeof(TypeWithoutDefaultCtor) };
yield return new object[] { typeof(int[]) };
yield return new object[] { typeof(int).MakeByRefType() };
yield return new object[] { typeof(int).MakePointerType() };
}
[Theory]
[MemberData(nameof(CreateInstance_NoDefaultConstructor_TestData))]
public void CreateInstance_NoDefaultConstructor_ThrowsMissingMemberException(Type type)
{
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(type));
}
[Theory]
[InlineData(typeof(AbstractTypeWithDefaultCtor))]
[InlineData(typeof(Array))]
public void CreateInstance_AbstractClass_ThrowsMissingMemberException(Type type)
{
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(type));
}
[Theory]
[InlineData(typeof(TypedReference))]
[InlineData(typeof(RuntimeArgumentHandle))]
public void CreateInstance_BoxedByRefType_ThrowsNotSupportedException(Type type)
{
Assert.Throws<NotSupportedException>(() => Activator.CreateInstance(type));
}
[Fact]
public void CreateInstance_Span_ThrowsNotSupportedException()
{
CreateInstance_BoxedByRefType_ThrowsNotSupportedException(typeof(Span<int>));
}
[Fact]
public void CreateInstance_InterfaceType_ThrowsMissingMemberException()
{
Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(IInterfaceType)));
}
public class SubMarshalByRefObject : MarshalByRefObject
{
}
[Fact]
public void CreateInstance_ConstructorThrows_ThrowsTargetInvocationException()
{
// Put the constructor into the cache and make sure we still throw if cached.
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(TypeWithDefaultCtorThatThrows)));
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(TypeWithDefaultCtorThatThrows)));
}
[Fact]
public void CreateInstance_ConstructorThrowsFromCache_ThrowsTargetInvocationException()
{
// Put the constructor into the cache and make sure we still throw if cached.
Assert.IsType<TypeWithDefaultCtorThatThrowsOnSecondCall>(Activator.CreateInstance(typeof(TypeWithDefaultCtorThatThrowsOnSecondCall)));
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(TypeWithDefaultCtorThatThrowsOnSecondCall)));
}
[Theory]
[SkipOnTargetFramework(~TargetFrameworkMonikers.Netcoreapp, "Activation Attributes are not supported in .NET Core.")]
[InlineData(typeof(MarshalByRefObject))]
[InlineData(typeof(SubMarshalByRefObject))]
public void CreateInstance_MarshalByRefObjectNetCore_ThrowsPlatformNotSupportedException(Type type)
{
Assert.Throws<PlatformNotSupportedException>(() => Activator.CreateInstance(type, null, new object[] { 1 } ));
Assert.Throws<PlatformNotSupportedException>(() => Activator.CreateInstance(type, null, new object[] { 1, 2 } ));
}
[Fact]
public static void TestActivatorOnNonActivatableFinalizableTypes()
{
// On runtimes where the generic Activator is implemented with special codegen intrinsics, we might allocate
// an uninitialized instance of the object before we realize there's no default constructor to run.
// Make sure this has no observable side effects.
Assert.ThrowsAny<MissingMemberException>(() => { Activator.CreateInstance<TypeWithPrivateDefaultCtorAndFinalizer>(); });
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.False(TypeWithPrivateDefaultCtorAndFinalizer.WasCreated);
}
private class PrivateType
{
public PrivateType() { }
}
class PrivateTypeWithDefaultCtor
{
private PrivateTypeWithDefaultCtor() { }
}
class PrivateTypeWithoutDefaultCtor
{
private PrivateTypeWithoutDefaultCtor(int x) { }
}
class PrivateTypeWithDefaultCtorThatThrows
{
public PrivateTypeWithDefaultCtorThatThrows() { throw new Exception(); }
}
[Fact]
public static void CreateInstance_Type_Bool()
{
Assert.Equal(typeof(PrivateType), Activator.CreateInstance(typeof(PrivateType), true).GetType());
Assert.Equal(typeof(PrivateType), Activator.CreateInstance(typeof(PrivateType), false).GetType());
Assert.Equal(typeof(PrivateTypeWithDefaultCtor), Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtor), true).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtor), false).GetType());
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtorThatThrows), true).GetType());
Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtorThatThrows), false).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithoutDefaultCtor), true).GetType());
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithoutDefaultCtor), false).GetType());
}
public class Choice1 : Attribute
{
public Choice1()
{
I = 1;
}
public Choice1(int i)
{
I = 2;
}
public Choice1(string s)
{
I = 3;
}
public Choice1(double d, string optionalS = "Hey")
{
I = 4;
}
public Choice1(VarArgs varArgs, params object[] parameters)
{
I = 5;
}
public Choice1(VarStringArgs varArgs, params string[] parameters)
{
I = 6;
}
public Choice1(VarIntArgs varArgs, params int[] parameters)
{
I = 7;
}
public int I;
}
public class VarArgs { }
public class VarStringArgs { }
public class VarIntArgs { }
public struct ValueTypeWithDefaultConstructor
{
}
public class TypeWithPrivateDefaultConstructor
{
public int Property { get; }
private TypeWithPrivateDefaultConstructor()
{
Property = -1;
}
}
public class TypeWithPrivateDefaultCtorAndFinalizer
{
public static bool WasCreated { get; private set; }
private TypeWithPrivateDefaultCtorAndFinalizer() { }
~TypeWithPrivateDefaultCtorAndFinalizer()
{
WasCreated = true;
}
}
private interface IInterfaceType
{
}
public abstract class AbstractTypeWithDefaultCtor
{
public AbstractTypeWithDefaultCtor() { }
}
public struct StructTypeWithoutReflectionMetadata { }
public class TypeWithoutDefaultCtor
{
private TypeWithoutDefaultCtor(int x) { }
}
public class TypeWithDefaultCtorThatThrows
{
public TypeWithDefaultCtorThatThrows() { throw new Exception(); }
}
public class TypeWithDefaultCtorThatThrowsOnSecondCall
{
private static int i;
public TypeWithDefaultCtorThatThrowsOnSecondCall()
{
if (i != 0)
{
throw new Exception();
}
i++;
}
}
class ClassWithPrivateCtor
{
static ClassWithPrivateCtor() { Flag.Reset(100); }
private ClassWithPrivateCtor() { Flag.Increase(200); }
public ClassWithPrivateCtor(int i) { Flag.Increase(300); }
}
class ClassWithPrivateCtor2
{
static ClassWithPrivateCtor2() { Flag.Reset(100); }
private ClassWithPrivateCtor2() { Flag.Increase(200); }
public ClassWithPrivateCtor2(int i) { Flag.Increase(300); }
}
class ClassWithPrivateCtor3
{
static ClassWithPrivateCtor3() { Flag.Reset(100); }
private ClassWithPrivateCtor3() { Flag.Increase(200); }
public ClassWithPrivateCtor3(int i) { Flag.Increase(300); }
}
class HasPublicCtor
{
public int Value = 0;
public HasPublicCtor(int value) => Value = value;
}
class HasPrivateCtor
{
public int Value = 0;
private HasPrivateCtor(int value) => Value = value;
}
public class IsTestedAttribute : Attribute
{
private bool flag;
public IsTestedAttribute(bool flag)
{
this.flag = flag;
}
}
[IsTestedAttribute(false)]
class ClassWithIsTestedAttribute { }
[Serializable]
class ClassWithSerializableAttribute { }
[IsTestedAttribute(false)]
class MBRWithIsTestedAttribute : MarshalByRefObject { }
class Flag
{
public static int cnt = 0;
public static void Reset(int i) { cnt = i; }
public static void Increase(int i) { cnt += i; }
public static bool Equal(int i) { return cnt == i; }
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInvokingStaticConstructorsSupported))]
public static void TestingBindingFlags()
{
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(ClassWithPrivateCtor), BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.CurrentCulture));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(ClassWithPrivateCtor), BindingFlags.Public | BindingFlags.Instance, null, new object[] { 1, 2, 3 }, CultureInfo.CurrentCulture));
Flag.Reset(0); Assert.Equal(0, Flag.cnt);
Activator.CreateInstance(typeof(ClassWithPrivateCtor), BindingFlags.Static | BindingFlags.NonPublic, null, null, CultureInfo.CurrentCulture);
Assert.Equal(300, Flag.cnt);
Activator.CreateInstance(typeof(ClassWithPrivateCtor), BindingFlags.Instance | BindingFlags.NonPublic, null, null, CultureInfo.CurrentCulture);
Assert.Equal(500, Flag.cnt);
Flag.Reset(0); Assert.Equal(0, Flag.cnt);
Activator.CreateInstance(typeof(ClassWithPrivateCtor2), BindingFlags.Instance | BindingFlags.NonPublic, null, null, CultureInfo.CurrentCulture);
Assert.Equal(300, Flag.cnt);
Activator.CreateInstance(typeof(ClassWithPrivateCtor2), BindingFlags.Static | BindingFlags.NonPublic, null, null, CultureInfo.CurrentCulture);
Assert.Equal(500, Flag.cnt);
Flag.Reset(0); Assert.Equal(0, Flag.cnt);
Activator.CreateInstance(typeof(ClassWithPrivateCtor3), BindingFlags.Instance | BindingFlags.Public, null, new object[] { 122 }, CultureInfo.CurrentCulture);
Assert.Equal(400, Flag.cnt);
Activator.CreateInstance(typeof(ClassWithPrivateCtor3), BindingFlags.Static | BindingFlags.NonPublic, null, null, CultureInfo.CurrentCulture);
Assert.Equal(600, Flag.cnt);
Activator.CreateInstance(typeof(ClassWithPrivateCtor3), BindingFlags.Instance | BindingFlags.Public, null, new object[] { 122 }, CultureInfo.CurrentCulture);
Assert.Equal(900, Flag.cnt);
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(ClassWithPrivateCtor), BindingFlags.Public | BindingFlags.Static, null, null, CultureInfo.CurrentCulture));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(ClassWithPrivateCtor), BindingFlags.Public | BindingFlags.Static, null, new object[] { 122 }, CultureInfo.CurrentCulture));
}
[Fact]
public static void TestingBindingFlagsInstanceOnly()
{
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(HasPublicCtor), default(BindingFlags), null, null, null));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(HasPublicCtor), BindingFlags.NonPublic | BindingFlags.Instance, null, null, null));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(HasPublicCtor), BindingFlags.Public | BindingFlags.Static, null, null, null));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(HasPrivateCtor), default(BindingFlags), null, null, null));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(HasPrivateCtor), BindingFlags.Public | BindingFlags.Instance, null, null, null));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(HasPrivateCtor), BindingFlags.NonPublic | BindingFlags.Static, null, null, null));
{
HasPublicCtor a = (HasPublicCtor)Activator.CreateInstance(typeof(HasPublicCtor), BindingFlags.Public | BindingFlags.Instance, null, new object[] { 100 }, null);
Assert.Equal(100, a.Value);
}
{
HasPrivateCtor a = (HasPrivateCtor)Activator.CreateInstance(typeof(HasPrivateCtor), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { 100 }, null);
Assert.Equal(100, a.Value);
}
}
[Fact]
public static void TestingBindingFlags1()
{
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(ClassWithPrivateCtor), BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.CurrentCulture, null));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(ClassWithPrivateCtor), BindingFlags.Public | BindingFlags.Instance, null, new object[] { 1, 2, 3 }, CultureInfo.CurrentCulture, null));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(ClassWithPrivateCtor), BindingFlags.Public | BindingFlags.Static, null, null, CultureInfo.CurrentCulture, null));
Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(ClassWithPrivateCtor), BindingFlags.Public | BindingFlags.Static, null, new object[] { 122 }, CultureInfo.CurrentCulture, null));
}
[Fact]
public static void TestingActivationAttributes()
{
Assert.Throws<PlatformNotSupportedException>(() => Activator.CreateInstance(typeof(ClassWithIsTestedAttribute), null, new object[] { new object() }));
Assert.Throws<PlatformNotSupportedException>(() => Activator.CreateInstance(typeof(ClassWithIsTestedAttribute), null, new object[] { new IsTestedAttribute(true) }));
Assert.Throws<PlatformNotSupportedException>(() => Activator.CreateInstance(typeof(ClassWithSerializableAttribute), null, new object[] { new ClassWithIsTestedAttribute() }));
Assert.Throws<PlatformNotSupportedException>(() => Activator.CreateInstance(typeof(MBRWithIsTestedAttribute), null, new object[] { new IsTestedAttribute(true) }));
Assert.Throws<PlatformNotSupportedException>(() => Activator.CreateInstance(typeof(ClassWithIsTestedAttribute), 0, null, null, CultureInfo.CurrentCulture, new object[] { new IsTestedAttribute(true) }));
Assert.Throws<PlatformNotSupportedException>(() => Activator.CreateInstance(typeof(ClassWithSerializableAttribute), 0, null, null, CultureInfo.CurrentCulture, new object[] { new ClassWithIsTestedAttribute() }));
Assert.Throws<PlatformNotSupportedException>(() => Activator.CreateInstance(typeof(MBRWithIsTestedAttribute), 0, null, null, CultureInfo.CurrentCulture, new object[] { new IsTestedAttribute(true) }));
}
[Fact]
public static void TestingActivationAttributes1()
{
Activator.CreateInstance(typeof(ClassWithIsTestedAttribute), null, null);
Activator.CreateInstance(typeof(ClassWithIsTestedAttribute), null, new object[] { });
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Randomized.Generators;
using System;
using System.Collections.Generic;
namespace Lucene.Net.Index
{
using Lucene.Net.Analysis;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
/*
* 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 DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
[TestFixture]
public class TestMultiFields : LuceneTestCase
{
[Test]
public virtual void TestRandom()
{
int num = AtLeast(2);
for (int iter = 0; iter < num; iter++)
{
if (VERBOSE)
{
Console.WriteLine("TEST: iter=" + iter);
}
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NoMergePolicy.COMPOUND_FILES));
// we can do this because we use NoMergePolicy (and dont merge to "nothing")
w.KeepFullyDeletedSegments = true;
IDictionary<BytesRef, IList<int?>> docs = new Dictionary<BytesRef, IList<int?>>();
HashSet<int?> deleted = new HashSet<int?>();
IList<BytesRef> terms = new List<BytesRef>();
int numDocs = TestUtil.NextInt(Random(), 1, 100 * RANDOM_MULTIPLIER);
Documents.Document doc = new Documents.Document();
Field f = NewStringField("field", "", Field.Store.NO);
doc.Add(f);
Field id = NewStringField("id", "", Field.Store.NO);
doc.Add(id);
bool onlyUniqueTerms = Random().NextBoolean();
if (VERBOSE)
{
Console.WriteLine("TEST: onlyUniqueTerms=" + onlyUniqueTerms + " numDocs=" + numDocs);
}
HashSet<BytesRef> uniqueTerms = new HashSet<BytesRef>();
for (int i = 0; i < numDocs; i++)
{
if (!onlyUniqueTerms && Random().NextBoolean() && terms.Count > 0)
{
// re-use existing term
BytesRef term = terms[Random().Next(terms.Count)];
docs[term].Add(i);
f.StringValue = term.Utf8ToString();
}
else
{
string s = TestUtil.RandomUnicodeString(Random(), 10);
BytesRef term = new BytesRef(s);
if (!docs.ContainsKey(term))
{
docs[term] = new List<int?>();
}
docs[term].Add(i);
terms.Add(term);
uniqueTerms.Add(term);
f.StringValue = s;
}
id.StringValue = "" + i;
w.AddDocument(doc);
if (Random().Next(4) == 1)
{
w.Commit();
}
if (i > 0 && Random().Next(20) == 1)
{
int delID = Random().Next(i);
deleted.Add(delID);
w.DeleteDocuments(new Term("id", "" + delID));
if (VERBOSE)
{
Console.WriteLine("TEST: delete " + delID);
}
}
}
if (VERBOSE)
{
List<BytesRef> termsList = new List<BytesRef>(uniqueTerms);
termsList.Sort(BytesRef.UTF8SortedAsUTF16Comparer);
Console.WriteLine("TEST: terms in UTF16 order:");
foreach (BytesRef b in termsList)
{
Console.WriteLine(" " + UnicodeUtil.ToHexString(b.Utf8ToString()) + " " + b);
foreach (int docID in docs[b])
{
if (deleted.Contains(docID))
{
Console.WriteLine(" " + docID + " (deleted)");
}
else
{
Console.WriteLine(" " + docID);
}
}
}
}
IndexReader reader = w.Reader;
w.Dispose();
if (VERBOSE)
{
Console.WriteLine("TEST: reader=" + reader);
}
Bits liveDocs = MultiFields.GetLiveDocs(reader);
foreach (int delDoc in deleted)
{
Assert.IsFalse(liveDocs.Get(delDoc));
}
for (int i = 0; i < 100; i++)
{
BytesRef term = terms[Random().Next(terms.Count)];
if (VERBOSE)
{
Console.WriteLine("TEST: seek term=" + UnicodeUtil.ToHexString(term.Utf8ToString()) + " " + term);
}
DocsEnum docsEnum = TestUtil.Docs(Random(), reader, "field", term, liveDocs, null, DocsEnum.FLAG_NONE);
Assert.IsNotNull(docsEnum);
foreach (int docID in docs[term])
{
if (!deleted.Contains(docID))
{
Assert.AreEqual(docID, docsEnum.NextDoc());
}
}
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, docsEnum.NextDoc());
}
reader.Dispose();
dir.Dispose();
}
}
/*
private void verify(IndexReader r, String term, List<Integer> expected) throws Exception {
DocsEnum docs = TestUtil.Docs(random, r,
"field",
new BytesRef(term),
MultiFields.GetLiveDocs(r),
null,
false);
for(int docID : expected) {
Assert.AreEqual(docID, docs.NextDoc());
}
Assert.AreEqual(docs.NO_MORE_DOCS, docs.NextDoc());
}
*/
[Test]
public virtual void TestSeparateEnums()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Documents.Document d = new Documents.Document();
d.Add(NewStringField("f", "j", Field.Store.NO));
w.AddDocument(d);
w.Commit();
w.AddDocument(d);
IndexReader r = w.Reader;
w.Dispose();
DocsEnum d1 = TestUtil.Docs(Random(), r, "f", new BytesRef("j"), null, null, DocsEnum.FLAG_NONE);
DocsEnum d2 = TestUtil.Docs(Random(), r, "f", new BytesRef("j"), null, null, DocsEnum.FLAG_NONE);
Assert.AreEqual(0, d1.NextDoc());
Assert.AreEqual(0, d2.NextDoc());
r.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestTermDocsEnum()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Documents.Document d = new Documents.Document();
d.Add(NewStringField("f", "j", Field.Store.NO));
w.AddDocument(d);
w.Commit();
w.AddDocument(d);
IndexReader r = w.Reader;
w.Dispose();
DocsEnum de = MultiFields.GetTermDocsEnum(r, null, "f", new BytesRef("j"));
Assert.AreEqual(0, de.NextDoc());
Assert.AreEqual(1, de.NextDoc());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, de.NextDoc());
r.Dispose();
dir.Dispose();
}
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Annotations;
using NodaTime.TimeZones.Cldr;
using NodaTime.TimeZones.IO;
using NodaTime.Utility;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
namespace NodaTime.TimeZones
{
/// <summary>
/// Provides an implementation of <see cref="IDateTimeZoneSource" /> that loads data originating from the
/// <a href="http://www.iana.org/time-zones">tz database</a> (also known as the IANA Time Zone database, or zoneinfo
/// or Olson database).
/// </summary>
/// <remarks>
/// All calls to <see cref="ForId"/> for fixed-offset IDs advertised by the source (i.e. "UTC" and "UTC+/-Offset")
/// will return zones equal to those returned by <see cref="DateTimeZone.ForOffset"/>.
/// </remarks>
/// <threadsafety>This type is immutable reference type. See the thread safety section of the user guide for more information.</threadsafety>
[Immutable]
public sealed class TzdbDateTimeZoneSource : IDateTimeZoneSource
{
/// <summary>
/// Gets the <see cref="TzdbDateTimeZoneSource"/> initialised from resources within the NodaTime assembly.
/// </summary>
/// <value>The source initialised from resources within the NodaTime assembly.</value>
public static TzdbDateTimeZoneSource Default => DefaultHolder.builtin;
// Class to enable lazy initialization of the default instance.
private static class DefaultHolder
{
static DefaultHolder() { }
internal static readonly TzdbDateTimeZoneSource builtin = new TzdbDateTimeZoneSource(LoadDefaultDataSource());
private static TzdbStreamData LoadDefaultDataSource()
{
var assembly = typeof(DefaultHolder).GetTypeInfo().Assembly;
using (Stream stream = assembly.GetManifestResourceStream("NodaTime.TimeZones.Tzdb.nzd"))
{
return TzdbStreamData.FromStream(stream);
}
}
}
/// <summary>
/// Original source data - we delegate to this to create actual DateTimeZone instances,
/// and for windows mappings.
/// </summary>
private readonly TzdbStreamData source;
/// <summary>
/// Composite version ID including TZDB and Windows mapping version strings.
/// </summary>
private readonly string version;
/// <summary>
/// Gets a lookup from canonical time zone ID (e.g. "Europe/London") to a group of aliases for that time zone
/// (e.g. {"Europe/Belfast", "Europe/Guernsey", "Europe/Jersey", "Europe/Isle_of_Man", "GB", "GB-Eire"}).
/// </summary>
/// <remarks>
/// The group of values for a key never contains the canonical ID, only aliases. Any time zone
/// ID which is itself an alias or has no aliases linking to it will not be present in the lookup.
/// The aliases within a group are returned in alphabetical (ordinal) order.
/// </remarks>
/// <value>A lookup from canonical ID to the aliases of that ID.</value>
public ILookup<string, string> Aliases { get; }
/// <summary>
/// Returns a read-only map from time zone ID to the canonical ID. For example, the key "Europe/Jersey"
/// would be associated with the value "Europe/London".
/// </summary>
/// <remarks>
/// <para>This map contains an entry for every ID returned by <see cref="GetIds"/>, where
/// canonical IDs map to themselves.</para>
/// <para>The returned map is read-only; any attempts to call a mutating method will throw
/// <see cref="NotSupportedException" />.</para>
/// </remarks>
/// <value>A map from time zone ID to the canonical ID.</value>
public IDictionary<string, string> CanonicalIdMap => source.TzdbIdMap;
/// <summary>
/// Gets a read-only list of zone locations known to this source, or null if the original source data
/// does not include zone locations.
/// </summary>
/// <remarks>
/// Every zone location's time zone ID is guaranteed to be valid within this source (assuming the source
/// has been validated).
/// </remarks>
/// <value>A read-only list of zone locations known to this source.</value>
public IList<TzdbZoneLocation>? ZoneLocations => source.ZoneLocations;
/// <summary>
/// Gets a read-only list of "zone 1970" locations known to this source, or null if the original source data
/// does not include zone locations.
/// </summary>
/// <remarks>
/// <p>
/// This location data differs from <see cref="ZoneLocations"/> in two important respects:
/// <ul>
/// <li>Where multiple similar zones exist but only differ in transitions before 1970,
/// this location data chooses one zone to be the canonical "post 1970" zone.
/// </li>
/// <li>
/// This location data can represent multiple ISO-3166 country codes in a single entry. For example,
/// the entry corresponding to "Europe/London" includes country codes GB, GG, JE and IM (Britain,
/// Guernsey, Jersey and the Isle of Man, respectively).
/// </li>
/// </ul>
/// </p>
/// <p>
/// Every zone location's time zone ID is guaranteed to be valid within this source (assuming the source
/// has been validated).
/// </p>
/// </remarks>
/// <value>A read-only list of zone locations known to this source.</value>
public IList<TzdbZone1970Location>? Zone1970Locations => source.Zone1970Locations;
/// <inheritdoc />
/// <remarks>
/// <para>
/// This source returns a string such as "TZDB: 2013b (mapping: 8274)" corresponding to the versions of the tz
/// database and the CLDR Windows zones mapping file.
/// </para>
/// <para>
/// Note that there is no need to parse this string to extract any of the above information, as it is available
/// directly from the <see cref="TzdbVersion"/> and <see cref="WindowsZones.Version"/> properties.
/// </para>
/// </remarks>
public string VersionId => "TZDB: " + version;
/// <summary>
/// Creates an instance from a stream in the custom Noda Time format. The stream must be readable.
/// </summary>
/// <remarks>
/// <para>
/// The stream is not closed by this method, but will be read from
/// without rewinding. A successful call will read the stream to the end.
/// </para>
/// <para>
/// See the user guide for instructions on how to generate an updated time zone database file from a copy of the
/// (textual) tz database.
/// </para>
/// </remarks>
/// <param name="stream">The stream containing time zone data</param>
/// <returns>A <c>TzdbDateTimeZoneSource</c> providing information from the given stream.</returns>
/// <exception cref="InvalidNodaDataException">The stream contains invalid time zone data, or data which cannot
/// be read by this version of Noda Time.</exception>
/// <exception cref="IOException">Reading from the stream failed.</exception>
/// <exception cref="InvalidOperationException">The supplied stream doesn't support reading.</exception>
public static TzdbDateTimeZoneSource FromStream(Stream stream)
{
Preconditions.CheckNotNull(stream, nameof(stream));
return new TzdbDateTimeZoneSource(TzdbStreamData.FromStream(stream));
}
[VisibleForTesting]
internal TzdbDateTimeZoneSource(TzdbStreamData source)
{
Preconditions.CheckNotNull(source, nameof(source));
this.source = source;
Aliases = CanonicalIdMap
.Where(pair => pair.Key != pair.Value)
.OrderBy(pair => pair.Key, StringComparer.Ordinal)
.ToLookup(pair => pair.Value, pair => pair.Key);
version = source.TzdbVersion + " (mapping: " + source.WindowsMapping.Version + ")";
}
/// <inheritdoc />
public DateTimeZone ForId(string id)
{
if (!CanonicalIdMap.TryGetValue(Preconditions.CheckNotNull(id, nameof(id)), out string canonicalId))
{
throw new ArgumentException("Time zone with ID " + id + " not found in source " + version, nameof(id));
}
return source.CreateZone(id, canonicalId);
}
/// <inheritdoc />
[DebuggerStepThrough]
public IEnumerable<string> GetIds() => CanonicalIdMap.Keys;
/// <inheritdoc />
public string? GetSystemDefaultId() => MapTimeZoneInfoId(TimeZoneInfoInterceptor.Local);
[VisibleForTesting]
internal string? MapTimeZoneInfoId(TimeZoneInfo? timeZone)
{
// Unusual, but can happen in some Mono installations.
if (timeZone is null)
{
return null;
}
string id = timeZone.Id;
// First see if it's a Windows time zone ID.
if (source.WindowsMapping.PrimaryMapping.TryGetValue(id, out string result))
{
return result;
}
// Next see if it's already a TZDB ID (e.g. .NET Core running on Linux or Mac).
if (CanonicalIdMap.Keys.Contains(id))
{
return id;
}
// Maybe it's a Windows zone we don't have a mapping for, or we're on a Mono system
// where TimeZoneInfo.Local.Id returns "Local" but can actually do the mappings.
return GuessZoneIdByTransitions(timeZone);
}
private readonly ConcurrentDictionary<string, string?> guesses = new ConcurrentDictionary<string, string?>();
// Cache around GuessZoneIdByTransitionsUncached
private string? GuessZoneIdByTransitions(TimeZoneInfo zone)
{
// FIXME: Stop using StandardName! (We have Id now...)
return guesses.GetOrAdd(zone.StandardName, _ =>
{
// Build the list of candidates here instead of within the method, so that
// tests can pass in the same list on each iteration. We order the time zones
// by ID so that if there are multiple zones with the same score, we'll always
// pick the same one across multiple runs/platforms.
var candidates = CanonicalIdMap.Values.Select(ForId).OrderBy(dtz => dtz.Id).ToList();
return GuessZoneIdByTransitionsUncached(zone, candidates);
});
}
/// <summary>
/// In cases where we can't get a zone mapping directly, we try to work out a good fit
/// by checking the transitions within the next few years.
/// This can happen if the Windows data isn't up-to-date, or if we're on a system where
/// TimeZoneInfo.Local.Id just returns "local", or if TimeZoneInfo.Local is a custom time
/// zone for some reason. We return null if we don't get a 70% hit rate.
/// We look at all transitions in all canonical IDs for the next 5 years.
/// Heuristically, this seems to be good enough to get the right results in most cases.
/// This method used to only be called in the PCL build in 1.x, but it seems reasonable enough to
/// call it if we can't get an exact match anyway.
/// </summary>
/// <param name="zone">Zone to resolve in a best-effort fashion.</param>
/// <param name="candidates">All the Noda Time zones to consider - normally a list
/// obtained from this source.</param>
internal string? GuessZoneIdByTransitionsUncached(TimeZoneInfo zone, List<DateTimeZone> candidates)
{
// See https://github.com/nodatime/nodatime/issues/686 for performance observations.
// Very rare use of the system clock! Windows time zone updates sometimes sacrifice past
// accuracy for future accuracy, so let's use the current year's transitions.
int thisYear = SystemClock.Instance.GetCurrentInstant().InUtc().Year;
Instant startOfThisYear = Instant.FromUtc(thisYear, 1, 1, 0, 0);
Instant startOfNextYear = Instant.FromUtc(thisYear + 5, 1, 1, 0, 0);
var instants = candidates.SelectMany(z => z.GetZoneIntervals(startOfThisYear, startOfNextYear))
.Select(zi => Instant.Max(zi.RawStart, startOfThisYear)) // Clamp to start of interval
.Distinct()
.ToList();
var bclOffsets = instants.Select(instant => Offset.FromTimeSpan(zone.GetUtcOffset(instant.ToDateTimeUtc()))).ToList();
// For a zone to be mappable, at most 30% of the checks must fail
// - so if we get to that number (or whatever our "best" so far is)
// we know we can stop for any particular zone.
int lowestFailureScore = (instants.Count * 30) / 100;
DateTimeZone? bestZone = null;
foreach (var candidate in candidates)
{
int failureScore = 0;
for (int i = 0; i < instants.Count; i++)
{
if (candidate.GetUtcOffset(instants[i]) != bclOffsets[i])
{
failureScore++;
if (failureScore == lowestFailureScore)
{
break;
}
}
}
if (failureScore < lowestFailureScore)
{
lowestFailureScore = failureScore;
bestZone = candidate;
}
}
return bestZone?.Id;
}
/// <summary>
/// Gets just the TZDB version (e.g. "2013a") of the source data.
/// </summary>
/// <value>The TZDB version (e.g. "2013a") of the source data.</value>
public string TzdbVersion => source.TzdbVersion;
/// <summary>
/// Gets the Windows time zone mapping information provided in the CLDR
/// supplemental "windowsZones.xml" file.
/// </summary>
/// <value>The Windows time zone mapping information provided in the CLDR
/// supplemental "windowsZones.xml" file.</value>
public WindowsZones WindowsMapping => source.WindowsMapping;
/// <summary>
/// Validates that the data within this source is consistent with itself.
/// </summary>
/// <remarks>
/// Source data is not validated automatically when it's loaded, but any source
/// loaded from data produced by <c>NodaTime.TzdbCompiler</c> (including the data shipped with Noda Time)
/// will already have been validated via this method when it was originally produced. This method should
/// only normally be called explicitly if you have data from a source you're unsure of.
/// </remarks>
/// <exception cref="InvalidNodaDataException">The source data is invalid. The source may not function
/// correctly.</exception>
public void Validate()
{
// Check that each entry has a canonical value. (Every mapping x to y
// should be such that y maps to itself.)
foreach (var entry in CanonicalIdMap)
{
if (!CanonicalIdMap.TryGetValue(entry.Value, out string canonical))
{
throw new InvalidNodaDataException(
"Mapping for entry {entry.Key} ({entry.Value}) is missing");
}
if (entry.Value != canonical)
{
throw new InvalidNodaDataException(
"Mapping for entry {entry.Key} ({entry.Value}) is not canonical ({entry.Value} maps to {canonical}");
}
}
// Check that every Windows mapping has a primary territory
foreach (var mapZone in WindowsMapping.MapZones)
{
// Simplest way of checking is to find the primary mapping...
if (!source.WindowsMapping.PrimaryMapping.ContainsKey(mapZone.WindowsId))
{
throw new InvalidNodaDataException(
$"Windows mapping for standard ID {mapZone.WindowsId} has no primary territory");
}
}
// Check that each Windows mapping uses TZDB IDs that are known to this source.
foreach (var mapZone in WindowsMapping.MapZones)
{
foreach (var id in mapZone.TzdbIds)
{
if (!CanonicalIdMap.ContainsKey(id))
{
throw new InvalidNodaDataException(
$"Windows mapping uses TZDB ID {id} which is missing");
}
}
}
// Check that each zone location has a valid zone ID
if (ZoneLocations != null)
{
foreach (var location in ZoneLocations)
{
if (!CanonicalIdMap.ContainsKey(location.ZoneId))
{
throw new InvalidNodaDataException(
$"Zone location {location.CountryName} uses zone ID {location.ZoneId} which is missing");
}
}
}
if (Zone1970Locations != null)
{
foreach (var location in Zone1970Locations)
{
if (!CanonicalIdMap.ContainsKey(location.ZoneId))
{
throw new InvalidNodaDataException(
$"Zone 1970 location {location.Countries[0].Name} uses zone ID {location.ZoneId} which is missing");
}
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Pooling;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets.Catch.Judgements;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.Objects.Drawables;
using osu.Game.Rulesets.Catch.Skinning;
using osu.Game.Rulesets.Judgements;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Catch.UI
{
[Cached]
public class Catcher : SkinReloadableDrawable
{
/// <summary>
/// The size of the catcher at 1x scale.
/// </summary>
public const float BASE_SIZE = 106.75f;
/// <summary>
/// The width of the catcher which can receive fruit. Equivalent to "catchMargin" in osu-stable.
/// </summary>
public const float ALLOWED_CATCH_RANGE = 0.8f;
/// <summary>
/// The default colour used to tint hyper-dash fruit, along with the moving catcher, its trail and after-image during a hyper-dash.
/// </summary>
public static readonly Color4 DEFAULT_HYPER_DASH_COLOUR = Color4.Red;
/// <summary>
/// The duration between transitioning to hyper-dash state.
/// </summary>
public const double HYPER_DASH_TRANSITION_DURATION = 180;
/// <summary>
/// Whether we are hyper-dashing or not.
/// </summary>
public bool HyperDashing => hyperDashModifier != 1;
/// <summary>
/// Whether <see cref="DrawablePalpableCatchHitObject"/> fruit should appear on the plate.
/// </summary>
public bool CatchFruitOnPlate { get; set; } = true;
/// <summary>
/// The relative space to cover in 1 millisecond. based on 1 game pixel per millisecond as in osu-stable.
/// </summary>
public const double BASE_SPEED = 1.0;
/// <summary>
/// The current speed of the catcher.
/// </summary>
public double Speed => (Dashing ? 1 : 0.5) * BASE_SPEED * hyperDashModifier;
/// <summary>
/// The amount by which caught fruit should be scaled down to fit on the plate.
/// </summary>
private const float caught_fruit_scale_adjust = 0.5f;
/// <summary>
/// Contains caught objects on the plate.
/// </summary>
private readonly Container<CaughtObject> caughtObjectContainer;
/// <summary>
/// Contains objects dropped from the plate.
/// </summary>
private readonly DroppedObjectContainer droppedObjectTarget;
public CatcherAnimationState CurrentState
{
get => body.AnimationState.Value;
private set => body.AnimationState.Value = value;
}
/// <summary>
/// Whether the catcher is currently dashing.
/// </summary>
public bool Dashing { get; set; }
/// <summary>
/// The currently facing direction.
/// </summary>
public Direction VisualDirection { get; set; } = Direction.Right;
public Vector2 BodyScale => Scale * body.Scale;
/// <summary>
/// Whether the contents of the catcher plate should be visually flipped when the catcher direction is changed.
/// </summary>
private bool flipCatcherPlate;
/// <summary>
/// Width of the area that can be used to attempt catches during gameplay.
/// </summary>
public readonly float CatchWidth;
private readonly SkinnableCatcher body;
private Color4 hyperDashColour = DEFAULT_HYPER_DASH_COLOUR;
private double hyperDashModifier = 1;
private int hyperDashDirection;
private float hyperDashTargetPosition;
private Bindable<bool> hitLighting;
private readonly HitExplosionContainer hitExplosionContainer;
private readonly DrawablePool<CaughtFruit> caughtFruitPool;
private readonly DrawablePool<CaughtBanana> caughtBananaPool;
private readonly DrawablePool<CaughtDroplet> caughtDropletPool;
public Catcher([NotNull] DroppedObjectContainer droppedObjectTarget, BeatmapDifficulty difficulty = null)
{
this.droppedObjectTarget = droppedObjectTarget;
Origin = Anchor.TopCentre;
Size = new Vector2(BASE_SIZE);
if (difficulty != null)
Scale = calculateScale(difficulty);
CatchWidth = CalculateCatchWidth(Scale);
InternalChildren = new Drawable[]
{
caughtFruitPool = new DrawablePool<CaughtFruit>(50),
caughtBananaPool = new DrawablePool<CaughtBanana>(100),
// less capacity is needed compared to fruit because droplet is not stacked
caughtDropletPool = new DrawablePool<CaughtDroplet>(25),
caughtObjectContainer = new Container<CaughtObject>
{
Anchor = Anchor.TopCentre,
Origin = Anchor.BottomCentre,
// offset fruit vertically to better place "above" the plate.
Y = -5
},
body = new SkinnableCatcher(),
hitExplosionContainer = new HitExplosionContainer
{
Anchor = Anchor.TopCentre,
Origin = Anchor.BottomCentre,
},
};
}
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
hitLighting = config.GetBindable<bool>(OsuSetting.HitLighting);
}
/// <summary>
/// Creates proxied content to be displayed beneath hitobjects.
/// </summary>
public Drawable CreateProxiedContent() => caughtObjectContainer.CreateProxy();
/// <summary>
/// Calculates the scale of the catcher based off the provided beatmap difficulty.
/// </summary>
private static Vector2 calculateScale(BeatmapDifficulty difficulty) => new Vector2(1.0f - 0.7f * (difficulty.CircleSize - 5) / 5);
/// <summary>
/// Calculates the width of the area used for attempting catches in gameplay.
/// </summary>
/// <param name="scale">The scale of the catcher.</param>
public static float CalculateCatchWidth(Vector2 scale) => BASE_SIZE * Math.Abs(scale.X) * ALLOWED_CATCH_RANGE;
/// <summary>
/// Calculates the width of the area used for attempting catches in gameplay.
/// </summary>
/// <param name="difficulty">The beatmap difficulty.</param>
public static float CalculateCatchWidth(BeatmapDifficulty difficulty) => CalculateCatchWidth(calculateScale(difficulty));
/// <summary>
/// Determine if this catcher can catch a <see cref="CatchHitObject"/> in the current position.
/// </summary>
public bool CanCatch(CatchHitObject hitObject)
{
if (!(hitObject is PalpableCatchHitObject fruit))
return false;
float halfCatchWidth = CatchWidth * 0.5f;
return fruit.EffectiveX >= X - halfCatchWidth &&
fruit.EffectiveX <= X + halfCatchWidth;
}
public void OnNewResult(DrawableCatchHitObject drawableObject, JudgementResult result)
{
var catchResult = (CatchJudgementResult)result;
catchResult.CatcherAnimationState = CurrentState;
catchResult.CatcherHyperDash = HyperDashing;
if (!(drawableObject is DrawablePalpableCatchHitObject palpableObject)) return;
var hitObject = palpableObject.HitObject;
if (result.IsHit)
{
var positionInStack = computePositionInStack(new Vector2(palpableObject.X - X, 0), palpableObject.DisplaySize.X);
if (CatchFruitOnPlate)
placeCaughtObject(palpableObject, positionInStack);
if (hitLighting.Value)
addLighting(result, drawableObject.AccentColour.Value, positionInStack.X);
}
// droplet doesn't affect the catcher state
if (hitObject is TinyDroplet) return;
if (result.IsHit && hitObject.HyperDash)
{
var target = hitObject.HyperDashTarget;
var timeDifference = target.StartTime - hitObject.StartTime;
double positionDifference = target.EffectiveX - X;
var velocity = positionDifference / Math.Max(1.0, timeDifference - 1000.0 / 60.0);
SetHyperDashState(Math.Abs(velocity), target.EffectiveX);
}
else
SetHyperDashState();
if (result.IsHit)
CurrentState = hitObject.Kiai ? CatcherAnimationState.Kiai : CatcherAnimationState.Idle;
else if (!(hitObject is Banana))
CurrentState = CatcherAnimationState.Fail;
}
public void OnRevertResult(DrawableCatchHitObject drawableObject, JudgementResult result)
{
var catchResult = (CatchJudgementResult)result;
CurrentState = catchResult.CatcherAnimationState;
if (HyperDashing != catchResult.CatcherHyperDash)
{
if (catchResult.CatcherHyperDash)
SetHyperDashState(2);
else
SetHyperDashState();
}
caughtObjectContainer.RemoveAll(d => d.HitObject == drawableObject.HitObject);
droppedObjectTarget.RemoveAll(d => d.HitObject == drawableObject.HitObject);
}
/// <summary>
/// Set hyper-dash state.
/// </summary>
/// <param name="modifier">The speed multiplier. If this is less or equals to 1, this catcher will be non-hyper-dashing state.</param>
/// <param name="targetPosition">When this catcher crosses this position, this catcher ends hyper-dashing.</param>
public void SetHyperDashState(double modifier = 1, float targetPosition = -1)
{
var wasHyperDashing = HyperDashing;
if (modifier <= 1 || X == targetPosition)
{
hyperDashModifier = 1;
hyperDashDirection = 0;
if (wasHyperDashing)
runHyperDashStateTransition(false);
}
else
{
hyperDashModifier = modifier;
hyperDashDirection = Math.Sign(targetPosition - X);
hyperDashTargetPosition = targetPosition;
if (!wasHyperDashing)
runHyperDashStateTransition(true);
}
}
/// <summary>
/// Drop any fruit off the plate.
/// </summary>
public void Drop() => clearPlate(DroppedObjectAnimation.Drop);
/// <summary>
/// Explode all fruit off the plate.
/// </summary>
public void Explode() => clearPlate(DroppedObjectAnimation.Explode);
private void runHyperDashStateTransition(bool hyperDashing)
{
this.FadeColour(hyperDashing ? hyperDashColour : Color4.White, HYPER_DASH_TRANSITION_DURATION, Easing.OutQuint);
}
protected override void SkinChanged(ISkinSource skin)
{
base.SkinChanged(skin);
hyperDashColour =
skin.GetConfig<CatchSkinColour, Color4>(CatchSkinColour.HyperDash)?.Value ??
DEFAULT_HYPER_DASH_COLOUR;
flipCatcherPlate = skin.GetConfig<CatchSkinConfiguration, bool>(CatchSkinConfiguration.FlipCatcherPlate)?.Value ?? true;
runHyperDashStateTransition(HyperDashing);
}
protected override void Update()
{
base.Update();
var scaleFromDirection = new Vector2((int)VisualDirection, 1);
body.Scale = scaleFromDirection;
caughtObjectContainer.Scale = hitExplosionContainer.Scale = flipCatcherPlate ? scaleFromDirection : Vector2.One;
// Correct overshooting.
if ((hyperDashDirection > 0 && hyperDashTargetPosition < X) ||
(hyperDashDirection < 0 && hyperDashTargetPosition > X))
{
X = hyperDashTargetPosition;
SetHyperDashState();
}
}
private void placeCaughtObject(DrawablePalpableCatchHitObject drawableObject, Vector2 position)
{
var caughtObject = getCaughtObject(drawableObject.HitObject);
if (caughtObject == null) return;
caughtObject.CopyStateFrom(drawableObject);
caughtObject.Anchor = Anchor.TopCentre;
caughtObject.Position = position;
caughtObject.Scale *= caught_fruit_scale_adjust;
caughtObjectContainer.Add(caughtObject);
if (!caughtObject.StaysOnPlate)
removeFromPlate(caughtObject, DroppedObjectAnimation.Explode);
}
private Vector2 computePositionInStack(Vector2 position, float displayRadius)
{
// this is taken from osu-stable (lenience should be 10 * 10 at standard scale).
const float lenience_adjust = 10 / CatchHitObject.OBJECT_RADIUS;
float adjustedRadius = displayRadius * lenience_adjust;
float checkDistance = MathF.Pow(adjustedRadius, 2);
while (caughtObjectContainer.Any(f => Vector2Extensions.DistanceSquared(f.Position, position) < checkDistance))
{
position.X += RNG.NextSingle(-adjustedRadius, adjustedRadius);
position.Y -= RNG.NextSingle(0, 5);
}
return position;
}
private void addLighting(JudgementResult judgementResult, Color4 colour, float x) =>
hitExplosionContainer.Add(new HitExplosionEntry(Time.Current, judgementResult, colour, x));
private CaughtObject getCaughtObject(PalpableCatchHitObject source)
{
switch (source)
{
case Fruit _:
return caughtFruitPool.Get();
case Banana _:
return caughtBananaPool.Get();
case Droplet _:
return caughtDropletPool.Get();
default:
return null;
}
}
private CaughtObject getDroppedObject(CaughtObject caughtObject)
{
var droppedObject = getCaughtObject(caughtObject.HitObject);
droppedObject.CopyStateFrom(caughtObject);
droppedObject.Anchor = Anchor.TopLeft;
droppedObject.Position = caughtObjectContainer.ToSpaceOfOtherDrawable(caughtObject.DrawPosition, droppedObjectTarget);
return droppedObject;
}
private void clearPlate(DroppedObjectAnimation animation)
{
var droppedObjects = caughtObjectContainer.Children.Select(getDroppedObject).ToArray();
caughtObjectContainer.Clear(false);
droppedObjectTarget.AddRange(droppedObjects);
foreach (var droppedObject in droppedObjects)
applyDropAnimation(droppedObject, animation);
}
private void removeFromPlate(CaughtObject caughtObject, DroppedObjectAnimation animation)
{
var droppedObject = getDroppedObject(caughtObject);
caughtObjectContainer.Remove(caughtObject);
droppedObjectTarget.Add(droppedObject);
applyDropAnimation(droppedObject, animation);
}
private void applyDropAnimation(Drawable d, DroppedObjectAnimation animation)
{
switch (animation)
{
case DroppedObjectAnimation.Drop:
d.MoveToY(d.Y + 75, 750, Easing.InSine);
d.FadeOut(750);
break;
case DroppedObjectAnimation.Explode:
float originalX = droppedObjectTarget.ToSpaceOfOtherDrawable(d.DrawPosition, caughtObjectContainer).X * caughtObjectContainer.Scale.X;
d.MoveToY(d.Y - 50, 250, Easing.OutSine).Then().MoveToY(d.Y + 50, 500, Easing.InSine);
d.MoveToX(d.X + originalX * 6, 1000);
d.FadeOut(750);
break;
}
d.Expire();
}
private enum DroppedObjectAnimation
{
Drop,
Explode
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics.Application;
using System.Text;
using System.Threading.Tasks;
namespace System.ServiceModel.Dispatcher
{
public class ChannelDispatcher : ChannelDispatcherBase
{
private SynchronizedCollection<IChannelInitializer> _channelInitializers;
private CommunicationObjectManager<IChannel> _channels;
private EndpointDispatcherCollection _endpointDispatchers;
private Collection<IErrorHandler> _errorHandlers;
private EndpointDispatcherTable _filterTable;
private bool _isTransactedReceive;
private bool _receiveContextEnabled;
private readonly IChannelListener _listener = null;
private ListenerHandler _listenerHandler;
private int _maxTransactedBatchSize;
private MessageVersion _messageVersion;
private SynchronizedChannelCollection<IChannel> _pendingChannels; // app has not yet seen these.
private bool _receiveSynchronously;
private bool _sendAsynchronously;
private int _maxPendingReceives;
private bool _includeExceptionDetailInFaults;
private bool _session = false;
private SharedRuntimeState _shared;
private IDefaultCommunicationTimeouts _timeouts = null;
private TimeSpan _transactionTimeout;
private bool _performDefaultCloseInput;
private EventTraceActivity _eventTraceActivity;
private ErrorBehavior _errorBehavior;
internal ChannelDispatcher(SharedRuntimeState shared)
{
this.Initialize(shared);
}
private void Initialize(SharedRuntimeState shared)
{
_shared = shared;
_endpointDispatchers = new EndpointDispatcherCollection(this);
_channelInitializers = this.NewBehaviorCollection<IChannelInitializer>();
_channels = new CommunicationObjectManager<IChannel>(this.ThisLock);
_pendingChannels = new SynchronizedChannelCollection<IChannel>(this.ThisLock);
_errorHandlers = new Collection<IErrorHandler>();
_isTransactedReceive = false;
_receiveSynchronously = false;
_transactionTimeout = TimeSpan.Zero;
_maxPendingReceives = 1; //Default maxpending receives is 1;
if (_listener != null)
{
_listener.Faulted += new EventHandler(OnListenerFaulted);
}
}
protected override TimeSpan DefaultCloseTimeout
{
get
{
if (_timeouts != null)
{
return _timeouts.CloseTimeout;
}
else
{
return ServiceDefaults.CloseTimeout;
}
}
}
protected override TimeSpan DefaultOpenTimeout
{
get
{
if (_timeouts != null)
{
return _timeouts.OpenTimeout;
}
else
{
return ServiceDefaults.OpenTimeout;
}
}
}
internal EndpointDispatcherTable EndpointDispatcherTable
{
get { return _filterTable; }
}
internal CommunicationObjectManager<IChannel> Channels
{
get { return _channels; }
}
public SynchronizedCollection<EndpointDispatcher> Endpoints
{
get { return _endpointDispatchers; }
}
public Collection<IErrorHandler> ErrorHandlers
{
get { return _errorHandlers; }
}
public MessageVersion MessageVersion
{
get { return _messageVersion; }
set
{
_messageVersion = value;
this.ThrowIfDisposedOrImmutable();
}
}
internal bool EnableFaults
{
get { return _shared.EnableFaults; }
set
{
this.ThrowIfDisposedOrImmutable();
_shared.EnableFaults = value;
}
}
internal bool IsOnServer
{
get { return _shared.IsOnServer; }
}
public bool IsTransactedReceive
{
get
{
return _isTransactedReceive;
}
set
{
this.ThrowIfDisposedOrImmutable();
_isTransactedReceive = value;
}
}
public bool ReceiveContextEnabled
{
get
{
return _receiveContextEnabled;
}
set
{
this.ThrowIfDisposedOrImmutable();
_receiveContextEnabled = value;
}
}
internal bool BufferedReceiveEnabled
{
get;
set;
}
public override IChannelListener Listener
{
get { return _listener; }
}
public int MaxTransactedBatchSize
{
get
{
return _maxTransactedBatchSize;
}
set
{
if (value < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.ValueMustBeNonNegative));
}
this.ThrowIfDisposedOrImmutable();
_maxTransactedBatchSize = value;
}
}
public bool ManualAddressing
{
get { return _shared.ManualAddressing; }
set
{
this.ThrowIfDisposedOrImmutable();
_shared.ManualAddressing = value;
}
}
public bool ReceiveSynchronously
{
get
{
return _receiveSynchronously;
}
set
{
this.ThrowIfDisposedOrImmutable();
_receiveSynchronously = value;
}
}
public bool SendAsynchronously
{
get
{
return _sendAsynchronously;
}
set
{
this.ThrowIfDisposedOrImmutable();
_sendAsynchronously = value;
}
}
public int MaxPendingReceives
{
get
{
return _maxPendingReceives;
}
set
{
this.ThrowIfDisposedOrImmutable();
_maxPendingReceives = value;
}
}
public bool IncludeExceptionDetailInFaults
{
get { return _includeExceptionDetailInFaults; }
set
{
lock (this.ThisLock)
{
this.ThrowIfDisposedOrImmutable();
_includeExceptionDetailInFaults = value;
}
}
}
internal IDefaultCommunicationTimeouts DefaultCommunicationTimeouts
{
get { return _timeouts; }
}
private void AbortPendingChannels()
{
lock (this.ThisLock)
{
for (int i = _pendingChannels.Count - 1; i >= 0; i--)
{
_pendingChannels[i].Abort();
}
}
}
internal override void CloseInput(TimeSpan timeout)
{
// we have to perform some slightly convoluted logic here due to
// backwards compat. We probably need an IAsyncChannelDispatcher
// interface that has timeouts and async
this.CloseInput();
if (_performDefaultCloseInput)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
lock (this.ThisLock)
{
ListenerHandler handler = _listenerHandler;
if (handler != null)
{
handler.CloseInput(timeoutHelper.RemainingTime());
}
}
if (!_session)
{
ListenerHandler handler = _listenerHandler;
if (handler != null)
{
handler.Close(timeoutHelper.RemainingTime());
}
}
}
}
public override void CloseInput()
{
_performDefaultCloseInput = true;
}
private void OnListenerFaulted(object sender, EventArgs e)
{
this.Fault();
}
internal bool HandleError(Exception error)
{
ErrorHandlerFaultInfo dummy = new ErrorHandlerFaultInfo();
return this.HandleError(error, ref dummy);
}
internal bool HandleError(Exception error, ref ErrorHandlerFaultInfo faultInfo)
{
ErrorBehavior behavior;
lock (this.ThisLock)
{
if (_errorBehavior != null)
{
behavior = _errorBehavior;
}
else
{
behavior = new ErrorBehavior(this);
}
}
if (behavior != null)
{
return behavior.HandleError(error, ref faultInfo);
}
else
{
return false;
}
}
internal void InitializeChannel(IClientChannel channel)
{
this.ThrowIfDisposedOrNotOpen();
try
{
for (int i = 0; i < _channelInitializers.Count; ++i)
{
_channelInitializers[i].Initialize(channel);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
}
internal SynchronizedCollection<T> NewBehaviorCollection<T>()
{
return new ChannelDispatcherBehaviorCollection<T>(this);
}
private void OnAddEndpoint(EndpointDispatcher endpoint)
{
lock (this.ThisLock)
{
endpoint.Attach(this);
if (this.State == CommunicationState.Opened)
{
_filterTable.AddEndpoint(endpoint);
}
}
}
private void OnRemoveEndpoint(EndpointDispatcher endpoint)
{
lock (this.ThisLock)
{
if (this.State == CommunicationState.Opened)
{
_filterTable.RemoveEndpoint(endpoint);
}
endpoint.Detach(this);
}
}
protected override void OnAbort()
{
if (_listener != null)
{
_listener.Abort();
}
ListenerHandler handler = _listenerHandler;
if (handler != null)
{
handler.Abort();
}
this.AbortPendingChannels();
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (_listener != null)
{
_listener.Close(timeoutHelper.RemainingTime());
}
ListenerHandler handler = _listenerHandler;
if (handler != null)
{
handler.Close(timeoutHelper.RemainingTime());
}
this.AbortPendingChannels();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
List<ICommunicationObject> list = new List<ICommunicationObject>();
if (_listener != null)
{
list.Add(_listener);
}
ListenerHandler handler = _listenerHandler;
if (handler != null)
{
list.Add(handler);
}
return new CloseCollectionAsyncResult(timeout, callback, state, list);
}
protected override void OnEndClose(IAsyncResult result)
{
try
{
CloseCollectionAsyncResult.End(result);
}
finally
{
this.AbortPendingChannels();
}
}
protected override void OnClosed()
{
base.OnClosed();
}
protected override void OnOpen(TimeSpan timeout)
{
ThrowIfNoMessageVersion();
if (_listener != null)
{
try
{
_listener.Open(timeout);
}
catch (InvalidOperationException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateOuterExceptionWithEndpointsInformation(e));
}
}
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
this.OnClose(timeout);
return TaskHelpers.CompletedTask();
}
protected internal override Task OnOpenAsync(TimeSpan timeout)
{
this.OnOpen(timeout);
return TaskHelpers.CompletedTask();
}
private InvalidOperationException CreateOuterExceptionWithEndpointsInformation(InvalidOperationException e)
{
string endpointContractNames = CreateContractListString();
if (String.IsNullOrEmpty(endpointContractNames))
{
return new InvalidOperationException(SR.Format(SR.SFxChannelDispatcherUnableToOpen1, _listener.Uri), e);
}
else
{
return new InvalidOperationException(SR.Format(SR.SFxChannelDispatcherUnableToOpen2, _listener.Uri, endpointContractNames), e);
}
}
internal string CreateContractListString()
{
const string OpenQuote = "\"";
const string CloseQuote = "\"";
const string Space = " ";
Collection<string> namesSeen = new Collection<string>();
StringBuilder endpointContractNames = new StringBuilder();
lock (this.ThisLock)
{
foreach (EndpointDispatcher ed in this.Endpoints)
{
if (!namesSeen.Contains(ed.ContractName))
{
if (endpointContractNames.Length > 0)
{
endpointContractNames.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator);
endpointContractNames.Append(Space);
}
endpointContractNames.Append(OpenQuote);
endpointContractNames.Append(ed.ContractName);
endpointContractNames.Append(CloseQuote);
namesSeen.Add(ed.ContractName);
}
}
}
return endpointContractNames.ToString();
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
ThrowIfNoMessageVersion();
if (_listener != null)
{
try
{
return _listener.BeginOpen(timeout, callback, state);
}
catch (InvalidOperationException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateOuterExceptionWithEndpointsInformation(e));
}
}
else
{
return new CompletedAsyncResult(callback, state);
}
}
protected override void OnEndOpen(IAsyncResult result)
{
if (_listener != null)
{
try
{
_listener.EndOpen(result);
}
catch (InvalidOperationException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateOuterExceptionWithEndpointsInformation(e));
}
}
else
{
CompletedAsyncResult.End(result);
}
}
protected override void OnOpening()
{
if (TD.ListenerOpenStartIsEnabled())
{
_eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate();
TD.ListenerOpenStart(_eventTraceActivity,
(this.Listener != null) ? this.Listener.Uri.ToString() : string.Empty, Guid.Empty);
// Desktop: (this.host != null && host.EventTraceActivity != null) ? this.host.EventTraceActivity.ActivityId : Guid.Empty);
}
base.OnOpening();
}
protected override void OnOpened()
{
base.OnOpened();
if (TD.ListenerOpenStopIsEnabled())
{
TD.ListenerOpenStop(_eventTraceActivity);
_eventTraceActivity = null; // clear this since we don't need this anymore.
}
_errorBehavior = new ErrorBehavior(this);
_filterTable = new EndpointDispatcherTable(this.ThisLock);
for (int i = 0; i < _endpointDispatchers.Count; i++)
{
EndpointDispatcher endpoint = _endpointDispatchers[i];
// Force a build of the runtime to catch any unexpected errors before we are done opening.
// Lock down the DispatchRuntime.
endpoint.DispatchRuntime.LockDownProperties();
_filterTable.AddEndpoint(endpoint);
}
IListenerBinder binder = ListenerBinder.GetBinder(_listener, _messageVersion);
_listenerHandler = new ListenerHandler(binder, this, _timeouts);
_listenerHandler.Open(); // This never throws, which is why it's ok for it to happen in OnOpened
}
internal void ProvideFault(Exception e, FaultConverter faultConverter, ref ErrorHandlerFaultInfo faultInfo)
{
ErrorBehavior behavior;
lock (this.ThisLock)
{
if (_errorBehavior != null)
{
behavior = _errorBehavior;
}
else
{
behavior = new ErrorBehavior(this);
}
}
behavior.ProvideFault(e, faultConverter, ref faultInfo);
}
internal new void ThrowIfDisposedOrImmutable()
{
base.ThrowIfDisposedOrImmutable();
_shared.ThrowIfImmutable();
}
private void ThrowIfNoMessageVersion()
{
if (_messageVersion == null)
{
Exception error = new InvalidOperationException(SR.SFxChannelDispatcherNoMessageVersion);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
}
internal class EndpointDispatcherCollection : SynchronizedCollection<EndpointDispatcher>
{
private ChannelDispatcher _owner;
internal EndpointDispatcherCollection(ChannelDispatcher owner)
: base(owner.ThisLock)
{
_owner = owner;
}
protected override void ClearItems()
{
foreach (EndpointDispatcher item in this.Items)
{
_owner.OnRemoveEndpoint(item);
}
base.ClearItems();
}
protected override void InsertItem(int index, EndpointDispatcher item)
{
if (item == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
_owner.OnAddEndpoint(item);
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
EndpointDispatcher item = this.Items[index];
base.RemoveItem(index);
_owner.OnRemoveEndpoint(item);
}
protected override void SetItem(int index, EndpointDispatcher item)
{
Exception error = new InvalidOperationException(SR.SFxCollectionDoesNotSupportSet0);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
}
internal class ChannelDispatcherBehaviorCollection<T> : SynchronizedCollection<T>
{
private ChannelDispatcher _outer;
internal ChannelDispatcherBehaviorCollection(ChannelDispatcher outer)
: base(outer.ThisLock)
{
_outer = outer;
}
protected override void ClearItems()
{
_outer.ThrowIfDisposedOrImmutable();
base.ClearItems();
}
protected override void InsertItem(int index, T item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
}
_outer.ThrowIfDisposedOrImmutable();
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
_outer.ThrowIfDisposedOrImmutable();
base.RemoveItem(index);
}
protected override void SetItem(int index, T item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
}
_outer.ThrowIfDisposedOrImmutable();
base.SetItem(index, item);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Sanford.Multimedia.Midi;
using Sanford.Multimedia.Midi.UI;
namespace SequencerDemo
{
public partial class Form1 : Form
{
private bool scrolling = false;
private bool playing = false;
private bool closing = false;
private OutputDevice outDevice;
private int outDeviceID = 0;
private OutputDeviceDialog outDialog = new OutputDeviceDialog();
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
if(OutputDevice.DeviceCount == 0)
{
MessageBox.Show("No MIDI output devices available.", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Stop);
Close();
}
else
{
try
{
outDevice = new OutputDevice(outDeviceID);
sequence1.LoadProgressChanged += HandleLoadProgressChanged;
sequence1.LoadCompleted += HandleLoadCompleted;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Stop);
Close();
}
}
base.OnLoad(e);
}
protected override void OnKeyDown(KeyEventArgs e)
{
pianoControl1.PressPianoKey(e.KeyCode);
base.OnKeyDown(e);
}
protected override void OnKeyUp(KeyEventArgs e)
{
pianoControl1.ReleasePianoKey(e.KeyCode);
base.OnKeyUp(e);
}
protected override void OnClosing(CancelEventArgs e)
{
closing = true;
base.OnClosing(e);
}
protected override void OnClosed(EventArgs e)
{
sequence1.Dispose();
if(outDevice != null)
{
outDevice.Dispose();
}
outDialog.Dispose();
base.OnClosed(e);
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if(openMidiFileDialog.ShowDialog() == DialogResult.OK)
{
string fileName = openMidiFileDialog.FileName;
Open(fileName);
}
}
public void Open(string fileName)
{
try
{
sequencer1.Stop();
playing = false;
sequence1.LoadAsync(fileName);
this.Cursor = Cursors.WaitCursor;
startButton.Enabled = false;
continueButton.Enabled = false;
stopButton.Enabled = false;
openToolStripMenuItem.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void outputDeviceToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutDialog dlg = new AboutDialog();
dlg.ShowDialog();
}
private void stopButton_Click(object sender, EventArgs e)
{
try
{
playing = false;
sequencer1.Stop();
timer1.Stop();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
private void startButton_Click(object sender, EventArgs e)
{
try
{
playing = true;
sequencer1.Start();
timer1.Start();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
private void continueButton_Click(object sender, EventArgs e)
{
try
{
playing = true;
sequencer1.Continue();
timer1.Start();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
}
private void positionHScrollBar_Scroll(object sender, ScrollEventArgs e)
{
if(e.Type == ScrollEventType.EndScroll)
{
sequencer1.Position = e.NewValue;
scrolling = false;
}
else
{
scrolling = true;
}
}
private void HandleLoadProgressChanged(object sender, ProgressChangedEventArgs e)
{
toolStripProgressBar1.Value = e.ProgressPercentage;
}
private void HandleLoadCompleted(object sender, AsyncCompletedEventArgs e)
{
this.Cursor = Cursors.Arrow;
startButton.Enabled = true;
continueButton.Enabled = true;
stopButton.Enabled = true;
openToolStripMenuItem.Enabled = true;
toolStripProgressBar1.Value = 0;
if(e.Error == null)
{
positionHScrollBar.Value = 0;
positionHScrollBar.Maximum = sequence1.GetLength();
}
else
{
MessageBox.Show(e.Error.Message);
}
}
private void HandleChannelMessagePlayed(object sender, ChannelMessageEventArgs e)
{
if(closing)
{
return;
}
outDevice.Send(e.Message);
pianoControl1.Send(e.Message);
}
private void HandleChased(object sender, ChasedEventArgs e)
{
foreach(ChannelMessage message in e.Messages)
{
outDevice.Send(message);
}
}
private void HandleSysExMessagePlayed(object sender, SysExMessageEventArgs e)
{
// outDevice.Send(e.Message); Sometimes causes an exception to be thrown because the output device is overloaded.
}
private void HandleStopped(object sender, StoppedEventArgs e)
{
foreach(ChannelMessage message in e.Messages)
{
outDevice.Send(message);
pianoControl1.Send(message);
}
}
private void HandlePlayingCompleted(object sender, EventArgs e)
{
timer1.Stop();
}
private void pianoControl1_PianoKeyDown(object sender, PianoKeyEventArgs e)
{
#region Guard
if(playing)
{
return;
}
#endregion
outDevice.Send(new ChannelMessage(ChannelCommand.NoteOn, 0, e.NoteID, 127));
}
private void pianoControl1_PianoKeyUp(object sender, PianoKeyEventArgs e)
{
#region Guard
if(playing)
{
return;
}
#endregion
outDevice.Send(new ChannelMessage(ChannelCommand.NoteOff, 0, e.NoteID, 0));
}
private void timer1_Tick(object sender, EventArgs e)
{
if(!scrolling)
{
positionHScrollBar.Value = Math.Min(sequencer1.Position, positionHScrollBar.Maximum);
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmLang
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmLang() : base()
{
Load += frmLang_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.RadioButton withEventsField_Option3;
public System.Windows.Forms.RadioButton Option3 {
get { return withEventsField_Option3; }
set {
if (withEventsField_Option3 != null) {
withEventsField_Option3.CheckedChanged -= Option3_CheckedChanged;
}
withEventsField_Option3 = value;
if (withEventsField_Option3 != null) {
withEventsField_Option3.CheckedChanged += Option3_CheckedChanged;
}
}
}
private System.Windows.Forms.RadioButton withEventsField_Option2;
public System.Windows.Forms.RadioButton Option2 {
get { return withEventsField_Option2; }
set {
if (withEventsField_Option2 != null) {
withEventsField_Option2.CheckedChanged -= Option2_CheckedChanged;
}
withEventsField_Option2 = value;
if (withEventsField_Option2 != null) {
withEventsField_Option2.CheckedChanged += Option2_CheckedChanged;
}
}
}
private System.Windows.Forms.RadioButton withEventsField_Option1;
public System.Windows.Forms.RadioButton Option1 {
get { return withEventsField_Option1; }
set {
if (withEventsField_Option1 != null) {
withEventsField_Option1.CheckedChanged -= Option1_CheckedChanged;
}
withEventsField_Option1 = value;
if (withEventsField_Option1 != null) {
withEventsField_Option1.CheckedChanged += Option1_CheckedChanged;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
public System.Windows.Forms.Button cmdPrint;
public System.Windows.Forms.Label Label2;
public System.Windows.Forms.Panel picButtons;
public myDataGridView gridEdit;
public System.Windows.Forms.Label Label1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmLang));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.txtName = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.Option3 = new System.Windows.Forms.RadioButton();
this.Option2 = new System.Windows.Forms.RadioButton();
this.Option1 = new System.Windows.Forms.RadioButton();
this.cmdClose = new System.Windows.Forms.Button();
this.cmdPrint = new System.Windows.Forms.Button();
this.Label2 = new System.Windows.Forms.Label();
this.gridEdit = new myDataGridView();
this.Label1 = new System.Windows.Forms.Label();
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.gridEdit).BeginInit();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Language Translation Editor";
this.ClientSize = new System.Drawing.Size(963, 663);
this.Location = new System.Drawing.Point(3, 29);
this.ControlBox = false;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.KeyPreview = false;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmLang";
this.txtName.AutoSize = false;
this.txtName.Size = new System.Drawing.Size(301, 24);
this.txtName.Location = new System.Drawing.Point(125, 48);
this.txtName.TabIndex = 4;
this.txtName.Text = "Text1";
this.txtName.AcceptsReturn = true;
this.txtName.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtName.BackColor = System.Drawing.SystemColors.Window;
this.txtName.CausesValidation = true;
this.txtName.Enabled = true;
this.txtName.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtName.HideSelection = true;
this.txtName.ReadOnly = false;
this.txtName.MaxLength = 0;
this.txtName.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtName.Multiline = false;
this.txtName.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtName.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtName.TabStop = true;
this.txtName.Visible = true;
this.txtName.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtName.Name = "txtName";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.ForeColor = System.Drawing.SystemColors.WindowText;
this.picButtons.Size = new System.Drawing.Size(963, 44);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 1;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.picButtons.Name = "picButtons";
this.Option3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.Option3.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.Option3.Text = "Touch Screen";
this.Option3.Size = new System.Drawing.Size(129, 29);
this.Option3.Location = new System.Drawing.Point(448, 6);
this.Option3.Appearance = System.Windows.Forms.Appearance.Button;
this.Option3.TabIndex = 9;
this.Option3.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.Option3.CausesValidation = true;
this.Option3.Enabled = true;
this.Option3.ForeColor = System.Drawing.SystemColors.ControlText;
this.Option3.Cursor = System.Windows.Forms.Cursors.Default;
this.Option3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Option3.TabStop = true;
this.Option3.Checked = false;
this.Option3.Visible = true;
this.Option3.Name = "Option3";
this.Option2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.Option2.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.Option2.Text = "Point of Sale";
this.Option2.Size = new System.Drawing.Size(129, 29);
this.Option2.Location = new System.Drawing.Point(312, 6);
this.Option2.Appearance = System.Windows.Forms.Appearance.Button;
this.Option2.TabIndex = 8;
this.Option2.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.Option2.CausesValidation = true;
this.Option2.Enabled = true;
this.Option2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Option2.Cursor = System.Windows.Forms.Cursors.Default;
this.Option2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Option2.TabStop = true;
this.Option2.Checked = false;
this.Option2.Visible = true;
this.Option2.Name = "Option2";
this.Option1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.Option1.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.Option1.Text = "Back Office";
this.Option1.Size = new System.Drawing.Size(129, 29);
this.Option1.Location = new System.Drawing.Point(176, 6);
this.Option1.Appearance = System.Windows.Forms.Appearance.Button;
this.Option1.TabIndex = 7;
this.Option1.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.Option1.CausesValidation = true;
this.Option1.Enabled = true;
this.Option1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Option1.Cursor = System.Windows.Forms.Cursors.Default;
this.Option1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Option1.TabStop = true;
this.Option1.Checked = false;
this.Option1.Visible = true;
this.Option1.Name = "Option1";
this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdClose.Text = "E&xit";
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.Location = new System.Drawing.Point(880, 6);
this.cmdClose.TabIndex = 3;
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.CausesValidation = true;
this.cmdClose.Enabled = true;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.TabStop = true;
this.cmdClose.Name = "cmdClose";
this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPrint.Text = "&Print";
this.cmdPrint.Size = new System.Drawing.Size(73, 29);
this.cmdPrint.Location = new System.Drawing.Point(798, 6);
this.cmdPrint.TabIndex = 2;
this.cmdPrint.TabStop = false;
this.cmdPrint.Visible = false;
this.cmdPrint.BackColor = System.Drawing.SystemColors.Control;
this.cmdPrint.CausesValidation = true;
this.cmdPrint.Enabled = true;
this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPrint.Name = "cmdPrint";
this.Label2.Text = "Show Translations for :";
this.Label2.ForeColor = System.Drawing.Color.White;
this.Label2.Size = new System.Drawing.Size(158, 21);
this.Label2.Location = new System.Drawing.Point(16, 14);
this.Label2.TabIndex = 6;
this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label2.BackColor = System.Drawing.Color.Transparent;
this.Label2.Enabled = true;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.UseMnemonic = true;
this.Label2.Visible = true;
this.Label2.AutoSize = true;
this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label2.Name = "Label2";
//gridEdit.OcxState = CType(resources.GetObject("gridEdit.OcxState"), System.Windows.Forms.AxHost.State)
this.gridEdit.Size = new System.Drawing.Size(947, 582);
this.gridEdit.Location = new System.Drawing.Point(9, 75);
this.gridEdit.TabIndex = 0;
this.gridEdit.Name = "gridEdit";
this.Label1.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.Label1.Text = "Lanuage Name:";
this.Label1.ForeColor = System.Drawing.Color.Black;
this.Label1.Size = new System.Drawing.Size(110, 16);
this.Label1.Location = new System.Drawing.Point(13, 51);
this.Label1.TabIndex = 5;
this.Label1.BackColor = System.Drawing.Color.Transparent;
this.Label1.Enabled = true;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.UseMnemonic = true;
this.Label1.Visible = true;
this.Label1.AutoSize = true;
this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label1.Name = "Label1";
this.Controls.Add(txtName);
this.Controls.Add(picButtons);
this.Controls.Add(gridEdit);
this.Controls.Add(Label1);
this.picButtons.Controls.Add(Option3);
this.picButtons.Controls.Add(Option2);
this.picButtons.Controls.Add(Option1);
this.picButtons.Controls.Add(cmdClose);
this.picButtons.Controls.Add(cmdPrint);
this.picButtons.Controls.Add(Label2);
((System.ComponentModel.ISupportInitialize)this.gridEdit).EndInit();
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnitySampleAssets.Effects;
namespace UnitySampleAssets.SceneUtils
{
public class ParticleSceneControls : MonoBehaviour
{
public enum Mode
{
Activate,
Instantiate,
Trail
}
public enum AlignMode
{
Normal,
Up
}
public DemoParticleSystemList demoParticles;
public float spawnOffset = 0.5f;
public float multiply = 1;
public bool clearOnChange = false;
public Text titleText;
public Transform sceneCamera;
public Text instructionText;
public Button previousButton;
public Button nextButton;
public GraphicRaycaster graphicRaycaster;
public EventSystem eventSystem;
private ParticleSystemMultiplier m_ParticleMultiplier;
private List<Transform> m_CurrentParticleList = new List<Transform>();
private Transform m_Instance;
private static int s_SelectedIndex = 0;
private Vector3 m_CamOffsetVelocity = Vector3.zero;
private Vector3 m_LastPos;
private static DemoParticleSystem s_Selected;
private void Awake()
{
Select(s_SelectedIndex);
previousButton.onClick.AddListener(Previous);
nextButton.onClick.AddListener(Next);
}
private void OnDisable()
{
previousButton.onClick.RemoveAllListeners();
previousButton.onClick.RemoveAllListeners();
}
private void Previous()
{
s_SelectedIndex--;
if (s_SelectedIndex == -1)
{
s_SelectedIndex = demoParticles.items.Length - 1;
}
Select(s_SelectedIndex);
}
public void Next()
{
s_SelectedIndex++;
if (s_SelectedIndex == demoParticles.items.Length)
{
s_SelectedIndex = 0;
}
Select(s_SelectedIndex);
}
private void Update()
{
#if !MOBILE_INPUT
KeyboardInput();
#endif
sceneCamera.localPosition = Vector3.SmoothDamp(sceneCamera.localPosition, Vector3.forward*-s_Selected.camOffset,
ref m_CamOffsetVelocity, 1);
if (s_Selected.mode == Mode.Activate)
{
// this is for a particle system that just needs activating, and needs no interaction (eg, duststorm)
return;
}
if (CheckForGuiCollision()) return;
bool oneShotClick = (Input.GetMouseButtonDown(0) && s_Selected.mode == Mode.Instantiate);
bool repeat = (Input.GetMouseButton(0) && s_Selected.mode == Mode.Trail);
if (oneShotClick || repeat)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
var rot = Quaternion.LookRotation(hit.normal);
if (s_Selected.align == AlignMode.Up)
{
rot = Quaternion.identity;
}
var pos = hit.point + hit.normal*spawnOffset;
if ((pos - m_LastPos).magnitude > s_Selected.minDist)
{
if (s_Selected.mode != Mode.Trail || m_Instance == null)
{
m_Instance = (Transform) Instantiate(s_Selected.transform, pos, rot);
if (m_ParticleMultiplier != null)
{
m_Instance.GetComponent<ParticleSystemMultiplier>().multiplier = multiply;
}
m_CurrentParticleList.Add(m_Instance);
if (s_Selected.maxCount > 0 && m_CurrentParticleList.Count > s_Selected.maxCount)
{
if (m_CurrentParticleList[0] != null)
{
Destroy(m_CurrentParticleList[0].gameObject);
}
m_CurrentParticleList.RemoveAt(0);
}
}
else
{
m_Instance.position = pos;
m_Instance.rotation = rot;
}
if (s_Selected.mode == Mode.Trail)
{
m_Instance.transform.GetComponent<ParticleSystem>().enableEmission = false;
m_Instance.transform.GetComponent<ParticleSystem>().Emit(1);
}
m_Instance.parent = hit.transform;
m_LastPos = pos;
}
}
}
}
#if !MOBILE_INPUT
void KeyboardInput()
{
if(Input.GetKeyDown(KeyCode.LeftArrow))
Previous();
if (Input.GetKeyDown(KeyCode.RightArrow))
Next();
}
#endif
bool CheckForGuiCollision()
{
PointerEventData eventData = new PointerEventData(eventSystem);
eventData.pressPosition = Input.mousePosition;
eventData.position = Input.mousePosition;
List<RaycastResult> list = new List<RaycastResult>();
graphicRaycaster.Raycast(eventData, list);
return list.Count > 0;
}
private void Select(int i)
{
s_Selected = demoParticles.items[i];
m_Instance = null;
foreach (var otherEffect in demoParticles.items)
{
if ((otherEffect != s_Selected) && (otherEffect.mode == Mode.Activate))
{
otherEffect.transform.gameObject.SetActive(false);
}
}
if (s_Selected.mode == Mode.Activate)
{
s_Selected.transform.gameObject.SetActive(true);
}
m_ParticleMultiplier = s_Selected.transform.GetComponent<ParticleSystemMultiplier>();
multiply = 1;
if (clearOnChange)
{
while (m_CurrentParticleList.Count > 0)
{
Destroy(m_CurrentParticleList[0].gameObject);
m_CurrentParticleList.RemoveAt(0);
}
}
instructionText.text = s_Selected.instructionText;
titleText.text = s_Selected.transform.name;
}
[Serializable]
public class DemoParticleSystem
{
public Transform transform;
public Mode mode;
public AlignMode align;
public int maxCount;
public float minDist;
public int camOffset = 15;
public string instructionText;
}
[Serializable]
public class DemoParticleSystemList
{
public DemoParticleSystem[] items;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Orders;
using Nop.Services.Events;
using Nop.Services.Stores;
namespace Nop.Services.Orders
{
/// <summary>
/// Checkout attribute service
/// </summary>
public partial class CheckoutAttributeService : ICheckoutAttributeService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : store ID
/// {1} : >A value indicating whether we should exlude shippable attributes
/// </remarks>
private const string CHECKOUTATTRIBUTES_ALL_KEY = "Nop.checkoutattribute.all-{0}-{1}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : checkout attribute ID
/// </remarks>
private const string CHECKOUTATTRIBUTES_BY_ID_KEY = "Nop.checkoutattribute.id-{0}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : checkout attribute ID
/// </remarks>
private const string CHECKOUTATTRIBUTEVALUES_ALL_KEY = "Nop.checkoutattributevalue.all-{0}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : checkout attribute value ID
/// </remarks>
private const string CHECKOUTATTRIBUTEVALUES_BY_ID_KEY = "Nop.checkoutattributevalue.id-{0}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string CHECKOUTATTRIBUTES_PATTERN_KEY = "Nop.checkoutattribute.";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string CHECKOUTATTRIBUTEVALUES_PATTERN_KEY = "Nop.checkoutattributevalue.";
#endregion
#region Fields
private readonly IRepository<CheckoutAttribute> _checkoutAttributeRepository;
private readonly IRepository<CheckoutAttributeValue> _checkoutAttributeValueRepository;
private readonly IStoreMappingService _storeMappingService;
private readonly IEventPublisher _eventPublisher;
private readonly ICacheManager _cacheManager;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="cacheManager">Cache manager</param>
/// <param name="checkoutAttributeRepository">Checkout attribute repository</param>
/// <param name="checkoutAttributeValueRepository">Checkout attribute value repository</param>
/// <param name="storeMappingService">Store mapping service</param>
/// <param name="eventPublisher">Event published</param>
public CheckoutAttributeService(ICacheManager cacheManager,
IRepository<CheckoutAttribute> checkoutAttributeRepository,
IRepository<CheckoutAttributeValue> checkoutAttributeValueRepository,
IStoreMappingService storeMappingService,
IEventPublisher eventPublisher)
{
this._cacheManager = cacheManager;
this._checkoutAttributeRepository = checkoutAttributeRepository;
this._checkoutAttributeValueRepository = checkoutAttributeValueRepository;
this._storeMappingService = storeMappingService;
this._eventPublisher = eventPublisher;
}
#endregion
#region Methods
#region Checkout attributes
/// <summary>
/// Deletes a checkout attribute
/// </summary>
/// <param name="checkoutAttribute">Checkout attribute</param>
public virtual void DeleteCheckoutAttribute(CheckoutAttribute checkoutAttribute)
{
if (checkoutAttribute == null)
throw new ArgumentNullException("checkoutAttribute");
_checkoutAttributeRepository.Delete(checkoutAttribute);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(checkoutAttribute);
}
/// <summary>
/// Gets all checkout attributes
/// </summary>
/// <param name="storeId">Store identifier</param>
/// <param name="excludeShippableAttributes">A value indicating whether we should exlude shippable attributes</param>
/// <returns>Checkout attribute collection</returns>
public virtual IList<CheckoutAttribute> GetAllCheckoutAttributes(int storeId = 0, bool excludeShippableAttributes = false)
{
string key = string.Format(CHECKOUTATTRIBUTES_ALL_KEY, storeId, excludeShippableAttributes);
return _cacheManager.Get(key, () =>
{
var query = from ca in _checkoutAttributeRepository.Table
orderby ca.DisplayOrder
select ca;
var checkoutAttributes = query.ToList();
if (storeId > 0)
{
//store mapping
checkoutAttributes = checkoutAttributes.Where(ca => _storeMappingService.Authorize(ca)).ToList();
}
if (excludeShippableAttributes)
{
//remove attributes which require shippable products
checkoutAttributes = checkoutAttributes.RemoveShippableAttributes().ToList();
}
return checkoutAttributes;
});
}
/// <summary>
/// Gets a checkout attribute
/// </summary>
/// <param name="checkoutAttributeId">Checkout attribute identifier</param>
/// <returns>Checkout attribute</returns>
public virtual CheckoutAttribute GetCheckoutAttributeById(int checkoutAttributeId)
{
if (checkoutAttributeId == 0)
return null;
string key = string.Format(CHECKOUTATTRIBUTES_BY_ID_KEY, checkoutAttributeId);
return _cacheManager.Get(key, () => _checkoutAttributeRepository.GetById(checkoutAttributeId));
}
/// <summary>
/// Inserts a checkout attribute
/// </summary>
/// <param name="checkoutAttribute">Checkout attribute</param>
public virtual void InsertCheckoutAttribute(CheckoutAttribute checkoutAttribute)
{
if (checkoutAttribute == null)
throw new ArgumentNullException("checkoutAttribute");
_checkoutAttributeRepository.Insert(checkoutAttribute);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(checkoutAttribute);
}
/// <summary>
/// Updates the checkout attribute
/// </summary>
/// <param name="checkoutAttribute">Checkout attribute</param>
public virtual void UpdateCheckoutAttribute(CheckoutAttribute checkoutAttribute)
{
if (checkoutAttribute == null)
throw new ArgumentNullException("checkoutAttribute");
_checkoutAttributeRepository.Update(checkoutAttribute);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(checkoutAttribute);
}
#endregion
#region Checkout attribute values
/// <summary>
/// Deletes a checkout attribute value
/// </summary>
/// <param name="checkoutAttributeValue">Checkout attribute value</param>
public virtual void DeleteCheckoutAttributeValue(CheckoutAttributeValue checkoutAttributeValue)
{
if (checkoutAttributeValue == null)
throw new ArgumentNullException("checkoutAttributeValue");
_checkoutAttributeValueRepository.Delete(checkoutAttributeValue);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(checkoutAttributeValue);
}
/// <summary>
/// Gets checkout attribute values by checkout attribute identifier
/// </summary>
/// <param name="checkoutAttributeId">The checkout attribute identifier</param>
/// <returns>Checkout attribute value collection</returns>
public virtual IList<CheckoutAttributeValue> GetCheckoutAttributeValues(int checkoutAttributeId)
{
string key = string.Format(CHECKOUTATTRIBUTEVALUES_ALL_KEY, checkoutAttributeId);
return _cacheManager.Get(key, () =>
{
var query = from cav in _checkoutAttributeValueRepository.Table
orderby cav.DisplayOrder
where cav.CheckoutAttributeId == checkoutAttributeId
select cav;
var checkoutAttributeValues = query.ToList();
return checkoutAttributeValues;
});
}
/// <summary>
/// Gets a checkout attribute value
/// </summary>
/// <param name="checkoutAttributeValueId">Checkout attribute value identifier</param>
/// <returns>Checkout attribute value</returns>
public virtual CheckoutAttributeValue GetCheckoutAttributeValueById(int checkoutAttributeValueId)
{
if (checkoutAttributeValueId == 0)
return null;
string key = string.Format(CHECKOUTATTRIBUTEVALUES_BY_ID_KEY, checkoutAttributeValueId);
return _cacheManager.Get(key, () => _checkoutAttributeValueRepository.GetById(checkoutAttributeValueId));
}
/// <summary>
/// Inserts a checkout attribute value
/// </summary>
/// <param name="checkoutAttributeValue">Checkout attribute value</param>
public virtual void InsertCheckoutAttributeValue(CheckoutAttributeValue checkoutAttributeValue)
{
if (checkoutAttributeValue == null)
throw new ArgumentNullException("checkoutAttributeValue");
_checkoutAttributeValueRepository.Insert(checkoutAttributeValue);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(checkoutAttributeValue);
}
/// <summary>
/// Updates the checkout attribute value
/// </summary>
/// <param name="checkoutAttributeValue">Checkout attribute value</param>
public virtual void UpdateCheckoutAttributeValue(CheckoutAttributeValue checkoutAttributeValue)
{
if (checkoutAttributeValue == null)
throw new ArgumentNullException("checkoutAttributeValue");
_checkoutAttributeValueRepository.Update(checkoutAttributeValue);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY);
_cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(checkoutAttributeValue);
}
#endregion
#endregion
}
}
| |
using System;
using System.Globalization;
using MvcContrib.FluentHtml.Elements;
using MvcContrib.FluentHtml.Html;
using MvcContrib.UnitTests.FluentHtml.Helpers;
using NUnit.Framework;
namespace MvcContrib.UnitTests.FluentHtml
{
[TestFixture]
public class DateAndTimePickerTests
{
[Test]
public void basic_datepicker_render()
{
var html = new DatePicker("foo").ToString();
html.ShouldHaveHtmlNode("foo")
.ShouldBeNamed(HtmlTag.Input)
.ShouldHaveAttribute(HtmlAttribute.Type).WithValue(HtmlInputType.Date);
}
[Test]
public void datepicker_correctly_formats_date_value()
{
var value = new DateTime(2000, 2, 2, 14, 5, 24, 331);
var element = new DatePicker("test").Value(value);
element.ValueAttributeShouldEqual("2000-02-02");
}
[Test]
public void datepicker_correctly_render_null_value()
{
var element = new DatePicker("test").Value(null);
element.ValueAttributeShouldEqual(null);
}
[Test]
public void datepicker_limit_sets_limits()
{
var element = new DatePicker("x").Limit(new DateTime(2000, 1, 1), new DateTime(2000, 12, 31), 7).ToString()
.ShouldHaveHtmlNode("x");
element.ShouldHaveAttribute(HtmlAttribute.Min).WithValue("2000-01-01");
element.ShouldHaveAttribute(HtmlAttribute.Max).WithValue("2000-12-31");
element.ShouldHaveAttribute(HtmlAttribute.Step).WithValue("7");
}
[Test]
public void datepicker_novalidate_true_renders_novalidate()
{
new DatePicker("x").Novalidate(true).ToString()
.ShouldHaveHtmlNode("x")
.ShouldHaveAttribute(HtmlAttribute.NoValidate).WithValue(HtmlAttribute.NoValidate);
}
[Test]
public void datepicker_novalidate_false_does_not_render_novalidate()
{
new DatePicker("x").Novalidate(true).Novalidate(false).ToString()
.ShouldHaveHtmlNode("x")
.ShouldNotHaveAttribute(HtmlAttribute.NoValidate);
}
[Test]
public void datepicker_required_true_renders_required()
{
new DatePicker("x").Required(true).ToString()
.ShouldHaveHtmlNode("x")
.ShouldHaveAttribute(HtmlAttribute.Required).WithValue(HtmlAttribute.Required);
}
[Test]
public void datepicker_required_false_does_not_render_required()
{
new DatePicker("x").Required(true).Required(false).ToString()
.ShouldHaveHtmlNode("x")
.ShouldNotHaveAttribute(HtmlAttribute.Required);
}
[Test]
public void basic_timepicker_render()
{
var html = new TimePicker("foo").ToString();
html.ShouldHaveHtmlNode("foo")
.ShouldBeNamed(HtmlTag.Input)
.ShouldHaveAttribute(HtmlAttribute.Type).WithValue(HtmlInputType.Time);
}
[Test]
public void timepicker_correctly_formats_date_value()
{
var value = new DateTime(2000, 2, 2, 14, 5, 24, 331);
var element = new TimePicker("test").Value(value);
element.ValueAttributeShouldEqual("14:05:24.331");
}
[Test]
public void timepicker_limit_sets_limits()
{
var element = new DatePicker("x").Limit(new TimeSpan(0, 1, 0, 0), new TimeSpan(10, 20, 30), 2).ToString()
.ShouldHaveHtmlNode("x");
element.ShouldHaveAttribute(HtmlAttribute.Min).WithValue("01:00:00");
element.ShouldHaveAttribute(HtmlAttribute.Max).WithValue("10:20:30");
element.ShouldHaveAttribute(HtmlAttribute.Step).WithValue("2");
}
[Test]
public void timepicker_correctly_formats_timespan_value()
{
var value = new TimeSpan(0, 14, 5, 24, 331);
var element = new TimePicker("test").Value(value);
element.ValueAttributeShouldEqual("14:05:24.331");
}
[Test]
public void basic_datetimepicker_render()
{
var html = new DateTimePicker("foo").ToString();
html.ShouldHaveHtmlNode("foo")
.ShouldBeNamed(HtmlTag.Input)
.ShouldHaveAttribute(HtmlAttribute.Type).WithValue(HtmlInputType.DateTime);
}
[Test]
public void datetimepicker_correctly_formats_utc_date_value()
{
var value = new DateTime(2000, 2, 2, 14, 5, 24, 331, DateTimeKind.Utc);
var element = new DateTimePicker("test").Value(value);
element.ValueAttributeShouldEqual("2000-02-02T14:05:24.331Z");
}
[Test]
public void datetimepicker_correctly_formats_unspecified_date_value()
{
var value = new DateTime(2000, 2, 2, 14, 5, 24, 331);
var element = new DateTimePicker("test").Value(value);
element.ValueAttributeShouldEqual("2000-02-02T14:05:24.331Z");
}
[Test]
public void datetimepicker_correctly_formats_local_date_value()
{
var value = new DateTime(2000, 2, 2, 14, 5, 24, 331, DateTimeKind.Local);
var element = new DateTimePicker("test").Value(value);
var timeZoneOffset = string.Format("{0:xK}", value).Substring(1, 6); //Note: 'K' by itself blows up.
var expectedValue = string.Format("2000-02-02T14:05:24.331{0}", timeZoneOffset);
element.ValueAttributeShouldEqual(expectedValue);
}
[Test]
public void datetimepicker_limit_sets_limits()
{
var element = new DateTimePicker("x").Limit(new DateTime(2000, 1, 1), new DateTime(2000, 12, 31, 10, 20, 30, 331), 3).ToString()
.ShouldHaveHtmlNode("x");
element.ShouldHaveAttribute(HtmlAttribute.Min).WithValue("2000-01-01T00:00:00.000Z");
element.ShouldHaveAttribute(HtmlAttribute.Max).WithValue("2000-12-31T10:20:30.331Z");
element.ShouldHaveAttribute(HtmlAttribute.Step).WithValue("3");
}
[Test]
public void basic_monthpicker_render()
{
var html = new MonthPicker("foo").ToString();
html.ShouldHaveHtmlNode("foo")
.ShouldBeNamed(HtmlTag.Input)
.ShouldHaveAttribute(HtmlAttribute.Type).WithValue(HtmlInputType.Month);
}
[Test]
public void monthpicker_correctly_formats_date_value()
{
var value = new DateTime(2000, 2, 2);
var element = new MonthPicker("test").Value(value);
element.ValueAttributeShouldEqual("2000-02");
}
[Test]
public void monthpicker_limit_sets_limits()
{
var element = new MonthPicker("x").Limit(new DateTime(2000, 1, 1), new DateTime(2000, 12, 31, 10, 20, 30, 331), 3).ToString()
.ShouldHaveHtmlNode("x");
element.ShouldHaveAttribute(HtmlAttribute.Min).WithValue("2000-01");
element.ShouldHaveAttribute(HtmlAttribute.Max).WithValue("2000-12");
element.ShouldHaveAttribute(HtmlAttribute.Step).WithValue("3");
}
[Test]
public void basic_datetimelocal_picker_render()
{
var html = new DateTimeLocalPicker("foo").ToString();
html.ShouldHaveHtmlNode("foo")
.ShouldBeNamed(HtmlTag.Input)
.ShouldHaveAttribute(HtmlAttribute.Type).WithValue(HtmlInputType.DateTimeLocal);
}
[Test]
public void datetimelocalpicker_correctly_formats_date_value()
{
var value = new DateTime(2000, 2, 2, 14, 33, 31, 331);
var element = new DateTimeLocalPicker("test").Value(value);
element.ValueAttributeShouldEqual("2000-02-02T14:33:31.331");
}
[Test]
public void datetimepickerlocal_limit_sets_limits()
{
var element = new DateTimeLocalPicker("x").Limit(new DateTime(2000, 1, 1), new DateTime(2000, 12, 31), 3).ToString()
.ShouldHaveHtmlNode("x");
element.ShouldHaveAttribute(HtmlAttribute.Min).WithValue("2000-01-01T00:00:00.000");
element.ShouldHaveAttribute(HtmlAttribute.Max).WithValue("2000-12-31T00:00:00.000");
element.ShouldHaveAttribute(HtmlAttribute.Step).WithValue("3");
}
[Test]
public void basic_weekpicker_render()
{
var html = new WeekPicker("foo").ToString();
html.ShouldHaveHtmlNode("foo")
.ShouldBeNamed(HtmlTag.Input)
.ShouldHaveAttribute(HtmlAttribute.Type).WithValue(HtmlInputType.Week);
}
[Test]
public void weekpicker_correctly_formats_date_value()
{
var value = new DateTime(2011, 1, 3);
var element = new WeekPicker("test").Value(value);
element.ValueAttributeShouldEqual("2011-W02");
}
[Test]
public void weekpicker_correctly_formats_date_value_using_custom_rules()
{
var value = new DateTime(2011, 1, 2);
var element = new WeekPicker("test")
.Evaluation(CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday)
.Value(value);
element.ValueAttributeShouldEqual("2011-W01");
}
[Test]
public void weekpicker_limit_sets_limits()
{
var element = new WeekPicker("x")
.Evaluation(CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday)
.Limit(new DateTime(2000, 1, 2), new DateTime(2000, 01, 9), 3).ToString()
.ShouldHaveHtmlNode("x");
element.ShouldHaveAttribute(HtmlAttribute.Min).WithValue("2000-W01");
element.ShouldHaveAttribute(HtmlAttribute.Max).WithValue("2000-W02");
element.ShouldHaveAttribute(HtmlAttribute.Step).WithValue("3");
}
[Test]
public void weekpicker_limit_sets_limits_without_step()
{
var element = new WeekPicker("x")
.Evaluation(CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday)
.Limit(new DateTime(2000, 1, 2), new DateTime(2000, 01, 9)).ToString()
.ShouldHaveHtmlNode("x");
element.ShouldHaveAttribute(HtmlAttribute.Min).WithValue("2000-W01");
element.ShouldHaveAttribute(HtmlAttribute.Max).WithValue("2000-W02");
element.ShouldNotHaveAttribute(HtmlAttribute.Step);
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Java.Security.Interfaces.cs
//
// 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.
#pragma warning disable 1717
namespace Java.Security.Interfaces
{
/// <summary>
/// <para>The interface for Digital Signature Algorithm (DSA) specific parameters. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/DSAParams
/// </java-name>
[Dot42.DexImport("java/security/interfaces/DSAParams", AccessFlags = 1537)]
public partial interface IDSAParams
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the base (<c> g </c> ) value.</para><para></para>
/// </summary>
/// <returns>
/// <para>the base (<c> g </c> ) value. </para>
/// </returns>
/// <java-name>
/// getG
/// </java-name>
[Dot42.DexImport("getG", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetG() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the prime (<c> p </c> ) value.</para><para></para>
/// </summary>
/// <returns>
/// <para>the prime (<c> p </c> ) value. </para>
/// </returns>
/// <java-name>
/// getP
/// </java-name>
[Dot42.DexImport("getP", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetP() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the subprime (<c> q </c> value.</para><para></para>
/// </summary>
/// <returns>
/// <para>the subprime (<c> q </c> value. </para>
/// </returns>
/// <java-name>
/// getQ
/// </java-name>
[Dot42.DexImport("getQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetQ() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The base interface for Elliptic Curve (EC) public or private keys. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/ECKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/ECKey", AccessFlags = 1537)]
public partial interface IECKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the EC key parameters.</para><para></para>
/// </summary>
/// <returns>
/// <para>the EC key parameters. </para>
/// </returns>
/// <java-name>
/// getParams
/// </java-name>
[Dot42.DexImport("getParams", "()Ljava/security/spec/ECParameterSpec;", AccessFlags = 1025)]
global::Java.Security.Spec.ECParameterSpec GetParams() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for key generators that can generate DSA key pairs. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/DSAKeyPairGenerator
/// </java-name>
[Dot42.DexImport("java/security/interfaces/DSAKeyPairGenerator", AccessFlags = 1537)]
public partial interface IDSAKeyPairGenerator
/* scope: __dot42__ */
{
/// <summary>
/// <para>Initializes this generator with the prime (<c> p </c> ), subprime (<c> q </c> ), and base (<c> g </c> ) values from the specified parameters.</para><para></para>
/// </summary>
/// <java-name>
/// initialize
/// </java-name>
[Dot42.DexImport("initialize", "(Ljava/security/interfaces/DSAParams;Ljava/security/SecureRandom;)V", AccessFlags = 1025)]
void Initialize(global::Java.Security.Interfaces.IDSAParams @params, global::Java.Security.SecureRandom random) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Initializes this generator for the specified modulus length. Valid values for the modulus length are the multiples of 8 between 512 and 1024. </para><para>The parameter <c> genParams </c> specifies whether this method should generate new prime (<c> p </c> ), subprime (<c> q </c> ), and base (<c> g </c> ) values or whether it will use the pre-calculated values for the specified modulus length. Default parameters are available for modulus lengths of 512 and 1024 bits.</para><para></para>
/// </summary>
/// <java-name>
/// initialize
/// </java-name>
[Dot42.DexImport("initialize", "(IZLjava/security/SecureRandom;)V", AccessFlags = 1025)]
void Initialize(int modlen, bool genParams, global::Java.Security.SecureRandom random) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a Digital Signature Algorithm (DSA) private key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/DSAPrivateKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/DSAPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IDSAPrivateKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = 7776497482533790279;
}
/// <summary>
/// <para>The interface for a Digital Signature Algorithm (DSA) private key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/DSAPrivateKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/DSAPrivateKey", AccessFlags = 1537)]
public partial interface IDSAPrivateKey : global::Java.Security.Interfaces.IDSAKey, global::Java.Security.IPrivateKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the private key value <c> x </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the private key value <c> x </c> . </para>
/// </returns>
/// <java-name>
/// getX
/// </java-name>
[Dot42.DexImport("getX", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetX() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for an Elliptic Curve (EC) private key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/ECPrivateKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/ECPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IECPrivateKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = -7896394956925609184;
}
/// <summary>
/// <para>The interface for an Elliptic Curve (EC) private key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/ECPrivateKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/ECPrivateKey", AccessFlags = 1537)]
public partial interface IECPrivateKey : global::Java.Security.IPrivateKey, global::Java.Security.Interfaces.IECKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the private value <c> S </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the private value <c> S </c> . </para>
/// </returns>
/// <java-name>
/// getS
/// </java-name>
[Dot42.DexImport("getS", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetS() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for an Elliptic Curve (EC) public key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/ECPublicKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/ECPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IECPublicKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = -3314988629879632826;
}
/// <summary>
/// <para>The interface for an Elliptic Curve (EC) public key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/ECPublicKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/ECPublicKey", AccessFlags = 1537)]
public partial interface IECPublicKey : global::Java.Security.IPublicKey, global::Java.Security.Interfaces.IECKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the public point <c> W </c> on an elliptic curve (EC).</para><para></para>
/// </summary>
/// <returns>
/// <para>the public point <c> W </c> on an elliptic curve (EC). </para>
/// </returns>
/// <java-name>
/// getW
/// </java-name>
[Dot42.DexImport("getW", "()Ljava/security/spec/ECPoint;", AccessFlags = 1025)]
global::Java.Security.Spec.ECPoint GetW() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a Digital Signature Algorithm (DSA) public key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/DSAPublicKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/DSAPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IDSAPublicKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = 1234526332779022332;
}
/// <summary>
/// <para>The interface for a Digital Signature Algorithm (DSA) public key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/DSAPublicKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/DSAPublicKey", AccessFlags = 1537)]
public partial interface IDSAPublicKey : global::Java.Security.Interfaces.IDSAKey, global::Java.Security.IPublicKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the public key value <c> y </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the public key value <c> y </c> . </para>
/// </returns>
/// <java-name>
/// getY
/// </java-name>
[Dot42.DexImport("getY", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetY() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The base interface for PKCS#1 RSA public and private keys. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/RSAKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/RSAKey", AccessFlags = 1537)]
public partial interface IRSAKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the modulus.</para><para></para>
/// </summary>
/// <returns>
/// <para>the modulus. </para>
/// </returns>
/// <java-name>
/// getModulus
/// </java-name>
[Dot42.DexImport("getModulus", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetModulus() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The base interface for Digital Signature Algorithm (DSA) public or private keys. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/DSAKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/DSAKey", AccessFlags = 1537)]
public partial interface IDSAKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the DSA key parameters.</para><para></para>
/// </summary>
/// <returns>
/// <para>the DSA key parameters. </para>
/// </returns>
/// <java-name>
/// getParams
/// </java-name>
[Dot42.DexImport("getParams", "()Ljava/security/interfaces/DSAParams;", AccessFlags = 1025)]
global::Java.Security.Interfaces.IDSAParams GetParams() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a Multi-Prime RSA private key. Specified by . </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/RSAMultiPrimePrivateCrtKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/RSAMultiPrimePrivateCrtKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IRSAMultiPrimePrivateCrtKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>the serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = 618058533534628008;
}
/// <summary>
/// <para>The interface for a Multi-Prime RSA private key. Specified by . </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/RSAMultiPrimePrivateCrtKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/RSAMultiPrimePrivateCrtKey", AccessFlags = 1537)]
public partial interface IRSAMultiPrimePrivateCrtKey : global::Java.Security.Interfaces.IRSAPrivateKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the CRT coefficient, <c> q^-1 mod p </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the CRT coefficient. </para>
/// </returns>
/// <java-name>
/// getCrtCoefficient
/// </java-name>
[Dot42.DexImport("getCrtCoefficient", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetCrtCoefficient() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the information for the additional primes.</para><para></para>
/// </summary>
/// <returns>
/// <para>the information for the additional primes, or <c> null </c> if there are only the two primes (<c> p, q </c> ), </para>
/// </returns>
/// <java-name>
/// getOtherPrimeInfo
/// </java-name>
[Dot42.DexImport("getOtherPrimeInfo", "()[Ljava/security/spec/RSAOtherPrimeInfo;", AccessFlags = 1025)]
global::Java.Security.Spec.RSAOtherPrimeInfo[] GetOtherPrimeInfo() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the prime factor <c> p </c> of <c> n </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the prime factor <c> p </c> of <c> n </c> . </para>
/// </returns>
/// <java-name>
/// getPrimeP
/// </java-name>
[Dot42.DexImport("getPrimeP", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPrimeP() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the prime factor <c> q </c> of <c> n </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the prime factor <c> q </c> of <c> n </c> . </para>
/// </returns>
/// <java-name>
/// getPrimeQ
/// </java-name>
[Dot42.DexImport("getPrimeQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPrimeQ() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the CRT exponent of the prime <c> p </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the CRT exponent of the prime <c> p </c> . </para>
/// </returns>
/// <java-name>
/// getPrimeExponentP
/// </java-name>
[Dot42.DexImport("getPrimeExponentP", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPrimeExponentP() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the CRT exponent of the prime <c> q </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the CRT exponent of the prime <c> q </c> . </para>
/// </returns>
/// <java-name>
/// getPrimeExponentQ
/// </java-name>
[Dot42.DexImport("getPrimeExponentQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPrimeExponentQ() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the public exponent <c> e </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the public exponent <c> e </c> . </para>
/// </returns>
/// <java-name>
/// getPublicExponent
/// </java-name>
[Dot42.DexImport("getPublicExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPublicExponent() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a PKCS#1 RSA private key using CRT information values. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/RSAPrivateCrtKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/RSAPrivateCrtKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IRSAPrivateCrtKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = -5682214253527700368;
}
/// <summary>
/// <para>The interface for a PKCS#1 RSA private key using CRT information values. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/RSAPrivateCrtKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/RSAPrivateCrtKey", AccessFlags = 1537)]
public partial interface IRSAPrivateCrtKey : global::Java.Security.Interfaces.IRSAPrivateKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the CRT coefficient, <c> q^-1 mod p </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the CRT coefficient. </para>
/// </returns>
/// <java-name>
/// getCrtCoefficient
/// </java-name>
[Dot42.DexImport("getCrtCoefficient", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetCrtCoefficient() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the prime factor <c> p </c> of <c> n </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the prime factor <c> p </c> of <c> n </c> . </para>
/// </returns>
/// <java-name>
/// getPrimeP
/// </java-name>
[Dot42.DexImport("getPrimeP", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPrimeP() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the prime factor <c> q </c> of <c> n </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the prime factor <c> q </c> of <c> n </c> . </para>
/// </returns>
/// <java-name>
/// getPrimeQ
/// </java-name>
[Dot42.DexImport("getPrimeQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPrimeQ() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the CRT exponent of the primet <c> p </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the CRT exponent of the prime <c> p </c> . </para>
/// </returns>
/// <java-name>
/// getPrimeExponentP
/// </java-name>
[Dot42.DexImport("getPrimeExponentP", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPrimeExponentP() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the CRT exponent of the prime <c> q </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the CRT exponent of the prime <c> q </c> . </para>
/// </returns>
/// <java-name>
/// getPrimeExponentQ
/// </java-name>
[Dot42.DexImport("getPrimeExponentQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPrimeExponentQ() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the public exponent <c> e </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the public exponent <c> e </c> . </para>
/// </returns>
/// <java-name>
/// getPublicExponent
/// </java-name>
[Dot42.DexImport("getPublicExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPublicExponent() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for an PKCS#1 RSA private key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/RSAPrivateKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/RSAPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IRSAPrivateKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = 5187144804936595022;
}
/// <summary>
/// <para>The interface for an PKCS#1 RSA private key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/RSAPrivateKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/RSAPrivateKey", AccessFlags = 1537)]
public partial interface IRSAPrivateKey : global::Java.Security.IPrivateKey, global::Java.Security.Interfaces.IRSAKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the private exponent <c> d </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the private exponent <c> d </c> . </para>
/// </returns>
/// <java-name>
/// getPrivateExponent
/// </java-name>
[Dot42.DexImport("getPrivateExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPrivateExponent() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>The interface for a PKCS#1 RSA public key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/RSAPublicKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/RSAPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IRSAPublicKeyConstants
/* scope: __dot42__ */
{
/// <summary>
/// <para>The serial version identifier. </para>
/// </summary>
/// <java-name>
/// serialVersionUID
/// </java-name>
[Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)]
public const long SerialVersionUID = -8727434096241101194;
}
/// <summary>
/// <para>The interface for a PKCS#1 RSA public key. </para>
/// </summary>
/// <java-name>
/// java/security/interfaces/RSAPublicKey
/// </java-name>
[Dot42.DexImport("java/security/interfaces/RSAPublicKey", AccessFlags = 1537)]
public partial interface IRSAPublicKey : global::Java.Security.IPublicKey, global::Java.Security.Interfaces.IRSAKey
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the public exponent <c> e </c> .</para><para></para>
/// </summary>
/// <returns>
/// <para>the public exponent <c> e </c> . </para>
/// </returns>
/// <java-name>
/// getPublicExponent
/// </java-name>
[Dot42.DexImport("getPublicExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)]
global::Java.Math.BigInteger GetPublicExponent() /* MethodBuilder.Create */ ;
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Batcher.Internals;
namespace Batcher
{
public class SqlDataSets : IDisposable
{
#region Private members
private bool _isDisposed;
private readonly SqlCommand _command;
private IDataReader _dataReader;
#endregion
#region .ctor
private SqlDataSets(SqlCommand command)
{
this._command = command;
}
public static SqlDataSets Get(SqlCommand command)
{
var dataSets = new SqlDataSets(command);
dataSets._dataReader = dataSets._command.ExecuteReader();
return dataSets;
}
public static async Task<SqlDataSets> GetAsync(SqlCommand command)
{
var dataSets = new SqlDataSets(command);
dataSets._dataReader = await dataSets._command.ExecuteReaderAsync();
return dataSets;
}
public static async Task<SqlDataSets> GetAsync(SqlCommand command, CancellationToken cancellationToken)
{
var dataSets = new SqlDataSets(command);
dataSets._dataReader = await dataSets._command.ExecuteReaderAsync(cancellationToken);
return dataSets;
}
#endregion
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool isDisposing)
{
if (!this._isDisposed)
{
if (isDisposing)
{
this._dataReader.Dispose();
this._command.Dispose();
}
this._isDisposed = true;
}
}
#endregion
#region Public methods
/// <summary>
/// Skips the next set of data from the underlying data reader.
/// </summary>
public void SkipSet()
{
this._dataReader.NextResult();
}
/// <summary>
/// Returns the next set of data from the underlying data reader.
/// </summary>
/// <typeparam name="T">The type in which the data is encapsulated.</typeparam>
/// <returns></returns>
public IEnumerable<T> GetSet<T>()
where T : class, new()
{
return GetSet(() => new T());
}
/// <summary>
/// Returns the next set of data from the underlying data reader.
/// </summary>
/// <typeparam name="T">The type in which the data is encapsulated.</typeparam>
/// <param name="instanceInitializer">An initializer for the object instance, in case the default constructor is not available.</param>
/// <returns></returns>
public IEnumerable<T> GetSet<T>(Func<T> instanceInitializer)
where T : class
{
if (instanceInitializer == null)
{
throw new ArgumentNullException("instanceInitializer");
}
return new SqlDataSet<T>(this, this._dataReader.GetObjects(instanceInitializer));
}
/// <summary>
/// Returns all sets of data from the underlying data reader mapped to a single type.
/// </summary>
/// <typeparam name="T">The type in which the data is encapsulated.</typeparam>
/// <returns></returns>
public IEnumerable<T> GetUnifiedSets<T>()
where T : class, new()
{
return GetUnifiedSets(() => new T());
}
/// <summary>
/// Returns all sets of data from the underlying data reader mapped to a single type.
/// </summary>
/// <typeparam name="T">The type in which the data is encapsulated.</typeparam>
/// <param name="instanceInitializer">An initializer for the object instance, in case the default constructor is not available.</param>
/// <returns></returns>
public IEnumerable<T> GetUnifiedSets<T>(Func<T> instanceInitializer)
where T : class
{
return new SqlDataSet<T>(this, GetUnifiedSetsInternal(instanceInitializer).SelectMany(sets => sets));
}
/// <summary>
/// Returns the next set of data from the underlying data reader, taking only the first column.
/// </summary>
/// <typeparam name="T">The base type (e.g.: string, int, decimal).</typeparam>
/// <returns></returns>
public IEnumerable<T> GetSetBase<T>()
{
return new SqlDataSet<T>(this, this._dataReader.GetBaseObjects<T>());
}
/// <summary>
/// Returns all sets of data from the underlying data reader, taking only the first column.
/// </summary>
/// <typeparam name="T">The base type (e.g.: string, int, decimal).</typeparam>
/// <returns></returns>
public IEnumerable<T> GetUnifiedSetsBase<T>()
{
return new SqlDataSet<T>(this, GetUnifiedSetsBaseInternal<T>().SelectMany(sets => sets));
}
/// <summary>
/// Returns the next set of data from the underlying data reader.
/// </summary>
/// <typeparam name="T">The type in which the data is encapsulated.</typeparam>
/// <param name="defaultValue">The default anonymous object value.</param>
/// <returns></returns>
public IEnumerable<T> GetSetAnonymous<T>(T defaultValue)
{
return new SqlDataSet<T>(this, this._dataReader.GetAnonymous(defaultValue));
}
/// <summary>
/// Returns all sets of data from the underlying data reader.
/// </summary>
/// <typeparam name="T">The type in which the data is encapsulated.</typeparam>
/// <param name="defaultValue">The default anonymous object value.</param>
/// <returns></returns>
public IEnumerable<T> GetUnifiedSetsAnonymous<T>(T defaultValue)
{
return new SqlDataSet<T>(this, GetUnifiedSetsAnonymousInternal(defaultValue).SelectMany(sets => sets));
}
#endregion
#region Private methods
private IEnumerable<IEnumerable<T>> GetUnifiedSetsInternal<T>(Func<T> instanceInitializer)
where T : class
{
if (instanceInitializer == null)
{
throw new ArgumentNullException("instanceInitializer");
}
yield return this._dataReader.GetObjects(instanceInitializer);
while (this._dataReader.NextResult())
{
yield return this._dataReader.GetObjects(instanceInitializer);
}
}
private IEnumerable<IEnumerable<T>> GetUnifiedSetsBaseInternal<T>()
{
yield return this._dataReader.GetBaseObjects<T>();
while (this._dataReader.NextResult())
{
yield return this._dataReader.GetBaseObjects<T>();
}
}
internal IEnumerable<IEnumerable<T>> GetUnifiedSetsAnonymousInternal<T>(T defaultValue)
{
yield return this._dataReader.GetAnonymous(defaultValue);
while (this._dataReader.NextResult())
{
yield return this._dataReader.GetAnonymous(defaultValue);
}
}
#endregion
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim 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.Xml.Serialization;
using OpenMetaverse;
namespace OpenSim.Framework
{
[Serializable]
public class AssetBase
{
private byte[] m_data;
private AssetMetadata m_metadata;
public AssetBase()
{
m_metadata = new AssetMetadata();
}
public AssetBase(UUID assetId, string name)
{
m_metadata = new AssetMetadata();
m_metadata.FullID = assetId;
m_metadata.Name = name;
}
public AssetBase(UUID assetID, string name, sbyte assetType, string creatorID)
{
m_metadata = new AssetMetadata();
m_metadata.FullID = assetID;
m_metadata.Name = name;
m_metadata.Type = assetType;
}
public bool ContainsReferences
{
get
{
return
IsTextualAsset && (
Type != (sbyte)AssetType.Notecard
&& Type != (sbyte)AssetType.CallingCard
&& Type != (sbyte)AssetType.LSLText
&& Type != (sbyte)AssetType.Landmark);
}
}
public bool IsTextualAsset
{
get
{
return !IsBinaryAsset;
}
}
public bool IsBinaryAsset
{
get
{
return
(Type == (sbyte) AssetType.Animation ||
Type == (sbyte)AssetType.Gesture ||
Type == (sbyte)AssetType.Simstate ||
Type == (sbyte)AssetType.Unknown ||
Type == (sbyte)AssetType.Object ||
Type == (sbyte)AssetType.Sound ||
Type == (sbyte)AssetType.SoundWAV ||
Type == (sbyte)AssetType.Texture ||
Type == (sbyte)AssetType.TextureTGA ||
Type == (sbyte)AssetType.Folder ||
Type == (sbyte)AssetType.RootFolder ||
Type == (sbyte)AssetType.LostAndFoundFolder ||
Type == (sbyte)AssetType.SnapshotFolder ||
Type == (sbyte)AssetType.TrashFolder ||
Type == (sbyte)AssetType.ImageJPEG ||
Type == (sbyte) AssetType.ImageTGA ||
Type == (sbyte) AssetType.LSLBytecode);
}
}
public bool IsImageAsset
{
get
{
return (
Type == (sbyte)AssetType.Texture ||
Type == (sbyte)AssetType.TextureTGA ||
Type == (sbyte)AssetType.ImageJPEG ||
Type == (sbyte)AssetType.ImageTGA
);
}
}
public virtual byte[] Data
{
get { return m_data; }
set { m_data = value; }
}
public UUID FullID
{
get { return m_metadata.FullID; }
set { m_metadata.FullID = value; }
}
public string ID
{
get { return m_metadata.ID; }
set { m_metadata.ID = value; }
}
public string Name
{
get { return m_metadata.Name; }
set { m_metadata.Name = value; }
}
public string Description
{
get { return m_metadata.Description; }
set { m_metadata.Description = value; }
}
public sbyte Type
{
get { return m_metadata.Type; }
set { m_metadata.Type = value; }
}
public bool Local
{
get { return m_metadata.Local; }
set { m_metadata.Local = value; }
}
public bool Temporary
{
get { return m_metadata.Temporary; }
set { m_metadata.Temporary = value; }
}
[XmlIgnore]
public AssetMetadata Metadata
{
get { return m_metadata; }
set { m_metadata = value; }
}
}
public class AssetMetadata
{
private UUID m_fullid;
private string m_name = String.Empty;
private string m_description = String.Empty;
private DateTime m_creation_date;
private sbyte m_type;
private string m_content_type;
private byte[] m_sha1;
private bool m_local = false;
private bool m_temporary = false;
//private Dictionary<string, Uri> m_methods = new Dictionary<string, Uri>();
//private OSDMap m_extra_data;
public UUID FullID
{
get { return m_fullid; }
set { m_fullid = value; }
}
public string ID
{
get { return m_fullid.ToString(); }
set { m_fullid = new UUID(value); }
}
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public string Description
{
get { return m_description; }
set { m_description = value; }
}
public DateTime CreationDate
{
get { return m_creation_date; }
set { m_creation_date = value; }
}
public sbyte Type
{
get { return m_type; }
set { m_type = value; }
}
public string ContentType
{
get { return m_content_type; }
set { m_content_type = value; }
}
public byte[] SHA1
{
get { return m_sha1; }
set { m_sha1 = value; }
}
public bool Local
{
get { return m_local; }
set { m_local = value; }
}
public bool Temporary
{
get { return m_temporary; }
set { m_temporary = value; }
}
//public Dictionary<string, Uri> Methods
//{
// get { return m_methods; }
// set { m_methods = value; }
//}
//public OSDMap ExtraData
//{
// get { return m_extra_data; }
// set { m_extra_data = value; }
//}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Net;
using System.Reflection;
using log4net;
using log4net.Config;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
namespace OpenSim
{
/// <summary>
/// Starting class for the OpenSimulator Region
/// </summary>
public static class Application
{
/// <summary>
/// Text Console Logger
/// </summary>
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Save Crashes in the bin/crashes folder. Configurable with m_crashDir
/// </summary>
public static bool m_saveCrashDumps = false;
/// <summary>
/// Directory to save crash reports to. Relative to bin/
/// </summary>
public static string m_crashDir = "crashes";
/// <summary>
/// Instance of the OpenSim class. This could be OpenSim or OpenSimBackground depending on the configuration
/// </summary>
private static OpenSimBase m_sim = null;
//could move our main function into OpenSimMain and kill this class
public static void Main(string[] args)
{
// Under any circumstance other than an explicit exit the exit code should be 1.
Environment.ExitCode = 1;
// First line, hook the appdomain to the crash reporter
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
ServicePointManager.DefaultConnectionLimit = 12;
// Add the arguments supplied when running the application to the configuration
var configSource = new ArgvConfigSource(args);
configSource.AddSwitch("Startup", "pidfile");
var pidFile = new PIDFileManager(configSource.Configs["Startup"].GetString("pidfile", string.Empty));
pidFile.SetStatus(PIDFileManager.Status.Starting);
// Configure Log4Net
configSource.AddSwitch("Startup", "logconfig");
string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty);
if (!String.IsNullOrEmpty(logConfigFile))
{
XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile));
m_log.InfoFormat("[HALCYON MAIN]: configured log4net using \"{0}\" as configuration file",
logConfigFile);
}
else
{
XmlConfigurator.Configure();
m_log.Info("[HALCYON MAIN]: configured log4net using default Halcyon.exe.config");
}
m_log.Info("Performing compatibility checks... ");
string supported = String.Empty;
if (Util.IsEnvironmentSupported(ref supported))
{
m_log.Info("Environment is compatible.\n");
}
else
{
m_log.Warn("Environment is unsupported (" + supported + ")\n");
}
// Configure nIni aliases and localles
Culture.SetCurrentCulture();
configSource.Alias.AddAlias("On", true);
configSource.Alias.AddAlias("Off", false);
configSource.Alias.AddAlias("True", true);
configSource.Alias.AddAlias("False", false);
configSource.Alias.AddAlias("Yes", true);
configSource.Alias.AddAlias("No", false);
configSource.AddSwitch("Startup", "background");
configSource.AddSwitch("Startup", "inifile");
configSource.AddSwitch("Startup", "inimaster");
configSource.AddSwitch("Startup", "inidirectory");
configSource.AddSwitch("Startup", "gridmode");
configSource.AddSwitch("Startup", "physics");
configSource.AddSwitch("Startup", "gui");
configSource.AddSwitch("Startup", "console");
configSource.AddSwitch("Startup", "save_crashes");
configSource.AddSwitch("Startup", "crash_dir");
configSource.AddConfig("StandAlone");
configSource.AddConfig("Network");
// Check if we're running in the background or not
bool background = configSource.Configs["Startup"].GetBoolean("background", false);
// Check if we're saving crashes
m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false);
// load Crash directory config
m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir);
if (background)
{
m_sim = new OpenSimBackground(configSource);
pidFile.SetStatus(PIDFileManager.Status.Running);
m_sim.Startup();
}
else
{
m_sim = new OpenSim(configSource);
m_sim.Startup();
pidFile.SetStatus(PIDFileManager.Status.Running);
while (true)
{
try
{
// Block thread here for input
MainConsole.Instance.Prompt();
}
catch (Exception e)
{
m_log.ErrorFormat("Command error: {0}", e);
}
}
}
}
private static bool _IsHandlingException = false; // Make sure we don't go recursive on ourself
/// <summary>
/// Global exception handler -- all unhandlet exceptions end up here :)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (_IsHandlingException)
{
return;
}
_IsHandlingException = true;
// TODO: Add config option to allow users to turn off error reporting
// TODO: Post error report (disabled for now)
string msg = String.Empty;
msg += "\r\n";
msg += "APPLICATION EXCEPTION DETECTED: " + e.ToString() + "\r\n";
msg += "\r\n";
msg += "Exception: " + e.ExceptionObject.ToString() + "\r\n";
Exception ex = (Exception) e.ExceptionObject;
if (ex.InnerException != null)
{
msg += "InnerException: " + ex.InnerException.ToString() + "\r\n";
}
msg += "\r\n";
msg += "Application is terminating: " + e.IsTerminating.ToString() + "\r\n";
m_log.ErrorFormat("[APPLICATION]: {0}", msg);
if (m_saveCrashDumps)
{
// Log exception to disk
try
{
if (!Directory.Exists(m_crashDir))
{
Directory.CreateDirectory(m_crashDir);
}
string log = Util.GetUniqueFilename(ex.GetType() + ".txt");
using (StreamWriter m_crashLog = new StreamWriter(Path.Combine(m_crashDir, log)))
{
m_crashLog.WriteLine(msg);
}
File.Copy("Halcyon.ini", Path.Combine(m_crashDir, log + "_Halcyon.ini"), true);
}
catch (Exception e2)
{
m_log.ErrorFormat("[CRASH LOGGER CRASHED]: {0}", e2);
}
}
_IsHandlingException = false;
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using Encog.Util;
namespace Encog.App.Quant.Util
{
/// <summary>
/// A buffer of bar segments.
/// </summary>
public class BarBuffer
{
/// <summary>
/// The bar data loaded.
/// </summary>
private readonly IList<double[]> data;
/// <summary>
/// The number of periods.
/// </summary>
private readonly int periods;
/// <summary>
/// Construct the object.
/// </summary>
/// <param name="thePeriods">The number of periods.</param>
public BarBuffer(int thePeriods)
{
data = new List<double[]>();
periods = thePeriods;
}
/// <value>The data.</value>
public IList<double[]> Data
{
get { return data; }
}
/// <summary>
/// Determine if the buffer is full.
/// </summary>
/// <value>True if the buffer is full.</value>
public bool Full
{
get { return data.Count >= periods; }
}
/// <summary>
/// Add a bar.
/// </summary>
/// <param name="d">The bar data.</param>
public void Add(double d)
{
var da = new double[1];
da[0] = d;
Add(da);
}
/// <summary>
/// Add a bar.
/// </summary>
/// <param name="d">The bar data.</param>
public void Add(double[] d)
{
data.Insert(0, EngineArray.ArrayCopy(d));
if (data.Count > periods)
{
data.RemoveAt(data.Count - 1);
}
}
/// <summary>
/// Average all of the bars.
/// </summary>
/// <param name="idx">The bar index to average.</param>
/// <returns>The average.</returns>
public double Average(int idx)
{
double total = 0;
for (int i = 0; i < data.Count; i++)
{
double[] d = data[i];
total += d[idx];
}
return total/data.Count;
}
/// <summary>
/// Get the average gain.
/// </summary>
/// <param name="idx">The field to get the average gain for.</param>
/// <returns>The average gain.</returns>
public double AverageGain(int idx)
{
double total = 0;
int count = 0;
for (int i = 0; i < data.Count - 1; i++)
{
double[] today = data[i];
double[] yesterday = data[i + 1];
double diff = today[idx] - yesterday[idx];
if (diff > 0)
{
total += diff;
}
count++;
}
if (count == 0)
{
return 0;
}
else
{
return total/count;
}
}
/// <summary>
/// Get the average loss.
/// </summary>
/// <param name="idx">The index to check for.</param>
/// <returns>The average loss.</returns>
public double AverageLoss(int idx)
{
double total = 0;
int count = 0;
for (int i = 0; i < data.Count - 1; i++)
{
double[] today = data[i];
double[] yesterday = data[i + 1];
double diff = today[idx] - yesterday[idx];
if (diff < 0)
{
total += Math.Abs(diff);
}
count++;
}
if (count == 0)
{
return 0;
}
else
{
return total/count;
}
}
/// <summary>
/// Get the max for the specified index.
/// </summary>
/// <param name="idx">The index to check.</param>
/// <returns>The max.</returns>
public double Max(int idx)
{
double result = Double.MinValue;
foreach (var d in data)
{
result = Math.Max(d[idx], result);
}
return result;
}
/// <summary>
/// Get the min for the specified index.
/// </summary>
/// <param name="idx">The index to check.</param>
/// <returns>The min.</returns>
public double Min(int idx)
{
double result = Double.MaxValue;
foreach (var d in data)
{
result = Math.Min(d[idx], result);
}
return result;
}
/// <summary>
/// Pop (and remove) the oldest bar in the buffer.
/// </summary>
/// <returns>The oldest bar in the buffer.</returns>
public double[] Pop()
{
if (data.Count == 0)
{
return null;
}
int idx = data.Count - 1;
double[] result = data[idx];
data.RemoveAt(idx);
return result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Execution;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
using Microsoft.Build.Unittest;
using Shouldly;
using Xunit;
namespace Microsoft.Build.UnitTests.BackEnd
{
public class ResultsCache_Tests
{
[Fact]
public void TestConstructor()
{
ResultsCache cache = new ResultsCache();
}
[Fact]
public void TestAddAndRetrieveResults()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget" }, null, BuildEventContext.Invalid, null); BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
BuildResult retrievedResult = cache.GetResultForRequest(request);
Assert.True(AreResultsIdentical(result, retrievedResult));
}
[Fact]
public void TestAddAndRetrieveResultsByConfiguration()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "otherTarget" }, null, BuildEventContext.Invalid, null);
result = new BuildResult(request);
result.AddResultsForTarget("otherTarget", BuildResultUtilities.GetEmptySucceedingTargetResult());
cache.AddResult(result);
BuildResult retrievedResult = cache.GetResultsForConfiguration(1);
Assert.True(retrievedResult.HasResultsForTarget("testTarget"));
Assert.True(retrievedResult.HasResultsForTarget("otherTarget"));
}
[Fact]
public void CacheCanBeEnumerated()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(submissionId: 1, nodeRequestId: 0, configurationId: 1, new string[1] { "testTarget" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("result1target1", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "otherTarget" }, null, BuildEventContext.Invalid, null);
result = new BuildResult(request);
result.AddResultsForTarget("result1target2", BuildResultUtilities.GetEmptySucceedingTargetResult());
cache.AddResult(result);
BuildResult result2 = new BuildResult(new BuildRequest(submissionId: 1, nodeRequestId: 0, configurationId: 2, new string[1] { "testTarget" }, null, BuildEventContext.Invalid, null));
result2.AddResultsForTarget("result2target1", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result2);
var results = cache.GetEnumerator().ToArray();
results.Length.ShouldBe(2);
Assert.True(results[0].HasResultsForTarget("result1target1"));
Assert.True(results[0].HasResultsForTarget("result1target2"));
Assert.True(results[1].HasResultsForTarget("result2target1"));
}
[Fact]
public void TestMissingResults()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget" }, null, BuildEventContext.Invalid, null);
BuildResult retrievedResult = cache.GetResultForRequest(request);
Assert.Null(retrievedResult);
}
[Fact]
public void TestRetrieveMergedResults()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[2] { "testTarget", "testTarget2" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
BuildResult result2 = new BuildResult(request);
result2.AddResultsForTarget("testTarget2", BuildResultUtilities.GetEmptySucceedingTargetResult());
cache.AddResult(result2);
BuildResult retrievedResult = cache.GetResultForRequest(request);
Assert.True(AreResultsIdenticalForTarget(result, retrievedResult, "testTarget"));
Assert.True(AreResultsIdenticalForTarget(result2, retrievedResult, "testTarget2"));
}
[Fact]
public void TestMergeResultsWithException()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[] { "testTarget" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
BuildResult result2 = new BuildResult(request, new Exception("Test exception"));
cache.AddResult(result2);
BuildResult retrievedResult = cache.GetResultForRequest(request);
Assert.NotNull(retrievedResult.Exception);
}
[Fact]
public void TestRetrieveIncompleteResults()
{
Assert.Throws<InternalErrorException>(() =>
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[2] { "testTarget", "testTarget2" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
cache.GetResultForRequest(request);
}
);
}
[Fact]
public void TestRetrieveSubsetResults()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget2" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
BuildResult result2 = new BuildResult(request);
result2.AddResultsForTarget("testTarget2", BuildResultUtilities.GetEmptySucceedingTargetResult());
cache.AddResult(result2);
BuildResult retrievedResult = cache.GetResultForRequest(request);
Assert.True(AreResultsIdenticalForTarget(result2, retrievedResult, "testTarget2"));
}
/// <summary>
/// If a result had multiple targets associated with it and we only requested some of their
/// results, the returned result should only contain the targets we asked for, BUT the overall
/// status of the result should remain the same.
/// </summary>
[Fact]
public void TestRetrieveSubsetTargetsFromResult()
{
ResultsCache cache = new ResultsCache();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget2" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
result.AddResultsForTarget("testTarget2", BuildResultUtilities.GetEmptySucceedingTargetResult());
cache.AddResult(result);
ResultsCacheResponse response = cache.SatisfyRequest(request, new List<string>(), new List<string>(new string[] { "testTarget2" }), new List<string>(new string[] { "testTarget" }), skippedResultsAreOK: false);
Assert.Equal(ResultsCacheResponseType.Satisfied, response.Type);
Assert.True(AreResultsIdenticalForTarget(result, response.Results, "testTarget2"));
Assert.False(response.Results.HasResultsForTarget("testTarget"));
Assert.Equal(BuildResultCode.Failure, response.Results.OverallResult);
}
[Fact]
public void TestClearResultsCache()
{
ResultsCache cache = new ResultsCache();
cache.ClearResults();
BuildRequest request = new BuildRequest(1 /* submissionId */, 0, 1, new string[1] { "testTarget2" }, null, BuildEventContext.Invalid, null);
BuildResult result = new BuildResult(request);
result.AddResultsForTarget("testTarget", BuildResultUtilities.GetEmptyFailingTargetResult());
cache.AddResult(result);
cache.ClearResults();
Assert.Null(cache.GetResultForRequest(request));
}
public static IEnumerable<object[]> CacheSerializationTestData
{
get
{
yield return new[] {new ResultsCache()};
var request1 = new BuildRequest(1, 2, 3, new[] {"target1"}, null, BuildEventContext.Invalid, null);
var request2 = new BuildRequest(4, 5, 6, new[] {"target2"}, null, BuildEventContext.Invalid, null);
var br1 = new BuildResult(request1);
br1.AddResultsForTarget("target1", BuildResultUtilities.GetEmptySucceedingTargetResult());
var resultsCache = new ResultsCache();
resultsCache.AddResult(br1.Clone());
yield return new[] {resultsCache};
var br2 = new BuildResult(request2);
br2.AddResultsForTarget("target2", BuildResultUtilities.GetEmptyFailingTargetResult());
var resultsCache2 = new ResultsCache();
resultsCache2.AddResult(br1.Clone());
resultsCache2.AddResult(br2.Clone());
yield return new[] {resultsCache2};
}
}
[Theory]
[MemberData(nameof(CacheSerializationTestData))]
public void TestResultsCacheTranslation(object obj)
{
var resultsCache = (ResultsCache)obj;
resultsCache.Translate(TranslationHelpers.GetWriteTranslator());
var copy = new ResultsCache(TranslationHelpers.GetReadTranslator());
copy.ResultsDictionary.Keys.ToHashSet().SetEquals(resultsCache.ResultsDictionary.Keys.ToHashSet()).ShouldBeTrue();
foreach (var configId in copy.ResultsDictionary.Keys)
{
var copiedBuildResult = copy.ResultsDictionary[configId];
var initialBuildResult = resultsCache.ResultsDictionary[configId];
copiedBuildResult.SubmissionId.ShouldBe(initialBuildResult.SubmissionId);
copiedBuildResult.ConfigurationId.ShouldBe(initialBuildResult.ConfigurationId);
copiedBuildResult.ResultsByTarget.Keys.ToHashSet().SetEquals(initialBuildResult.ResultsByTarget.Keys.ToHashSet()).ShouldBeTrue();
foreach (var targetKey in copiedBuildResult.ResultsByTarget.Keys)
{
var copiedTargetResult = copiedBuildResult.ResultsByTarget[targetKey];
var initialTargetResult = initialBuildResult.ResultsByTarget[targetKey];
copiedTargetResult.WorkUnitResult.ResultCode.ShouldBe(initialTargetResult.WorkUnitResult.ResultCode);
copiedTargetResult.WorkUnitResult.ActionCode.ShouldBe(initialTargetResult.WorkUnitResult.ActionCode);
}
}
}
#region Helper Methods
static internal bool AreResultsIdentical(BuildResult a, BuildResult b)
{
if (a.ConfigurationId != b.ConfigurationId)
{
return false;
}
if ((a.Exception == null) ^ (b.Exception == null))
{
return false;
}
if (a.Exception != null)
{
if (a.Exception.GetType() != b.Exception.GetType())
{
return false;
}
}
if (a.OverallResult != b.OverallResult)
{
return false;
}
foreach (KeyValuePair<string, TargetResult> targetResult in a.ResultsByTarget)
{
if (!AreResultsIdenticalForTarget(a, b, targetResult.Key))
{
return false;
}
}
foreach (KeyValuePair<string, TargetResult> targetResult in b.ResultsByTarget)
{
if (!AreResultsIdenticalForTarget(a, b, targetResult.Key))
{
return false;
}
}
return true;
}
static internal bool AreResultsIdenticalForTargets(BuildResult a, BuildResult b, string[] targets)
{
foreach (string target in targets)
{
if (!AreResultsIdenticalForTarget(a, b, target))
{
return false;
}
}
return true;
}
static private bool AreResultsIdenticalForTarget(BuildResult a, BuildResult b, string target)
{
if (!a.HasResultsForTarget(target) || !b.HasResultsForTarget(target))
{
return false;
}
if (a[target].ResultCode != b[target].ResultCode)
{
return false;
}
if (!AreItemsIdentical(a[target].Items, b[target].Items))
{
return false;
}
return true;
}
static private bool AreItemsIdentical(IList<ITaskItem> a, IList<ITaskItem> b)
{
// Exhaustive comparison of items should not be necessary since we don't merge on the item level.
return a.Count == b.Count;
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Linq;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;
namespace LibGit2Sharp.Tests
{
public class UnstageFixture : BaseFixture
{
[Fact]
public void StagingANewVersionOfAFileThenUnstagingItRevertsTheBlobToTheVersionOfHead()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
int count = repo.Index.Count;
string filename = Path.Combine("1", "branch_file.txt");
const string posixifiedFileName = "1/branch_file.txt";
ObjectId blobId = repo.Index[posixifiedFileName].Id;
string fullpath = Path.Combine(repo.Info.WorkingDirectory, filename);
File.AppendAllText(fullpath, "Is there there anybody out there?");
repo.Stage(filename);
Assert.Equal(count, repo.Index.Count);
Assert.NotEqual((blobId), repo.Index[posixifiedFileName].Id);
repo.Unstage(posixifiedFileName);
Assert.Equal(count, repo.Index.Count);
Assert.Equal(blobId, repo.Index[posixifiedFileName].Id);
}
}
[Fact]
public void CanStageAndUnstageAnIgnoredFile()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
Touch(repo.Info.WorkingDirectory, ".gitignore", "*.ign" + Environment.NewLine);
const string relativePath = "Champa.ign";
Touch(repo.Info.WorkingDirectory, relativePath, "On stage!" + Environment.NewLine);
Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(relativePath));
repo.Stage(relativePath, new StageOptions { IncludeIgnored = true });
Assert.Equal(FileStatus.Added, repo.RetrieveStatus(relativePath));
repo.Unstage(relativePath);
Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(relativePath));
}
}
[Theory]
[InlineData("1/branch_file.txt", FileStatus.Unaltered, true, FileStatus.Unaltered, true, 0)]
[InlineData("deleted_unstaged_file.txt", FileStatus.Missing, true, FileStatus.Missing, true, 0)]
[InlineData("modified_unstaged_file.txt", FileStatus.Modified, true, FileStatus.Modified, true, 0)]
[InlineData("modified_staged_file.txt", FileStatus.Staged, true, FileStatus.Modified, true, 0)]
[InlineData("new_tracked_file.txt", FileStatus.Added, true, FileStatus.Untracked, false, -1)]
[InlineData("deleted_staged_file.txt", FileStatus.Removed, false, FileStatus.Missing, true, 1)]
public void CanUnstage(
string relativePath, FileStatus currentStatus, bool doesCurrentlyExistInTheIndex,
FileStatus expectedStatusOnceStaged, bool doesExistInTheIndexOnceStaged, int expectedIndexCountVariation)
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
int count = repo.Index.Count;
Assert.Equal(doesCurrentlyExistInTheIndex, (repo.Index[relativePath] != null));
Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath));
repo.Unstage(relativePath);
Assert.Equal(count + expectedIndexCountVariation, repo.Index.Count);
Assert.Equal(doesExistInTheIndexOnceStaged, (repo.Index[relativePath] != null));
Assert.Equal(expectedStatusOnceStaged, repo.RetrieveStatus(relativePath));
}
}
[Theory]
[InlineData("new_untracked_file.txt", FileStatus.Untracked)]
[InlineData("where-am-I.txt", FileStatus.Nonexistent)]
public void UnstagingUnknownPathsWithStrictUnmatchedExplicitPathsValidationThrows(string relativePath, FileStatus currentStatus)
{
using (var repo = new Repository(SandboxStandardTestRepo()))
{
Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath));
Assert.Throws<UnmatchedPathException>(() => repo.Unstage(relativePath, new ExplicitPathsOptions()));
}
}
[Theory]
[InlineData("new_untracked_file.txt", FileStatus.Untracked)]
[InlineData("where-am-I.txt", FileStatus.Nonexistent)]
public void CanUnstageUnknownPathsWithLaxUnmatchedExplicitPathsValidation(string relativePath, FileStatus currentStatus)
{
using (var repo = new Repository(SandboxStandardTestRepo()))
{
Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath));
Assert.DoesNotThrow(() => repo.Unstage(relativePath, new ExplicitPathsOptions() { ShouldFailOnUnmatchedPath = false }));
Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath));
}
}
[Fact]
public void CanUnstageTheRemovalOfAFile()
{
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
int count = repo.Index.Count;
const string filename = "deleted_staged_file.txt";
string fullPath = Path.Combine(repo.Info.WorkingDirectory, filename);
Assert.False(File.Exists(fullPath));
Assert.Equal(FileStatus.Removed, repo.RetrieveStatus(filename));
repo.Unstage(filename);
Assert.Equal(count + 1, repo.Index.Count);
Assert.Equal(FileStatus.Missing, repo.RetrieveStatus(filename));
}
}
[Fact]
public void CanUnstageUntrackedFileAgainstAnOrphanedHead()
{
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
const string relativePath = "a.txt";
Touch(repo.Info.WorkingDirectory, relativePath, "hello test file\n");
repo.Stage(relativePath);
repo.Unstage(relativePath);
RepositoryStatus status = repo.RetrieveStatus();
Assert.Equal(0, status.Staged.Count());
Assert.Equal(1, status.Untracked.Count());
Assert.Throws<UnmatchedPathException>(() => repo.Unstage("i-dont-exist", new ExplicitPathsOptions()));
}
}
[Theory]
[InlineData("new_untracked_file.txt", FileStatus.Untracked)]
[InlineData("where-am-I.txt", FileStatus.Nonexistent)]
public void UnstagingUnknownPathsAgainstAnOrphanedHeadWithStrictUnmatchedExplicitPathsValidationThrows(string relativePath, FileStatus currentStatus)
{
using (var repo = new Repository(SandboxStandardTestRepo()))
{
repo.Refs.UpdateTarget("HEAD", "refs/heads/orphaned");
Assert.True(repo.Info.IsHeadUnborn);
Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath));
Assert.Throws<UnmatchedPathException>(() => repo.Unstage(relativePath, new ExplicitPathsOptions()));
}
}
[Theory]
[InlineData("new_untracked_file.txt", FileStatus.Untracked)]
[InlineData("where-am-I.txt", FileStatus.Nonexistent)]
public void CanUnstageUnknownPathsAgainstAnOrphanedHeadWithLaxUnmatchedExplicitPathsValidation(string relativePath, FileStatus currentStatus)
{
using (var repo = new Repository(SandboxStandardTestRepo()))
{
repo.Refs.UpdateTarget("HEAD", "refs/heads/orphaned");
Assert.True(repo.Info.IsHeadUnborn);
Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath));
Assert.DoesNotThrow(() => repo.Unstage(relativePath));
Assert.DoesNotThrow(() => repo.Unstage(relativePath, new ExplicitPathsOptions { ShouldFailOnUnmatchedPath = false }));
Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath));
}
}
[Fact]
public void UnstagingANewFileWithAFullPathWhichEscapesOutOfTheWorkingDirThrows()
{
SelfCleaningDirectory scd = BuildSelfCleaningDirectory();
string path = SandboxStandardTestRepo();
using (var repo = new Repository(path))
{
DirectoryInfo di = Directory.CreateDirectory(scd.DirectoryPath);
const string filename = "unit_test.txt";
string fullPath = Touch(di.FullName, filename, "some contents");
Assert.Throws<ArgumentException>(() => repo.Unstage(fullPath));
}
}
[Fact]
public void UnstagingANewFileWithAFullPathWhichEscapesOutOfTheWorkingDirAgainstAnOrphanedHeadThrows()
{
SelfCleaningDirectory scd = BuildSelfCleaningDirectory();
string repoPath = InitNewRepository();
using (var repo = new Repository(repoPath))
{
DirectoryInfo di = Directory.CreateDirectory(scd.DirectoryPath);
const string filename = "unit_test.txt";
string fullPath = Touch(di.FullName, filename, "some contents");
Assert.Throws<ArgumentException>(() => repo.Unstage(fullPath));
}
}
[Fact]
public void UnstagingFileWithBadParamsThrows()
{
var path = SandboxStandardTestRepoGitDir();
using (var repo = new Repository(path))
{
Assert.Throws<ArgumentException>(() => repo.Unstage(string.Empty));
Assert.Throws<ArgumentNullException>(() => repo.Unstage((string)null));
Assert.Throws<ArgumentException>(() => repo.Unstage(new string[] { }));
Assert.Throws<ArgumentException>(() => repo.Unstage(new string[] { null }));
}
}
[Fact]
public void CanUnstageSourceOfARename()
{
using (var repo = new Repository(SandboxStandardTestRepo()))
{
repo.Move("branch_file.txt", "renamed_branch_file.txt");
RepositoryStatus oldStatus = repo.RetrieveStatus();
Assert.Equal(1, oldStatus.RenamedInIndex.Count());
Assert.Equal(FileStatus.Nonexistent, oldStatus["branch_file.txt"].State);
Assert.Equal(FileStatus.RenamedInIndex, oldStatus["renamed_branch_file.txt"].State);
repo.Unstage(new string[] { "branch_file.txt" });
RepositoryStatus newStatus = repo.RetrieveStatus();
Assert.Equal(0, newStatus.RenamedInIndex.Count());
Assert.Equal(FileStatus.Missing, newStatus["branch_file.txt"].State);
Assert.Equal(FileStatus.Added, newStatus["renamed_branch_file.txt"].State);
}
}
[Fact]
public void CanUnstageTargetOfARename()
{
using (var repo = new Repository(SandboxStandardTestRepo()))
{
repo.Move("branch_file.txt", "renamed_branch_file.txt");
RepositoryStatus oldStatus = repo.RetrieveStatus();
Assert.Equal(1, oldStatus.RenamedInIndex.Count());
Assert.Equal(FileStatus.RenamedInIndex, oldStatus["renamed_branch_file.txt"].State);
repo.Unstage(new string[] { "renamed_branch_file.txt" });
RepositoryStatus newStatus = repo.RetrieveStatus();
Assert.Equal(0, newStatus.RenamedInIndex.Count());
Assert.Equal(FileStatus.Untracked, newStatus["renamed_branch_file.txt"].State);
Assert.Equal(FileStatus.Removed, newStatus["branch_file.txt"].State);
}
}
[Fact]
public void CanUnstageBothSidesOfARename()
{
using (var repo = new Repository(SandboxStandardTestRepo()))
{
repo.Move("branch_file.txt", "renamed_branch_file.txt");
repo.Unstage(new string[] { "branch_file.txt", "renamed_branch_file.txt" });
RepositoryStatus status = repo.RetrieveStatus();
Assert.Equal(FileStatus.Missing, status["branch_file.txt"].State);
Assert.Equal(FileStatus.Untracked, status["renamed_branch_file.txt"].State);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Common;
using HydraPaper.Properties;
using Ookii.Dialogs;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
namespace HydraPaper
{
public partial class frmMain : Form
{
private VistaFolderBrowserDialog dlgVistaFolder;
private JobArguments jobArguments;
private System.Timers.Timer timDisplaySettingsChanged;
private System.Windows.Forms.Timer timCMSStatus;
private System.Windows.Forms.Timer timTraySingleClick;
private HPTimer timRotate;
private ApplicationStates AppState = ApplicationStates.Configuration;
private AsyncOperation asyncOp;
private bool previousAeroState = false;
public frmMain()
{
InitializeComponent();
Microsoft.Win32.SystemEvents.DisplaySettingsChanged += new EventHandler(SystemEvents_DisplaySettingsChanged);
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
this.dlgVistaFolder = new VistaFolderBrowserDialog();
this.jobArguments = new JobArguments();
this.previousAeroState = AeroCheck.AeroEnabled;
Program.DebugMessage("Starting with Aero: " + (this.previousAeroState ? "true" : "false"));
this.SetupControls();
this.LoadSettings();
if (SystemInformation.TerminalServerSession)
{
this.ConfigureForStatus(StateCommands.Remote);
}
else
{
this.ConfigureForStatus(StateCommands.StartRotation);
}
}
private void SetupControls()
{
this.Icon = Icons.HydraIconForm;
// Manually build the item list to match the enumeration
this.cmbSSIImageSize.Items.Clear();
this.cmbMSIImageSize.Items.Clear();
this.cmbSSIImageSize.ValueMember = this.cmbMSIImageSize.ValueMember = "ID";
this.cmbSSIImageSize.DisplayMember = this.cmbMSIImageSize.DisplayMember = "Text";
List<object> behaviors = new List<object>();
behaviors.Add(new { ID = (int)ImageBehavior.TouchInside, Text = ImageBehavior.TouchInside });
behaviors.Add(new { ID = (int)ImageBehavior.TouchOutside, Text = ImageBehavior.TouchOutside });
behaviors.Add(new { ID = (int)ImageBehavior.Stretch, Text = ImageBehavior.Stretch });
behaviors.Add(new { ID = (int)ImageBehavior.Center, Text = ImageBehavior.Center });
this.cmbSSIImageSize.DataSource = behaviors;
behaviors = new List<object>();
behaviors.Add(new { ID = (int)ImageBehavior.TouchInside, Text = ImageBehavior.TouchInside });
behaviors.Add(new { ID = (int)ImageBehavior.TouchOutside, Text = ImageBehavior.TouchOutside });
behaviors.Add(new { ID = (int)ImageBehavior.Stretch, Text = ImageBehavior.Stretch });
behaviors.Add(new { ID = (int)ImageBehavior.Center, Text = ImageBehavior.Center });
this.cmbMSIImageSize.DataSource = behaviors;
this.timRotate = new HPTimer(60000); // Timer with a default of 1 minute
this.timRotate.Elapsed = timRotate_Elapsed;
this.timDisplaySettingsChanged = new System.Timers.Timer(3000);
this.timDisplaySettingsChanged.Elapsed += displayTimer_Elapsed;
this.timDisplaySettingsChanged.AutoReset = false;
this.timCMSStatus = new System.Windows.Forms.Timer();
this.timCMSStatus.Interval = 1000;
this.timCMSStatus.Tick += timCMSStatus_Elapsed;
this.timTraySingleClick = new System.Windows.Forms.Timer();
this.timTraySingleClick.Interval = SystemInformation.DoubleClickTime + 100;
this.timTraySingleClick.Tick += timTraySingleClick_Elapsed;
this.asyncOp = AsyncOperationManager.CreateOperation(null);
this.Text += " v" + FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;
this.WindowState = FormWindowState.Minimized;
}
bool formCanBeVisible = false;
protected override void SetVisibleCore(bool value)
{
if (!formCanBeVisible) value = false;
base.SetVisibleCore(value);
}
public void LoadSettings()
{
// Check validity of configuration and recover if necessary: http://www.codeproject.com/Articles/30216/Handling-Corrupt-user-config-Settings
try
{
var test = Settings.Default.SingleScreenImagePath;
}
catch (System.Configuration.ConfigurationErrorsException ex)
{
string filename = ((System.Configuration.ConfigurationErrorsException)ex.InnerException).Filename;
File.Delete(filename);
Settings.Default.Reload();
}
if (Settings.Default.UpgradeSettings)
{
Settings.Default.Upgrade();
Settings.Default.Reload();
Settings.Default.UpgradeSettings = false;
Settings.Default.Save();
}
this.txtSSIImageFolderPath.Text = Settings.Default.SingleScreenImagePath;
this.txtMSIImageFolderPath.Text = Settings.Default.MultiScreenImagePath;
this.cmbSSIImageSize.SelectedValue = (int)Settings.Default.SingleScreenImageBehavior;
this.cmbMSIImageSize.SelectedValue = (int)Settings.Default.MultiScreenImageBehavior;
this.numRotateMinutes.Value = Math.Min(this.numRotateMinutes.Maximum, Math.Max(this.numRotateMinutes.Minimum, Settings.Default.ChangeInterval));
this.jobArguments.Settings = Settings.Default;
this.jobArguments.RefreshFilesList = true;
}
private void btnExit_Click(object sender, EventArgs e)
{
this.ConfigureForStatus(StateCommands.Exit);
}
private void SaveSettings()
{
Settings.Default.SingleScreenImagePath = this.txtSSIImageFolderPath.Text.Trim();
Settings.Default.MultiScreenImagePath = this.txtMSIImageFolderPath.Text.Trim();
Settings.Default.SingleScreenImageBehavior = (ImageBehavior)this.cmbSSIImageSize.SelectedValue;
Settings.Default.MultiScreenImageBehavior = (ImageBehavior)this.cmbMSIImageSize.SelectedValue;
Settings.Default.ChangeInterval = Convert.ToInt32(this.numRotateMinutes.Value);
Settings.Default.Save();
}
private void btnSSIImageFolderChooser_Click(object sender, EventArgs e)
{
this.ImageFolderChooser(this.txtSSIImageFolderPath);
}
private void btnMSIImageFolderChooser_Click(object sender, EventArgs e)
{
this.ImageFolderChooser(this.txtMSIImageFolderPath);
}
private void ImageFolderChooser(TextBox targetTextBox)
{
this.dlgVistaFolder.Description = "Wallpapers";
this.dlgVistaFolder.ShowNewFolderButton = true;
this.dlgVistaFolder.RootFolder = Environment.SpecialFolder.MyPictures;
string imageFolder = targetTextBox.Text.Trim();
if (!string.IsNullOrEmpty(imageFolder) && Directory.Exists(imageFolder))
{
this.dlgVistaFolder.SelectedPath = imageFolder;
}
else
{
this.dlgVistaFolder.SelectedPath = Environment.GetFolderPath(this.dlgVistaFolder.RootFolder);
}
this.dlgVistaFolder.SelectedPath = this.dlgVistaFolder.SelectedPath.TrimEnd('\\') + "\\";
if (this.dlgVistaFolder.ShowDialog() == DialogResult.OK)
{
targetTextBox.Text = this.dlgVistaFolder.SelectedPath;
this.jobArguments.RefreshFilesList = true;
}
}
private void btnChangeNow_Click(object sender, EventArgs e)
{
this.ConfigureForStatus(StateCommands.ShowNext);
}
public void UpdateWallPaper()
{
//Program.DebugMessage("Triggering Wallpaper update");
this.timDisplaySettingsChanged.Stop();
this.SaveSettings();
if (!this.bwWallPaper.IsBusy)
{
this.bwWallPaper.RunWorkerAsync(this.jobArguments);
this.lblWorking.Visible = true;
}
}
internal void CleanEvents()
{
Microsoft.Win32.SystemEvents.DisplaySettingsChanged -= new EventHandler(SystemEvents_DisplaySettingsChanged);
Microsoft.Win32.SystemEvents.SessionSwitch -= new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
}
private void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
{
Program.DebugMessage("Detected Display Setting Change. Starting timer for delayed rotation");
if (this.timDisplaySettingsChanged.Enabled) this.timDisplaySettingsChanged.Stop();
this.timDisplaySettingsChanged.Start(); // We do this on a timer so other events can have a chance to cancel the timer and prevent the display change from updating the wallpaper
}
/// <summary>
/// Runs on a separate thread so we need to sync with the form thread
/// </summary>
private void timRotate_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.asyncOp.Post((state) => {
Program.DebugMessage("Rotation timer elapsed.");
this.UpdateWallPaper();
}, null);
}
/// <summary>
/// Runs on a separate thread so we need to sync with the form thread
/// </summary>
private void displayTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.asyncOp.Post((state) =>
{
// Detect if the change was to a low graphics mode which indicates a video game or remote session (VNC) and we should suspend the timer
if (this.previousAeroState != AeroCheck.AeroEnabled)
{
this.previousAeroState = AeroCheck.AeroEnabled;
if (!this.previousAeroState)
{
Program.DebugMessage("Detected low graphics change. Moved to Remote state");
this.ConfigureForStatus(StateCommands.Remote);
return;
}
}
// Aero didn't change (some other display property changed) or aero was enabled so go ahead and rotate the wallpaper so it is updated to match the new
// display settings
Program.DebugMessage("State Update triggered by graphics change.");
this.ConfigureForStatus(StateCommands.DisplayChange);
}, null);
}
private void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
switch (e.Reason)
{
case Microsoft.Win32.SessionSwitchReason.SessionLock:
case Microsoft.Win32.SessionSwitchReason.RemoteConnect:
case Microsoft.Win32.SessionSwitchReason.SessionRemoteControl:
Program.DebugMessage($"Detected {(SystemInformation.TerminalServerSession ? "remote session" : "workstation lock")}. Terminal: {SystemInformation.TerminalServerSession}");
if (SystemInformation.TerminalServerSession)
{
this.ConfigureForStatus(StateCommands.Remote);
}
else {
this.ConfigureForStatus(StateCommands.Lock);
}
break;
case Microsoft.Win32.SessionSwitchReason.ConsoleConnect: // triggers after a remote desktop session
case Microsoft.Win32.SessionSwitchReason.SessionUnlock:
if (SystemInformation.TerminalServerSession)
{
Program.DebugMessage($"Detected remote end. Terminal: {SystemInformation.TerminalServerSession}");
this.ConfigureForStatus(StateCommands.Remote);
}
else
{
Program.DebugMessage($"Detected unlock. Terminal: {SystemInformation.TerminalServerSession}");
this.ConfigureForStatus(StateCommands.Pause);
this.ConfigureForStatus(StateCommands.StartRotation);
}
break;
default:
break;
}
}
private void bwWallPaper_DoWork(object sender, DoWorkEventArgs e)
{
JobArguments settings = e.Argument as JobArguments;
WallPaperBuilder.BuildWallPaper(settings);
}
private void bwWallPaper_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.lblWorking.Visible = false;
this.lbImagesUsed.Items.Clear();
foreach (var fileName in this.jobArguments.FileNamesUsed)
{
this.lbImagesUsed.Items.Add(fileName);
}
}
private void btnStart_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
this.jobArguments.RefreshFilesList = true;
this.ConfigureForStatus(StateCommands.StartRotation);
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
this.ConfigureForStatus(StateCommands.Configure);
}
private void frmMain_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.formCanBeVisible = false;
this.Hide();
}
}
private void niTray_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
this.timTraySingleClick.Stop(); // Prevent the two single clicks from triggering wallpaper rotations
this.openToolStripMenuItem_Click(null, null);
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
this.SaveSettings();
}
private void startStopStripMenuItem_Click(object sender, EventArgs e)
{
if (this.AppState == ApplicationStates.RotateWallpaper)
{
this.ConfigureForStatus(StateCommands.Pause);
}
else
{
this.ConfigureForStatus(StateCommands.StartRotation);
}
}
private void blankToolStripMenuItem_Click(object sender, EventArgs e)
{
this.ConfigureForStatus(StateCommands.Blank);
}
private void cmsTray_Opening(object sender, CancelEventArgs e)
{
this.statusToolStripMenuItem.Text = this.GetStatusMessage();
}
private string GetStatusMessage()
{
string statusText = "Unknown";
switch (this.AppState)
{
case ApplicationStates.RotateWallpaper:
var timeRemaining = new TimeSpan(0, 0, 0, 0, Convert.ToInt32(this.timRotate.MillisecondsRemaining));
statusText = $"Next wallpaper in {timeRemaining.Minutes}m {timeRemaining.Seconds}s";
break;
case ApplicationStates.Remote:
statusText = "Remote";
break;
case ApplicationStates.Locked:
statusText = "Locked";
break;
case ApplicationStates.Paused:
statusText = "Stopped";
break;
case ApplicationStates.Blanked:
statusText = "Blanked";
break;
case ApplicationStates.Configuration:
statusText = "Stopped";
break;
default:
break;
}
return statusText;
}
/// <summary>
/// Restarts the rotation, also causes the wallpaper to be rotated immediately
/// </summary>
private void nextToolStripMenuItem_Click(object sender, EventArgs e)
{
this.ConfigureForStatus(StateCommands.ShowNext);
}
/// <summary>
/// A tray icon single left click on the tray icon starts a timer to rotate the wallpaper. Setting a timer allows a double click to prevent the rotation and open the app instead.
/// </summary>
private void niTray_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
timTraySingleClick.Start();
}
}
private void cmsTray_VisibleChanged(object sender, EventArgs e)
{
var cms = sender as ContextMenuStrip;
if (cms.Visible)
{
this.timCMSStatus.Start();
}
else
{
this.timCMSStatus.Stop();
}
}
void timCMSStatus_Elapsed(object sender, System.EventArgs e)
{
this.cmsTray_Opening(null, null);
}
/// <summary>
/// A Single click on the tray (after a delay to watch for double clicks) makes the wallpaper rotate
/// </summary>
void timTraySingleClick_Elapsed(object sender, System.EventArgs e)
{
timTraySingleClick.Stop();
nextToolStripMenuItem_Click(null, null);
}
private void ConfigureForStatus(StateCommands command)
{
if (command == StateCommands.Blank)
{
Program.DebugMessage("Command: Blank");
if (this.AppState != ApplicationStates.Remote)
{
this.AppState = ApplicationStates.Blanked; // If in remote state don't change, but still blank the screen
this.SaveSettings();
this.niTray.Icon = Icons.HydraBlankIcon.ToIcon();
this.niTray.Text = this.GetStatusMessage();
}
this.startStopStripMenuItem.Text = "Start";
this.nextToolStripMenuItem.Enabled = false;
this.timDisplaySettingsChanged.Stop();
this.timTraySingleClick.Stop();
this.timRotate.Stop();
CSSetDesktopWallpaper.SolidColor.SetColor(Color.Black);
}
else if (command == StateCommands.Lock)
{
Program.DebugMessage("Command: Lock");
this.AppState = ApplicationStates.Locked;
this.SaveSettings();
this.startStopStripMenuItem.Enabled = true;
this.nextToolStripMenuItem.Enabled = true;
this.timDisplaySettingsChanged.Stop();
this.timTraySingleClick.Stop();
this.timRotate.Stop();
this.niTray.Icon = Icons.HydraBlankIcon.ToIcon();
this.niTray.Text = this.GetStatusMessage();
CSSetDesktopWallpaper.SolidColor.SetColor(Color.Black);
}
else if (command == StateCommands.Pause)
{
Program.DebugMessage("Command: Pause");
this.AppState = ApplicationStates.Paused;
this.SaveSettings();
this.startStopStripMenuItem.Text = "Start";
this.timDisplaySettingsChanged.Stop();
this.timRotate.Stop();
this.timTraySingleClick.Stop();
this.niTray.Icon = Icons.HydraStoppedIcon;
this.niTray.Text = this.GetStatusMessage();
}
else if (command == StateCommands.Remote)
{
Program.DebugMessage("Command: Remote");
this.AppState = ApplicationStates.Remote;
this.SaveSettings();
this.startStopStripMenuItem.Text = "Start";
this.startStopStripMenuItem.Enabled = false;
this.nextToolStripMenuItem.Enabled = false;
this.timDisplaySettingsChanged.Stop();
this.timTraySingleClick.Stop();
this.timRotate.Stop();
this.niTray.Icon = Icons.HydraRemoteIcon.ToIcon();
this.niTray.Text = this.GetStatusMessage();
CSSetDesktopWallpaper.SolidColor.SetColor(Color.Black);
}
else if (command == StateCommands.ShowNext)
{
Program.DebugMessage("Command: ShowNext");
if (this.AppState == ApplicationStates.RotateWallpaper || this.AppState == ApplicationStates.Paused || this.AppState == ApplicationStates.Configuration)
{
this.timRotate.Stop();
this.UpdateWallPaper();
if (this.AppState == ApplicationStates.RotateWallpaper)
{
this.timRotate.Start();
}
}
}
else if (command == StateCommands.DisplayChange)
{
Program.DebugMessage("Command: DisplayChange");
if (this.AppState == ApplicationStates.Remote && !System.Windows.Forms.SystemInformation.TerminalServerSession)
{
this.AppState = ApplicationStates.Paused;
command = StateCommands.StartRotation;
}
else
{
if (this.AppState == ApplicationStates.Remote || this.AppState == ApplicationStates.Blanked || this.AppState == ApplicationStates.Locked)
{
return;
}
if (this.AppState == ApplicationStates.Paused)
{
// They don't want to rotate but now the background is going to be messed up so just blank.
CSSetDesktopWallpaper.SolidColor.SetColor(Color.Black);
}
else
{
this.timRotate.Stop();
this.timTraySingleClick.Stop();
this.UpdateWallPaper();
if (this.AppState == ApplicationStates.RotateWallpaper)
{
this.timRotate.Start();
}
}
}
}
else if (command == StateCommands.Configure)
{
Program.DebugMessage("Command: Configure");
this.AppState = ApplicationStates.Configuration;
this.timRotate.Stop();
this.timDisplaySettingsChanged.Stop();
this.timTraySingleClick.Stop();
this.niTray.Icon = Icons.HydraStoppedIcon;
this.niTray.Text = this.GetStatusMessage();
this.formCanBeVisible = true;
this.Show();
this.WindowState = FormWindowState.Normal;
}
else if (command == StateCommands.Exit)
{
try
{
Program.DebugMessage("Command: Exit");
this.AppState = ApplicationStates.Paused;
this.startStopStripMenuItem.Text = "Start";
this.timDisplaySettingsChanged.Stop();
this.timRotate.Stop();
this.timTraySingleClick.Stop();
this.niTray.Icon = Icons.HydraStoppedIcon;
this.niTray.Text = this.GetStatusMessage();
this.SaveSettings();
}
catch { }
Application.Exit();
return;
}
// The lack of ELSE IF is to allow another command to change to Start Rotation
if (command == StateCommands.StartRotation)
{
Program.DebugMessage("Command: StartRotation");
if (this.AppState == ApplicationStates.Remote || this.AppState == ApplicationStates.Locked)
{
return;
}
this.AppState = ApplicationStates.RotateWallpaper;
this.SaveSettings();
this.nextToolStripMenuItem.Enabled = true;
this.startStopStripMenuItem.Enabled = true;
this.startStopStripMenuItem.Text = "Stop";
this.timRotate.Stop();
this.timDisplaySettingsChanged.Stop();
this.timTraySingleClick.Stop();
this.niTray.Icon = Icons.HydraIcon;
this.niTray.Text = "HydraPaper";
this.UpdateWallPaper();
this.timRotate.Interval = Math.Max(Convert.ToInt32(this.numRotateMinutes.Value * 60000), 60000);
this.timRotate.Start();
}
}
private void copyPathToolStripMenuItem_Click(object sender, EventArgs e)
{
var listBox = this.GetContextMenuSourceControl(sender as ToolStripMenuItem) as ListBox;
if (listBox == null || listBox.SelectedItem == null)
{
Program.DebugMessage($"Somehow the menu item was activated without a list box or selected item. The clipboard was cleared.");
Clipboard.Clear();
return;
}
var path = System.IO.Path.GetDirectoryName(listBox.SelectedItem as string);
if (path == null)
{
Program.DebugMessage($"Selected item had no path (null). Clipboard was cleared.");
Clipboard.Clear();
}
else
{
Program.DebugMessage($"Copied selected item path to clipboard: {path}");
Clipboard.SetText(path);
}
}
private void copyFileNameToolStripMenuItem_Click(object sender, EventArgs e)
{
var listBox = this.GetContextMenuSourceControl(sender as ToolStripMenuItem) as ListBox;
if (listBox == null || listBox.SelectedItem == null)
{
Program.DebugMessage($"Somehow the menu item was activated without a list box or selected item. The clipboard was cleared.");
Clipboard.Clear();
return;
}
var fileName = listBox.SelectedItem as string;
if (fileName == null)
{
Program.DebugMessage($"Selected item had no file name (null). Clipboard was cleared.");
Clipboard.Clear();
}
else
{
Program.DebugMessage($"Copied selected item to clipboard: {fileName}");
Clipboard.SetText(fileName);
}
}
private void openImageToolStripMenuItem_Click(object sender, EventArgs e)
{
var listBox = this.GetContextMenuSourceControl(sender as ToolStripMenuItem) as ListBox;
if (listBox == null || listBox.SelectedItem == null)
{
Program.DebugMessage($"Somehow the menu item was activated without a list box or selected item.");
MessageBox.Show("Unable to open image. You may not have permissions or it may no longer exist.", "Error Opening Image", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var fileName = listBox.SelectedItem as string;
if (!this.OpenImage(fileName))
{
MessageBox.Show("Unable to open image. You may not have permissions or it may no longer exist.", "Error Opening Image", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void openFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
var listBox = this.GetContextMenuSourceControl(sender as ToolStripMenuItem) as ListBox;
if (listBox == null || listBox.SelectedItem == null)
{
Program.DebugMessage($"Somehow the menu item was activated without a list box or selected item.");
MessageBox.Show("Unable to open folder. You may not have permissions or it may no longer exist.", "Error Opening Folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var path = System.IO.Path.GetDirectoryName(listBox.SelectedItem as string);
if (string.IsNullOrEmpty(path) || !System.IO.Directory.Exists(path))
{
MessageBox.Show("Unable to open folder. You may not have permissions or it may no longer exist.", "Error Opening Folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
try
{
var fullPath = listBox.SelectedItem as string;
var arguments = $"/select, {EscapeCommandArguments(fullPath)}";
var expProcess = new Process() {
StartInfo = new ProcessStartInfo() {
FileName = "explorer.exe",
WorkingDirectory = path,
UseShellExecute = true,
Arguments = arguments
}
};
Program.DebugMessage($"Opening image '{fullPath}' folder. Launching process {expProcess.StartInfo.FileName} {expProcess.StartInfo.Arguments}.");
expProcess.Start();
}
catch (Exception)
{
MessageBox.Show("Unable to open folder. You may not have permissions or it may no longer exist.", "Error Opening Folder", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void cmsImagesUsed_Opening(object sender, CancelEventArgs e)
{
var cms = sender as ContextMenuStrip;
if (cms == null) return;
var listBox = cms.SourceControl as ListBox;
if (listBox == null)
{
e.Cancel = true;
return;
}
var listItem = listBox.SelectedItem as string;
if (listItem == null)
{
e.Cancel = true;
return;
}
}
private void lbImagesUsed_MouseDown(object sender, MouseEventArgs e)
{
var listBox = sender as ListBox;
if (listBox == null) return;
var listItemIndex = listBox.IndexFromPoint(e.Location);
listBox.SelectedIndex = listItemIndex;
}
private void lbImagesUsed_DoubleClick(object sender, EventArgs e)
{
var listBox = sender as ListBox;
if (listBox == null || listBox.SelectedItem == null) return;
var fileName = listBox.SelectedItem as string;
if (!this.OpenImage(fileName))
{
MessageBox.Show("Unable to open image. You may not have permissions or it may no longer exist.", "Error Opening Image", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void lbImagesUsed_KeyUp(object sender, KeyEventArgs e)
{
var listBox = sender as ListBox;
if (listBox == null)
{
return;
}
if (e.KeyCode == Keys.Enter && e.Modifiers == Keys.None)
{
if (listBox.SelectedIndex >= 0)
{
e.Handled = true;
this.lbImagesUsed_DoubleClick(listBox, e);
}
}
}
private bool OpenImage(string fullPath)
{
if (!string.IsNullOrEmpty(fullPath) && System.IO.File.Exists(fullPath))
{
try
{
new Process() { StartInfo = new ProcessStartInfo(fullPath) { UseShellExecute = true } }.Start();
return true;
}
catch { }
}
return false;
}
private Control GetContextMenuSourceControl(ToolStripMenuItem menuItem)
{
if (menuItem == null) return null;
var parentMenu = menuItem.GetCurrentParent(); // Not sure if this handles nested menus but it'll work for now
if (parentMenu is ContextMenuStrip)
{
return (parentMenu as ContextMenuStrip).SourceControl;
}
return null;
}
private string EscapeCommandArguments(string input)
{
// https://stackoverflow.com/a/6040946/5583585
return "\"" + Regex.Replace(input, @"(\\+)$", @"$1$1") + "\"";
}
}
public static class Ext
{
public static Icon ToIcon(this Bitmap bitMap)
{
return Icon.FromHandle(bitMap.GetHicon());
}
}
}
| |
// Copyright 2018 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 Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.ErrorReporting.V1Beta1
{
/// <summary>
/// Settings for a <see cref="ErrorStatsServiceClient"/>.
/// </summary>
public sealed partial class ErrorStatsServiceSettings : ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="ErrorStatsServiceSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="ErrorStatsServiceSettings"/>.
/// </returns>
public static ErrorStatsServiceSettings GetDefault() => new ErrorStatsServiceSettings();
/// <summary>
/// Constructs a new <see cref="ErrorStatsServiceSettings"/> object with default settings.
/// </summary>
public ErrorStatsServiceSettings() { }
private ErrorStatsServiceSettings(ErrorStatsServiceSettings existing) : base(existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListGroupStatsSettings = existing.ListGroupStatsSettings;
ListEventsSettings = existing.ListEventsSettings;
DeleteEventsSettings = existing.DeleteEventsSettings;
OnCopy(existing);
}
partial void OnCopy(ErrorStatsServiceSettings existing);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="ErrorStatsServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> IdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="ErrorStatsServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods.
/// </remarks>
public static Predicate<RpcException> NonIdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes();
/// <summary>
/// "Default" retry backoff for <see cref="ErrorStatsServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="ErrorStatsServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="ErrorStatsServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 60000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.3</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(100),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// "Default" timeout backoff for <see cref="ErrorStatsServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="ErrorStatsServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="ErrorStatsServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Maximum timeout: 20000 milliseconds</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(20000),
maxDelay: TimeSpan.FromMilliseconds(20000),
delayMultiplier: 1.0
);
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>ErrorStatsServiceClient.ListGroupStats</c> and <c>ErrorStatsServiceClient.ListGroupStatsAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>ErrorStatsServiceClient.ListGroupStats</c> and
/// <c>ErrorStatsServiceClient.ListGroupStatsAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 20000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings ListGroupStatsSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>ErrorStatsServiceClient.ListEvents</c> and <c>ErrorStatsServiceClient.ListEventsAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>ErrorStatsServiceClient.ListEvents</c> and
/// <c>ErrorStatsServiceClient.ListEventsAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 20000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings ListEventsSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>ErrorStatsServiceClient.DeleteEvents</c> and <c>ErrorStatsServiceClient.DeleteEventsAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>ErrorStatsServiceClient.DeleteEvents</c> and
/// <c>ErrorStatsServiceClient.DeleteEventsAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 20000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 20000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings DeleteEventsSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="ErrorStatsServiceSettings"/> object.</returns>
public ErrorStatsServiceSettings Clone() => new ErrorStatsServiceSettings(this);
}
/// <summary>
/// ErrorStatsService client wrapper, for convenient use.
/// </summary>
public abstract partial class ErrorStatsServiceClient
{
/// <summary>
/// The default endpoint for the ErrorStatsService service, which is a host of "clouderrorreporting.googleapis.com" and a port of 443.
/// </summary>
public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("clouderrorreporting.googleapis.com", 443);
/// <summary>
/// The default ErrorStatsService scopes.
/// </summary>
/// <remarks>
/// The default ErrorStatsService scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// </list>
/// </remarks>
public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
});
private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes);
// Note: we could have parameterless overloads of Create and CreateAsync,
// documented to just use the default endpoint, settings and credentials.
// Pros:
// - Might be more reassuring on first use
// - Allows method group conversions
// Con: overloads!
/// <summary>
/// Asynchronously creates a <see cref="ErrorStatsServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="ErrorStatsServiceSettings"/>.</param>
/// <returns>The task representing the created <see cref="ErrorStatsServiceClient"/>.</returns>
public static async Task<ErrorStatsServiceClient> CreateAsync(ServiceEndpoint endpoint = null, ErrorStatsServiceSettings settings = null)
{
Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="ErrorStatsServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="ErrorStatsServiceSettings"/>.</param>
/// <returns>The created <see cref="ErrorStatsServiceClient"/>.</returns>
public static ErrorStatsServiceClient Create(ServiceEndpoint endpoint = null, ErrorStatsServiceSettings settings = null)
{
Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="ErrorStatsServiceClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="ErrorStatsServiceSettings"/>.</param>
/// <returns>The created <see cref="ErrorStatsServiceClient"/>.</returns>
public static ErrorStatsServiceClient Create(Channel channel, ErrorStatsServiceSettings settings = null)
{
GaxPreconditions.CheckNotNull(channel, nameof(channel));
ErrorStatsService.ErrorStatsServiceClient grpcClient = new ErrorStatsService.ErrorStatsServiceClient(channel);
return new ErrorStatsServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, ErrorStatsServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, ErrorStatsServiceSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, ErrorStatsServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, ErrorStatsServiceSettings)"/> will create new channels, which could
/// in turn be shut down by another call to this method.</remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC ErrorStatsService client.
/// </summary>
public virtual ErrorStatsService.ErrorStatsServiceClient GrpcClient
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="projectName">
/// [Required] The resource name of the Google Cloud Platform project. Written
/// as <code>projects/</code> plus the
/// <a href="https://support.google.com/cloud/answer/6158840">Google Cloud
/// Platform project ID</a>.
///
/// Example: <code>projects/my-project-123</code>.
/// </param>
/// <param name="timeRange">
/// [Optional] List data for the given time range.
/// If not set a default time range is used. The field time_range_begin
/// in the response will specify the beginning of this time range.
/// Only <code>ErrorGroupStats</code> with a non-zero count in the given time
/// range are returned, unless the request contains an explicit group_id list.
/// If a group_id list is given, also <code>ErrorGroupStats</code> with zero
/// occurrences are returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources.
/// </returns>
public virtual PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync(
ProjectName projectName,
QueryTimeRange timeRange,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null) => ListGroupStatsAsync(
new ListGroupStatsRequest
{
ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
TimeRange = GaxPreconditions.CheckNotNull(timeRange, nameof(timeRange)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
},
callSettings);
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="projectName">
/// [Required] The resource name of the Google Cloud Platform project. Written
/// as <code>projects/</code> plus the
/// <a href="https://support.google.com/cloud/answer/6158840">Google Cloud
/// Platform project ID</a>.
///
/// Example: <code>projects/my-project-123</code>.
/// </param>
/// <param name="timeRange">
/// [Optional] List data for the given time range.
/// If not set a default time range is used. The field time_range_begin
/// in the response will specify the beginning of this time range.
/// Only <code>ErrorGroupStats</code> with a non-zero count in the given time
/// range are returned, unless the request contains an explicit group_id list.
/// If a group_id list is given, also <code>ErrorGroupStats</code> with zero
/// occurrences are returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="ErrorGroupStats"/> resources.
/// </returns>
public virtual PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats(
ProjectName projectName,
QueryTimeRange timeRange,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null) => ListGroupStats(
new ListGroupStatsRequest
{
ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
TimeRange = GaxPreconditions.CheckNotNull(timeRange, nameof(timeRange)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
},
callSettings);
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources.
/// </returns>
public virtual PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync(
ListGroupStatsRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="ErrorGroupStats"/> resources.
/// </returns>
public virtual PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats(
ListGroupStatsRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="projectName">
/// [Required] The resource name of the Google Cloud Platform project. Written
/// as `projects/` plus the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="groupId">
/// [Required] The group for which events shall be returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources.
/// </returns>
public virtual PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync(
ProjectName projectName,
string groupId,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null) => ListEventsAsync(
new ListEventsRequest
{
ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
GroupId = GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
},
callSettings);
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="projectName">
/// [Required] The resource name of the Google Cloud Platform project. Written
/// as `projects/` plus the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="groupId">
/// [Required] The group for which events shall be returned.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request.
/// A value of <c>null</c> or an empty string retrieves the first page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller.
/// A value of <c>null</c> or 0 uses a server-defined page size.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="ErrorEvent"/> resources.
/// </returns>
public virtual PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents(
ProjectName projectName,
string groupId,
string pageToken = null,
int? pageSize = null,
CallSettings callSettings = null) => ListEvents(
new ListEventsRequest
{
ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
GroupId = GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
},
callSettings);
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources.
/// </returns>
public virtual PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync(
ListEventsRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="ErrorEvent"/> resources.
/// </returns>
public virtual PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents(
ListEventsRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="projectName">
/// [Required] The resource name of the Google Cloud Platform project. Written
/// as `projects/` plus the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<DeleteEventsResponse> DeleteEventsAsync(
ProjectName projectName,
CallSettings callSettings = null) => DeleteEventsAsync(
new DeleteEventsRequest
{
ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
},
callSettings);
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="projectName">
/// [Required] The resource name of the Google Cloud Platform project. Written
/// as `projects/` plus the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<DeleteEventsResponse> DeleteEventsAsync(
ProjectName projectName,
CancellationToken cancellationToken) => DeleteEventsAsync(
projectName,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="projectName">
/// [Required] The resource name of the Google Cloud Platform project. Written
/// as `projects/` plus the
/// [Google Cloud Platform project
/// ID](https://support.google.com/cloud/answer/6158840).
/// Example: `projects/my-project-123`.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual DeleteEventsResponse DeleteEvents(
ProjectName projectName,
CallSettings callSettings = null) => DeleteEvents(
new DeleteEventsRequest
{
ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)),
},
callSettings);
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<DeleteEventsResponse> DeleteEventsAsync(
DeleteEventsRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual DeleteEventsResponse DeleteEvents(
DeleteEventsRequest request,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
}
/// <summary>
/// ErrorStatsService client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class ErrorStatsServiceClientImpl : ErrorStatsServiceClient
{
private readonly ApiCall<ListGroupStatsRequest, ListGroupStatsResponse> _callListGroupStats;
private readonly ApiCall<ListEventsRequest, ListEventsResponse> _callListEvents;
private readonly ApiCall<DeleteEventsRequest, DeleteEventsResponse> _callDeleteEvents;
/// <summary>
/// Constructs a client wrapper for the ErrorStatsService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ErrorStatsServiceSettings"/> used within this client </param>
public ErrorStatsServiceClientImpl(ErrorStatsService.ErrorStatsServiceClient grpcClient, ErrorStatsServiceSettings settings)
{
GrpcClient = grpcClient;
ErrorStatsServiceSettings effectiveSettings = settings ?? ErrorStatsServiceSettings.GetDefault();
ClientHelper clientHelper = new ClientHelper(effectiveSettings);
_callListGroupStats = clientHelper.BuildApiCall<ListGroupStatsRequest, ListGroupStatsResponse>(
GrpcClient.ListGroupStatsAsync, GrpcClient.ListGroupStats, effectiveSettings.ListGroupStatsSettings);
_callListEvents = clientHelper.BuildApiCall<ListEventsRequest, ListEventsResponse>(
GrpcClient.ListEventsAsync, GrpcClient.ListEvents, effectiveSettings.ListEventsSettings);
_callDeleteEvents = clientHelper.BuildApiCall<DeleteEventsRequest, DeleteEventsResponse>(
GrpcClient.DeleteEventsAsync, GrpcClient.DeleteEvents, effectiveSettings.DeleteEventsSettings);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void OnConstruction(ErrorStatsService.ErrorStatsServiceClient grpcClient, ErrorStatsServiceSettings effectiveSettings, ClientHelper clientHelper);
/// <summary>
/// The underlying gRPC ErrorStatsService client.
/// </summary>
public override ErrorStatsService.ErrorStatsServiceClient GrpcClient { get; }
// Partial modifier methods contain '_' to ensure no name conflicts with RPC methods.
partial void Modify_ListGroupStatsRequest(ref ListGroupStatsRequest request, ref CallSettings settings);
partial void Modify_ListEventsRequest(ref ListEventsRequest request, ref CallSettings settings);
partial void Modify_DeleteEventsRequest(ref DeleteEventsRequest request, ref CallSettings settings);
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="ErrorGroupStats"/> resources.
/// </returns>
public override PagedAsyncEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStatsAsync(
ListGroupStatsRequest request,
CallSettings callSettings = null)
{
Modify_ListGroupStatsRequest(ref request, ref callSettings);
return new GrpcPagedAsyncEnumerable<ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>(_callListGroupStats, request, callSettings);
}
/// <summary>
/// Lists the specified groups.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="ErrorGroupStats"/> resources.
/// </returns>
public override PagedEnumerable<ListGroupStatsResponse, ErrorGroupStats> ListGroupStats(
ListGroupStatsRequest request,
CallSettings callSettings = null)
{
Modify_ListGroupStatsRequest(ref request, ref callSettings);
return new GrpcPagedEnumerable<ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>(_callListGroupStats, request, callSettings);
}
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable asynchronous sequence of <see cref="ErrorEvent"/> resources.
/// </returns>
public override PagedAsyncEnumerable<ListEventsResponse, ErrorEvent> ListEventsAsync(
ListEventsRequest request,
CallSettings callSettings = null)
{
Modify_ListEventsRequest(ref request, ref callSettings);
return new GrpcPagedAsyncEnumerable<ListEventsRequest, ListEventsResponse, ErrorEvent>(_callListEvents, request, callSettings);
}
/// <summary>
/// Lists the specified events.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A pageable sequence of <see cref="ErrorEvent"/> resources.
/// </returns>
public override PagedEnumerable<ListEventsResponse, ErrorEvent> ListEvents(
ListEventsRequest request,
CallSettings callSettings = null)
{
Modify_ListEventsRequest(ref request, ref callSettings);
return new GrpcPagedEnumerable<ListEventsRequest, ListEventsResponse, ErrorEvent>(_callListEvents, request, callSettings);
}
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<DeleteEventsResponse> DeleteEventsAsync(
DeleteEventsRequest request,
CallSettings callSettings = null)
{
Modify_DeleteEventsRequest(ref request, ref callSettings);
return _callDeleteEvents.Async(request, callSettings);
}
/// <summary>
/// Deletes all error events of a given project.
/// </summary>
/// <param name="request">
/// The request object containing all of the parameters for the API call.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override DeleteEventsResponse DeleteEvents(
DeleteEventsRequest request,
CallSettings callSettings = null)
{
Modify_DeleteEventsRequest(ref request, ref callSettings);
return _callDeleteEvents.Sync(request, callSettings);
}
}
// Partial classes to enable page-streaming
public partial class ListGroupStatsRequest : IPageRequest { }
public partial class ListGroupStatsResponse : IPageResponse<ErrorGroupStats>
{
/// <summary>
/// Returns an enumerator that iterates through the resources in this response.
/// </summary>
public IEnumerator<ErrorGroupStats> GetEnumerator() => ErrorGroupStats.GetEnumerator();
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public partial class ListEventsRequest : IPageRequest { }
public partial class ListEventsResponse : IPageResponse<ErrorEvent>
{
/// <summary>
/// Returns an enumerator that iterates through the resources in this response.
/// </summary>
public IEnumerator<ErrorEvent> GetEnumerator() => ErrorEvents.GetEnumerator();
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
using System;
namespace Netco.Logging
{
/// <summary>
/// Logger interface to use for logging.
/// </summary>
/// <remarks>Logging providers are expected to implement this.</remarks>
public interface ILogger
{
/// <summary>
/// Logs the trace message.
/// </summary>
/// <param name="message">The message.</param>
void Trace( string message );
/// <summary>
/// Logs the trace message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
void Trace( Exception exception, string message );
/// <summary>
/// Logs the trace message.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Trace( string format, params object[] args );
/// <summary>
/// Logs the trace message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Trace( Exception exception, string format, params object[] args );
/// <summary>
/// Logs the debug message.
/// </summary>
/// <param name="message">The message.</param>
void Debug( string message );
/// <summary>
/// Logs the debug message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
void Debug( Exception exception, string message );
/// <summary>
/// Logs the debug message.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Debug( string format, params object[] args );
/// <summary>
/// Logs the debug message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Debug( Exception exception, string format, params object[] args );
/// <summary>
/// Logs the info message.
/// </summary>
/// <param name="message">The message.</param>
void Info( string message );
/// <summary>
/// Logs the info message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
void Info( Exception exception, string message );
/// <summary>
/// Logs the info message.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Info( string format, params object[] args );
/// <summary>
/// Logs the info message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Info( Exception exception, string format, params object[] args );
/// <summary>
/// Logs the warn message.
/// </summary>
/// <param name="message">The message.</param>
void Warn( string message );
/// <summary>
/// Logs the warn message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
void Warn( Exception exception, string message );
/// <summary>
/// Logs the warn message.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Warn( string format, params object[] args );
/// <summary>
/// Logs the warn message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Warn( Exception exception, string format, params object[] args );
/// <summary>
/// Logs the error message.
/// </summary>
/// <param name="message">The message.</param>
void Error( string message );
/// <summary>
/// Logs the error message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
void Error( Exception exception, string message );
/// <summary>
/// Logs the error message.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Error( string format, params object[] args );
/// <summary>
/// Logs the error message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Error( Exception exception, string format, params object[] args );
/// <summary>
/// Logs the fatal message.
/// </summary>
/// <param name="message">The message.</param>
void Fatal( string message );
/// <summary>
/// Logs the fatal message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="message">The message.</param>
void Fatal( Exception exception, string message );
/// <summary>
/// Logs the fatal message.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Fatal( string format, params object[] args );
/// <summary>
/// Logs the fatal message.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="format">The format string.</param>
/// <param name="args">The format arguments.</param>
void Fatal( Exception exception, string format, params object[] args );
}
/// <summary>
/// Logger factory interface. Supplies logger for each log call.
/// </summary>
/// <remarks>Needs to be implemented by each separate logger provider.</remarks>
public interface ILoggerFactory
{
/// <summary>
/// Gets the logger to log message for the specified type.
/// </summary>
/// <param name="objectToLogType">Type of the object to log.</param>
/// <returns>Logger to log messages for the specified type.</returns>
ILogger GetLogger( Type objectToLogType );
/// <summary>
/// Gets the logger to log message for the specified type.
/// </summary>
/// <param name="loggerName">Name of the logger.</param>
/// <returns> Logger to log messages for the specified type.</returns>
ILogger GetLogger( string loggerName );
}
/// <summary>
/// Extends all objects to support logging.
/// </summary>
public static class LogExtensions
{
/// <summary>
/// Gets the logger for the specified object.
/// </summary>
/// <typeparam name="T">Type of the object for which to get the logger.</typeparam>
/// <param name="needToLogObj">Object to log for.</param>
/// <returns>The logger for the specified object.</returns>
public static ILogger Log< T >( this T needToLogObj )
{
return NetcoLogger.GetLogger( typeof( T ) );
}
/// <summary>
/// Gets the logger with the specified logger name.
/// </summary>
/// <typeparam name="T">Type of the object for which to get the logger.</typeparam>
/// <param name="needToLogObj">Object to log for.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <returns>The logger with the specified name.</returns>
public static ILogger Log< T >( this T needToLogObj, string loggerName )
{
return NetcoLogger.GetLogger( loggerName );
}
}
/// <summary>
/// Provides maing logging support.
/// </summary>
public static class NetcoLogger
{
static NetcoLogger()
{
LoggerFactory = new NullLoggerFactory();
}
/// <summary>
/// Gets or sets the logger factory.
/// </summary>
/// <value>
/// The logger factory that will supply the logger.
/// </value>
public static ILoggerFactory LoggerFactory{ get; set; }
/// <summary>
/// Gets the logger.
/// </summary>
/// <param name="objectToLogType">Type of the object to log.</param>
/// <returns>
/// Logger to log messages for the specified object type.
/// </returns>
public static ILogger GetLogger( Type objectToLogType )
{
return LoggerFactory.GetLogger( objectToLogType );
}
/// <summary>
/// Gets the logger.
/// </summary>
/// <typeparam name="T">Type of the object to log.</typeparam>
/// <returns>
/// Logger to log messages for the specified object type.
/// </returns>
public static ILogger GetLogger< T >()
{
return LoggerFactory.GetLogger( typeof( T ) );
}
/// <summary>
/// Gets the logger.
/// </summary>
/// <param name="loggerName">Name of the logger.</param>
/// <returns>
/// Logger to log messages for the specified object type.
/// </returns>
public static ILogger GetLogger( string loggerName )
{
return LoggerFactory.GetLogger( loggerName );
}
}
}
| |
// 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.IO;
using System.Runtime.CompilerServices;
class ApplicationException : Exception
{
public ApplicationException(string message) : base(message) { }
}
namespace Test
{
public abstract class Base
{
public abstract string AbstractFinal();
public abstract string AbstractOverrideFinal();
public abstract string AbstractOverrideOverride();
public abstract string AbstractOverrideNil();
public virtual string VirtualFinal()
{
return "Base.VirtualFinal";
}
public virtual string VirtualNilFinal()
{
return "Base.VirtualNilFinal";
}
public virtual string VirtualOverrideFinal()
{
return "Base.VirtualOverrideFinal";
}
public virtual string VirtualNilOverride()
{
return "Base.VirtualNilOverride";
}
public virtual string VirtualNilNil()
{
return "Base.VirtualNilNil";
}
public virtual string VirtualOverrideOverride()
{
return "Base.VirtualOverrideOverride";
}
public virtual string VirtualOverrideNil()
{
return "Base.VirtualOverrideNil";
}
}
public class Child : Base
{
public sealed override string AbstractFinal()
{
return "Child.AbstractFinal";
}
public string CallAbstractFinal()
{
return AbstractFinal();
}
public override string AbstractOverrideFinal()
{
return "Child.AbstractOverrideFinal";
}
public override string AbstractOverrideOverride()
{
return "Child.AbstractOverrideOverride";
}
public override string AbstractOverrideNil()
{
return "Child.AbstractOverrideNil";
}
public string CallAbstractOverrideNil()
{
return AbstractOverrideNil();
}
public sealed override string VirtualFinal()
{
return "Child.VirtualFinal";
}
public string CallVirtualFinal()
{
return VirtualFinal();
}
public override string VirtualOverrideFinal()
{
return "Child.VirtualOverrideFinal";
}
public override string VirtualOverrideOverride()
{
return "Child.VirtualOverrideOverride";
}
public override string VirtualOverrideNil()
{
return "Child.VirtualOverrideNil";
}
public string CallVirtualOverrideNil()
{
return VirtualOverrideNil();
}
}
public class GrandChild : Child
{
public sealed override string AbstractOverrideFinal()
{
return "GrandChild.AbstractOverrideFinal";
}
public string CallAbstractOverrideFinal()
{
return AbstractOverrideFinal();
}
public override string AbstractOverrideOverride()
{
return "GrandChild.AbstractOverrideOverride";
}
public string CallAbstractOverrideOverride()
{
return AbstractOverrideOverride();
}
public sealed override string VirtualNilFinal()
{
return "GrandChild.VirtualNilFinal";
}
public string CallVirtualNilFinal()
{
return VirtualNilFinal();
}
public sealed override string VirtualOverrideFinal()
{
return "GrandChild.VirtualOverrideFinal";
}
public string CallVirtualOverrideFinal()
{
return VirtualOverrideFinal();
}
public override string VirtualOverrideOverride()
{
return "GrandChild.VirtualOverrideOverride";
}
public string CallVirtualOverrideOverride()
{
return VirtualOverrideOverride();
}
public override string VirtualNilOverride()
{
return "GrandChild.VirtualNilOverride";
}
public string CallVirtualNilOverride()
{
return VirtualNilOverride();
}
public void TestGrandChild()
{
Console.WriteLine("Call from inside GrandChild");
Assert.AreEqual("Child.AbstractFinal", CallAbstractFinal());
Assert.AreEqual("GrandChild.AbstractOverrideFinal", CallAbstractOverrideFinal());
Assert.AreEqual("GrandChild.AbstractOverrideOverride", CallAbstractOverrideOverride());
Assert.AreEqual("Child.AbstractOverrideNil", CallAbstractOverrideNil());
Assert.AreEqual("Child.VirtualFinal", CallVirtualFinal());
Assert.AreEqual("GrandChild.VirtualOverrideFinal", CallVirtualOverrideFinal());
Assert.AreEqual("GrandChild.VirtualOverrideOverride", CallVirtualOverrideOverride());
Assert.AreEqual("Child.VirtualOverrideNil", CallVirtualOverrideNil());
}
}
public static class Program
{
public static void CallFromInsideGrandChild()
{
GrandChild child = new GrandChild();
child.TestGrandChild();
}
public static int Main(string[] args)
{
try
{
CallFromInsideGrandChild();
Console.WriteLine("Test SUCCESS");
return 100;
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine("Test FAILED");
return 101;
}
}
}
public static class Assert
{
public static void AreEqual(string left, string right)
{
if (String.IsNullOrEmpty(left))
throw new ArgumentNullException("left");
if (string.IsNullOrEmpty(right))
throw new ArgumentNullException("right");
if (left != right)
{
string message = String.Format("[[{0}]] != [[{1}]]", left, right);
throw new ApplicationException(message);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Test
{
public class ExchangeTests
{
[Fact]
public static void SimplePartitionMergeWhereScanTest()
{
for (int i = 1; i <= 128; i *= 2)
{
SimplePartitionMergeWhereScanTest1(1024 * 8, i, true);
SimplePartitionMergeWhereScanTest1(1024 * 8, i, false);
}
}
[Fact]
[OuterLoop]
public static void SimplePartitionMergeWhereScanTest_LongRunning()
{
for (int i = 1; i <= 128; i *= 2)
{
SimplePartitionMergeWhereScanTest1(1024 * 1024 * 2, i, true);
SimplePartitionMergeWhereScanTest1(1024 * 1024 * 2, i, false);
}
}
private static void SimplePartitionMergeWhereScanTest1(int dataSize, int partitions, bool pipeline)
{
int[] data = new int[dataSize];
for (int i = 0; i < dataSize; i++)
data[i] = i;
var whereOp = data.AsParallel()
.Where(delegate(int x) { return (x % 2) == 0; }); // select only even elements
IEnumerator<int> stream = whereOp.GetEnumerator();
int count = 0;
while (stream.MoveNext())
{
// @TODO: verify all the elements we expected are present.
count++;
}
if (count != (dataSize / 2))
{
Assert.True(false, string.Format("SimplePartitionMergeWhereScanTest1: {0}, {1}, {2}: > FAILED: count does not equal (dataSize/2)?", dataSize, partitions, pipeline));
}
}
[Fact]
public static void CheckWhereSelectComposition()
{
CheckWhereSelectCompositionCore(1024 * 8);
}
private static void CheckWhereSelectCompositionCore(int dataSize)
{
int[] data = new int[dataSize];
for (int i = 0; i < dataSize; i++)
data[i] = i;
var whereOp = data.AsParallel().Where(
delegate(int x) { return (x % 2) == 0; }); // select only even elements
var selectOp = whereOp.Select(
delegate(int x) { return x * 2; }); // just double the elements
// Now verify the output is what we expect.
int expectSum = 0;
for (int i = 0; i < dataSize; i++)
if ((i % 2) == 0)
expectSum += (i * 2);
int realSum = 0;
IEnumerator<int> e = selectOp.GetEnumerator();
while (e.MoveNext())
{
realSum += e.Current;
}
if (realSum != expectSum)
{
Assert.True(false, string.Format("CheckWhereSelectComposition datasize({0}): actual sum does not equal expected sum.", dataSize));
}
}
[Fact]
public static void PartitioningTest()
{
PartitioningTestCore(true, 1, 0, 10);
PartitioningTestCore(false, 1, 0, 10);
PartitioningTestCore(true, 1, 0, 500);
PartitioningTestCore(false, 1, 0, 520);
PartitioningTestCore(true, 4, 0, 500);
PartitioningTestCore(false, 4, 0, 520);
}
[Fact]
[OuterLoop]
public static void PartitioningTest_LongRunning()
{
PartitioningTestCore(true, 2, 0, 900);
PartitioningTestCore(false, 2, 0, 900);
}
private static void PartitioningTestCore(bool stripedPartitioning, int partitions, int minLen, int maxLen)
{
for (int len = minLen; len < maxLen; len++)
{
int[] arr = Enumerable.Range(0, len).ToArray();
IEnumerable<int> query;
if (stripedPartitioning)
{
query = arr.AsParallel().AsOrdered().WithDegreeOfParallelism(partitions).Take(len).Select(i => i);
}
else
{
query = arr.AsParallel().AsOrdered().WithDegreeOfParallelism(partitions).Select(i => i);
}
if (!arr.SequenceEqual(query))
{
Console.WriteLine("PartitioningTest: {0}, {1}, {2}, {3}", stripedPartitioning, partitions, minLen, maxLen);
Assert.True(false, string.Format(" ** FAILED: incorrect output for array of length {0}", len));
}
}
}
[Fact]
public static void OrderedPipeliningTest()
{
OrderedPipeliningTest1(4, true);
OrderedPipeliningTest1(4, false);
OrderedPipeliningTest1(10007, true);
OrderedPipeliningTest1(10007, false);
OrderedPipeliningTest2(true);
OrderedPipeliningTest2(false);
}
/// <summary>
/// Checks whether an ordered pipelining merge produces the correct output.
/// </summary>
private static void OrderedPipeliningTest1(int dataSize, bool buffered)
{
ParallelMergeOptions merge = buffered ? ParallelMergeOptions.FullyBuffered : ParallelMergeOptions.NotBuffered;
IEnumerable<int> src = Enumerable.Range(0, dataSize);
if (!Enumerable.SequenceEqual(src.AsParallel().AsOrdered().WithMergeOptions(merge).Select(x => x), src))
{
Assert.True(false, string.Format("OrderedPipeliningTest1: dataSize={0}, buffered={1}: > FAILED: Incorrect output.", dataSize, buffered));
}
}
/// <summary>
/// Checks whether an ordered pipelining merge pipelines the results
/// instead of running in a stop-and-go fashion.
/// </summary>
private static void OrderedPipeliningTest2(bool buffered)
{
ParallelMergeOptions merge = buffered ? ParallelMergeOptions.AutoBuffered : ParallelMergeOptions.NotBuffered;
IEnumerable<int> src = Enumerable.Range(0, int.MaxValue)
.Select(x => { if (x == 100000000) throw new Exception(); return x; });
try
{
int expect = 0;
int got = Enumerable.First(src.AsParallel().AsOrdered().WithMergeOptions(merge).Select(x => x));
if (got != expect)
{
Assert.True(false, string.Format("OrderedPipeliningTest2: buffered={0} > FAILED: Expected {1}, got {2}.", buffered, expect, got));
}
}
catch (Exception e)
{
Assert.True(false, string.Format("OrderedPipeliningTest2: buffered={0}: > FAILED. Caught an exception - {1}", buffered, e));
}
}
/// <summary>
/// Verifies that AsEnumerable causes subsequent LINQ operators to bind to LINQ-to-objects
/// </summary>
/// <returns></returns>
[Fact]
public static void RunAsEnumerableTest()
{
IEnumerable<int> src = Enumerable.Range(0, 100).AsParallel().AsEnumerable().Select(x => x);
bool passed = !(src is ParallelQuery<int>);
if (!passed)
Assert.True(false, string.Format("AsEnumerableTest: > Failed. AsEnumerable() didn't prevent the Select operator from binding to PLINQ."));
}
}
}
| |
/*
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 *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.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Research.JobObjectModel;
using Microsoft.Research.Tools;
namespace Microsoft.Research.DryadAnalysis
{
/// <summary>
/// The result of a decision (ternary booleans?)
/// </summary>
public enum Decision
{
/// <summary>
/// Yes.
/// </summary>
Yes,
/// <summary>
/// No.
/// </summary>
No,
/// <summary>
/// Cannot say.
/// </summary>
Dontknow,
/// <summary>
/// Not applicable.
/// </summary>
NA
};
/// <summary>
/// A message diagnosing a problem in a system.
/// </summary>
public class DiagnosisMessage
{
/// <summary>
/// Categorizes diagnosis messages according to their importance.
/// </summary>
public enum Importance
{
/// <summary>
/// Traces the decision flow.
/// </summary>
Tracing,
/// <summary>
/// An error occured during the diagnostic process.
/// </summary>
Error,
/// <summary>
/// Final diagnostic message.
/// </summary>
Final,
/// <summary>
/// This is a bug_ in Dryad/DryadLINQ.
/// </summary>
CoreBug,
}
/// <summary>
/// Importance of the message.
/// </summary>
public Importance MessageImportance { get; protected set; }
/// <summary>
/// Message itself.
/// </summary>
public string Message { get; protected set; }
/// <summary>
/// Additional details about the message.
/// </summary>
public string Details { get; protected set; }
/// <summary>
/// Create a new diagnosis message.
/// </summary>
/// <param name="i">Message importance.</param>
/// <param name="message">Message attached.</param>
/// <param name="details">Additional details about the message.</param>
public DiagnosisMessage(Importance i, string message, string details)
{
this.MessageImportance = i;
this.Message = message;
this.Details = details;
}
/// <summary>
/// String representation of the diagnosis message.
/// </summary>
/// <returns>A string representation.</returns>
public override string ToString()
{
return string.Format("{0} {1}", this.Message, this.Details);
}
}
/// <summary>
/// A diagnostic log is a sequence of messages.
/// </summary>
public class DiagnosisLog
{
/// <summary>
/// List of messages in the log.
/// </summary>
private List<DiagnosisMessage> messages;
/// <summary>
/// Summary of job being diagnosed.
/// </summary>
public DryadLinqJobSummary Summary { get; protected set; }
/// <summary>
/// Job being diagnosed.
/// </summary>
public DryadLinqJobInfo Job { get; protected set; }
/// <summary>
/// Create a new diagnostic log.
/// </summary>
public DiagnosisLog(DryadLinqJobInfo job, DryadLinqJobSummary summary)
{
this.messages = new List<DiagnosisMessage>();
this.Summary = summary;
this.Job = job;
}
/// <summary>
/// Add a new message to the log.
/// </summary>
/// <param name="msg">Message to add to log.</param>
public void AddMessage(DiagnosisMessage msg)
{
this.messages.Add(msg);
}
/// <summary>
/// The part of the log with high enough severity.
/// </summary>
/// <param name="cutoff">Do not show messages below this severity.</param>
/// <returns>A string representation of all suitable messages in the log.</returns>
public IEnumerable<string> Message(DiagnosisMessage.Importance cutoff)
{
bool coreBugFound = false;
IEnumerable<DiagnosisMessage> suitable = this.messages.Where(m => m.MessageImportance >= cutoff);
// remove duplicated messages
Dictionary<string, Tuple<int, DiagnosisMessage>> repeats = new Dictionary<string,Tuple<int,DiagnosisMessage>>();
foreach (DiagnosisMessage s in suitable) {
if (s.MessageImportance == DiagnosisMessage.Importance.CoreBug)
coreBugFound = true;
if (repeats.ContainsKey(s.Message))
repeats[s.Message] = Tuple.Create(repeats[s.Message].Item1+1, repeats[s.Message].Item2);
else
repeats[s.Message] = new Tuple<int,DiagnosisMessage>(1, s);
}
foreach (var m in repeats) {
var count = m.Value.Item1;
var msg = m.Value.Item2.ToString();
if (count > 1)
msg += " [repeated " + count + " times]";
yield return msg;
}
if (coreBugFound)
{
yield return "This is a bug in the underlying system (Dryad/DryadLINQ/Quincy). You can report this diagnosis to the DryadLINQ developers at drylnqin";
}
}
/// <summary>
/// Default string representation.
/// </summary>
/// <returns>A string representation of the log.</returns>
public IEnumerable<string> Message()
{
// ReSharper disable once IntroduceOptionalParameters.Global
return this.Message(DiagnosisMessage.Importance.Final);
}
/// <summary>
/// String representation of the log contents.
/// </summary>
/// <returns>A big string containing each line of the log on a separate line.</returns>
public override string ToString()
{
return string.Join("\n", this.Message().ToArray());
}
}
/// <summary>
/// Base class for failure diagnoses.
/// </summary>
public abstract class FailureDiagnosis
{
/// <summary>
/// Log used to write the diagnosis messages.
/// </summary>
protected DiagnosisLog diagnosisLog;
/// <summary>
/// Summary of the job being diagnosed.
/// </summary>
public DryadLinqJobSummary Summary
{
get;
protected set;
}
/// <summary>
/// Cluster where the job resides.
/// </summary>
protected readonly ClusterConfiguration cluster;
/// <summary>
/// Job that owns the vertex.
/// </summary>
public DryadLinqJobInfo Job { get; protected set; }
/// <summary>
/// Communication manager.
/// </summary>
public CommManager Manager { get; protected set; }
/// <summary>
/// Plan of the job.
/// </summary>
public DryadJobStaticPlan StaticPlan { get; protected set; }
/// <summary>
/// Create a FailureDiagnosis object.
/// </summary>
/// <param name="job">Job being diagnosed.</param>
/// <param name="plan">Static plan of the job.</param>
/// <param name="manager">Communication manager.</param>
protected FailureDiagnosis(DryadLinqJobInfo job, DryadJobStaticPlan plan, CommManager manager)
{
this.Job = job;
this.StaticPlan = plan;
this.Manager = manager;
this.Summary = job.Summary;
this.cluster = job.ClusterConfiguration;
}
/// <summary>
/// Try to find the job information from cluster and summary.
/// </summary>
/// <param name="manager">Communication manager.</param>
protected void FindJobInfo(CommManager manager)
{
DryadLinqJobInfo jobinfo = DryadLinqJobInfo.CreateDryadLinqJobInfo(this.cluster, this.Summary, true, manager);
if (jobinfo == null)
{
manager.Status("Cannot collect information for " + Summary.ShortName() + " to diagnose", StatusKind.Error);
return;
}
this.Job = jobinfo;
this.StaticPlan = JobObjectModel.DryadJobStaticPlan.CreatePlan(jobinfo, manager);
}
/// <summary>
/// Create a failure diagnosis when the job info is not yet known.
/// </summary>
/// <param name="config">Cluster where job resides.</param>
/// <param name="summary">Job summary.</param>
/// <param name="manager">Communication manager.</param>
protected FailureDiagnosis(ClusterConfiguration config, DryadLinqJobSummary summary, CommManager manager)
{
this.cluster = config;
this.Summary = summary;
this.Manager = manager;
this.FindJobInfo(manager);
}
/// <summary>
/// Write a log message to the diagnosis log.
/// </summary>
/// <param name="importance">Message importance.</param>
/// <param name="message">Message to write.</param>
/// <param name="details">Additional message details.</param>
protected void Log(DiagnosisMessage.Importance importance, string message, string details)
{
this.diagnosisLog.AddMessage(new DiagnosisMessage(importance, message, details));
}
}
#region COMMON_DIAGNOSIS
// This is diagnosis which is mostly Dryad dependent, so it is independent on the cluster platform.
/// <summary>
/// Diagnoses the failure of a vertex.
/// </summary>
public class VertexFailureDiagnosis : FailureDiagnosis
{
/// <summary>
/// Vertex that is being diagnosed.
/// </summary>
public ExecutedVertexInstance Vertex { get; protected set; }
/// <summary>
/// Create a class to diagnose the problems of a vertex.
/// </summary>
/// <param name="vertex">Vertex to diagnose.</param>
/// <param name="job">Job containing the vertex.</param>
/// <param name="plan">Plan of the executed job.</param>
/// <param name="manager">Communication manager.</param>
protected VertexFailureDiagnosis(DryadLinqJobInfo job, DryadJobStaticPlan plan, ExecutedVertexInstance vertex, CommManager manager)
: base(job, plan, manager)
{
this.Job = job;
this.Vertex = vertex;
// ReSharper disable once DoNotCallOverridableMethodsInConstructor
this.stackTraceFile = "dryadLinqStackTrace.txt";
}
/// <summary>
/// Create a VertexFailureDiagnosis of the appropriate type.
/// </summary>
/// <param name="vertex">Vertex to diagnose.</param>
/// <param name="job">Job containing the vertex.</param>
/// <param name="manager">Communication manager.</param>
/// <returns>A subclass of VertexFailureDiagnosis.</returns>
/// <param name="plan">Plan of the executed job.</param>
public static VertexFailureDiagnosis CreateVertexFailureDiagnosis(DryadLinqJobInfo job,
DryadJobStaticPlan plan,
ExecutedVertexInstance vertex,
CommManager manager)
{
ClusterConfiguration config = job.ClusterConfiguration;
if (config is CacheClusterConfiguration)
config = (config as CacheClusterConfiguration).ActualConfig(job.Summary);
throw new InvalidOperationException("Config of type " + config.TypeOfCluster + " not handled");
}
/// <summary>
/// The main function of the diagnosis.
/// </summary>
/// <param name="log">Log where explanation is written.</param>
/// <returns>The decision of the diagnosis.</returns>
public virtual Decision Diagnose(DiagnosisLog log)
{
throw new InvalidOperationException("Must override this function");
}
/// <summary>
/// Diagnose a vertex.
/// </summary>
/// <returns>The log of the diagnostic.</returns>
public DiagnosisLog Diagnose()
{
DiagnosisLog log = new DiagnosisLog(this.Job, this.Summary);
log.AddMessage(new DiagnosisMessage(DiagnosisMessage.Importance.Final, "Diagnostic for " + this.VertexName, "Vertex state is " + this.Vertex.State));
this.Diagnose(log);
this.Manager.Status("Vertex diagnosis complete", StatusKind.OK);
return log;
}
/// <summary>
/// Return the vertex logs.
/// </summary>
/// <param name="errorLogs">If true return only the error logs.</param>
/// <returns>An iterator over all log files.</returns>
public virtual IEnumerable<IClusterResidentObject> Logs(bool errorLogs)
{
IClusterResidentObject logdir = this.Job.ClusterConfiguration.ProcessLogDirectory(this.Vertex.ProcessIdentifier, this.Vertex.VertexIsCompleted, this.Vertex.Machine, this.Job.Summary);
string pattern = this.Job.ClusterConfiguration.VertexLogFilesPattern(errorLogs, this.Job.Summary);
if (logdir.Exception != null)
yield break;
IEnumerable<IClusterResidentObject> logs = logdir.GetFilesAndFolders(pattern);
foreach (var l in logs)
{
if (l.Exception == null)
yield return l;
}
}
/// <summary>
/// Detect whether the vertex had problems reading a particular channel.
/// </summary>
/// <returns>The channel that cannot be read, or null if that's not the problem.</returns>
/// <param name="manager">Communication manager.</param>
public virtual ChannelEndpointDescription ChannelReadFailure(CommManager manager)
{
List<string> stack = this.StackTrace().ToList();
if (stack.Count == 0)
return null;
string firstLine = stack.First();
Regex errorMsg = new Regex(@"(.*)Exception: (.*)ailed to read from input channel at port (\d+)");
Match m = errorMsg.Match(firstLine);
if (!m.Success)
return null;
int channelNo;
bool success = int.TryParse(m.Groups[3].Value, out channelNo);
if (!success)
return null;
try
{
this.Vertex.DiscoverChannels(true, false, true, manager);
var channels = this.Vertex.InputChannels;
if (channels == null)
return null;
if (channels.Count < channelNo)
{
this.Log(DiagnosisMessage.Importance.Error, "Could not discover channel " + channelNo, this.VertexName);
return null;
}
return channels[channelNo];
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Detect whether vertex terminates with a stack overflow.
/// </summary>
/// <returns>True if this seems likely.</returns>
protected virtual Decision StackOverflow()
{
IClusterResidentObject stdout = this.Job.ClusterConfiguration.ProcessStdoutFile(this.Vertex.ProcessIdentifier, this.Vertex.VertexIsCompleted, this.Vertex.Machine, this.Job.Summary);
if (stdout.Exception != null)
return Decision.Dontknow;
ISharedStreamReader sr = stdout.GetStream(false);
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (line.Contains("StackOverflowException"))
{
this.Log(DiagnosisMessage.Importance.Final, "Error found in vertex stderr:", line);
sr.Close();
return Decision.Yes;
}
}
sr.Close();
return Decision.Dontknow;
}
/// <summary>
/// Try to diagnose whether there's a CLR mismatch error.
/// </summary>
/// <returns>True if this is the problem.</returns>
protected bool CLRStartupProblems()
{
IClusterResidentObject stdout = this.Job.ClusterConfiguration.ProcessStdoutFile(this.Vertex.ProcessIdentifier, this.Vertex.VertexIsCompleted, this.Vertex.Machine, this.Job.Summary);
if (stdout.Exception != null)
return false;
ISharedStreamReader sr = stdout.GetStream(false);
// only look for the error in the first 10 lines
for (int i = 0; i < 10; i++)
{
if (sr.EndOfStream)
{
sr.Close();
return false;
}
string line = sr.ReadLine();
if (line.Contains("Error code 2148734720 (0x80131700)"))
{
this.Log(DiagnosisMessage.Importance.Final, "Error found in vertex stdout:", line);
sr.Close();
return true;
}
}
sr.Close();
return false;
}
/// <summary>
/// Name of vertex that is being diagnosed.
/// </summary>
public string VertexName { get { return this.Vertex.Name; } }
/// <summary>
/// Name of the file containing the stack trace.
/// </summary>
public string stackTraceFile { get; protected set; }
/// <summary>
/// The stack trace of the vertex at the time of the crash.
/// </summary>
/// <returns>The stack trace or an empty collection.</returns>
public virtual IEnumerable<string> StackTrace()
{
IClusterResidentObject logdir = this.Job.ClusterConfiguration.ProcessWorkDirectory(this.Vertex.ProcessIdentifier, this.Vertex.VertexIsCompleted, this.Vertex.Machine, this.Job.Summary);
IClusterResidentObject stackTrace = logdir.GetFile(this.stackTraceFile);
ISharedStreamReader sr = stackTrace.GetStream(false);
if (sr.Exception == null)
{
while (! sr.EndOfStream)
yield return sr.ReadLine();
}
else
yield break;
}
/// <summary>
/// Check whether this vertex is reading from a job input.
/// </summary>
/// <returns>The list of input stages this vertex is reading from.</returns>
protected IEnumerable<DryadJobStaticPlan.Stage> VertexIsReadingFromJobInput()
{
if (this.StaticPlan == null)
yield break;
string stage = this.Vertex.StageName;
DryadJobStaticPlan.Stage staticStage = this.StaticPlan.GetStageByName(stage);
if (staticStage == null)
yield break;
foreach (DryadJobStaticPlan.Connection connection in this.StaticPlan.GetStageConnections(staticStage, true))
{
var input = connection.From;
if (input.IsInput)
yield return input;
}
}
/// <summary>
/// Detect whether a problem with incorrect serialization may be the reason for job failure.
/// </summary>
/// <returns>Yes if serialization is the issue.</returns>
protected virtual Decision SerializationError()
{
// two things must have happened:
// - the vertex must be reading from an input file
// - the vertex has failed with an error during reading
var inputStages = this.VertexIsReadingFromJobInput().Select(s => s.Uri).ToArray();
if (inputStages.Count() == 0)
return Decision.Dontknow;
Decision decision = this.VertexFailedWhenReading();
if (decision != Decision.Yes)
return decision;
this.Log(DiagnosisMessage.Importance.Final,
"A vertex failed with an error that may be indicative of incorrect data serialization.",
"Make sure that the program uses the correct data type for the used input files (and also it is using the proper combination of serialization attributes)."
);
this.Log(DiagnosisMessage.Importance.Final,
"The failed vertex is reading from the following input(s): ",
string.Join(",", inputStages));
return decision;
}
/// <summary>
/// Yes if this vertex had a read error.
/// </summary>
/// <returns>A decision.</returns>
protected virtual Decision VertexFailedWhenReading()
{
// Look for a DryadRecordReader string on the stack trace
foreach (string s in this.StackTrace())
{
if (s.Contains("DryadRecordReader"))
return Decision.Yes;
}
return Decision.Dontknow;
}
/// <summary>
/// If true the vertex died with an assertion failure.
/// </summary>
public bool DiedWithAssertion { get; protected set; }
}
/// <summary>
/// Diagnose failures in a job.
/// </summary>
public abstract class JobFailureDiagnosis : FailureDiagnosis
{
/// <summary>
/// Job manager vertex.
/// </summary>
protected readonly ExecutedVertexInstance jobManager;
/// <summary>
/// Create a class to diagnose the problems of a job.
/// </summary>
/// <param name="job">Job to diagnose.</param>
/// <param name="plan">Plan of the diagnosed job.</param>
/// <param name="manager">Communication manager.</param>
protected JobFailureDiagnosis(DryadLinqJobInfo job, DryadJobStaticPlan plan, CommManager manager)
: base(job, plan, manager)
{
this.diagnosisLog = new DiagnosisLog(job, job.Summary);
this.jobManager = this.Job.ManagerVertex;
}
/// <summary>
/// Create a class to diagnose the problems of a job.
/// </summary>
/// <param name="config">Cluster where job resides.</param>
/// <param name="manager">Communication manager.</param>
/// <param name="summary">Job summary.</param>
protected JobFailureDiagnosis(ClusterConfiguration config, DryadLinqJobSummary summary, CommManager manager)
: base(config, summary, manager)
{
this.diagnosisLog = new DiagnosisLog(this.Job, summary);
if (this.Job != null)
this.jobManager = this.Job.ManagerVertex;
}
/// <summary>
/// Decide whether the job has finished executing.
/// </summary>
/// <returns>A decision.</returns>
protected Decision IsJobFinished()
{
bool dec = ClusterJobInformation.JobIsFinished(this.Summary.Status);
return dec ? Decision.Yes : Decision.No;
}
/// <summary>
/// Decide whether the job has failed.
/// </summary>
/// <returns>A decision.</returns>
protected Decision IsJobFailed()
{
switch (this.Summary.Status)
{
case ClusterJobInformation.ClusterJobStatus.Failed:
return Decision.Yes;
case ClusterJobInformation.ClusterJobStatus.Cancelled:
case ClusterJobInformation.ClusterJobStatus.Succeeded:
return Decision.No;
case ClusterJobInformation.ClusterJobStatus.Running:
// job may still fail.
case ClusterJobInformation.ClusterJobStatus.Unknown:
return Decision.Dontknow;
default:
throw new InvalidDataException("Invalid job status " + this.Summary.Status);
}
}
/// <summary>
/// Main entry point: diagnose the failures of a job.
/// </summary>
/// <returns>The log containing the diagnosis result.</returns>
public virtual DiagnosisLog Diagnose()
{
throw new InvalidOperationException("Must override this function");
}
/// <summary>
/// Discover whether the failure is caused by the inability to parse the XML plan.
/// </summary>
/// <returns>The decision.</returns>
public Decision XmlPlanParseError()
{
if (this.jobManager == null)
{
this.Log(DiagnosisMessage.Importance.Tracing, "Could not find job manager vertex information", "");
return Decision.Dontknow;
}
IClusterResidentObject jmstdout = this.jobManager.StdoutFile;
if (jmstdout.Exception != null)
{
this.Log(DiagnosisMessage.Importance.Tracing, "Could not find job manager standard output", "");
return Decision.Dontknow;
}
ISharedStreamReader sr = jmstdout.GetStream(false);
if (sr.Exception != null)
{
this.Log(DiagnosisMessage.Importance.Tracing, "Could not read job manager standard output", sr.Exception.Message);
return Decision.Dontknow;
}
string firstline = sr.ReadLine();
if (sr.EndOfStream || firstline == null)
{
sr.Close();
return Decision.No;
}
sr.Close();
if (firstline.Contains("Error parsing input XML file"))
{
this.Log(DiagnosisMessage.Importance.Final, "The job manager cannot parse the XML plan file.\n",
"This means probably that the version of LinqToDryad.dll that you are using does not match the XmlExecHost.exe file from your drop.");
return Decision.Yes;
}
return Decision.No;
}
/// <summary>
/// Find if a vertex has had many instances failed.
/// </summary>
/// <returns>The vertex that failed many times.</returns>
protected ExecutedVertexInstance LookForRepeatedVertexFailures()
{
IEnumerable<ExecutedVertexInstance> failures =
this.Job.Vertices.Where(v => v.State == ExecutedVertexInstance.VertexState.Failed).
Where(v => !v.IsManager).
ToList();
if (failures.Count() == 0)
return null;
var mostFailed = failures.GroupBy(v => v.Name).OrderBy(g => -g.Count()).First();
if (mostFailed.Count() > 3)
return mostFailed.First();
return null;
}
/// <summary>
/// Find if a vertex has had many instances failed.
/// </summary>
/// <returns>The vertex that failed many times.</returns>
protected ExecutedVertexInstance LookForManyVertexFailures()
{
IEnumerable<ExecutedVertexInstance> failures =
this.Job.Vertices.Where(v => v.State == ExecutedVertexInstance.VertexState.Failed).
Where(v => !v.IsManager).
ToList();
if (failures.Count() < 5)
return null;
var mostFailed = failures.GroupBy(v => v.Name).OrderBy(g => -g.Count()).First();
return mostFailed.First();
}
/// <summary>
/// Find multiple failures on the same machine.
/// </summary>
/// <returns>Yes if there are some.</returns>
protected Decision LookForCorrelatedMachineFailures()
{
// if we have more than this many failures we start to worry
const int maxFailures = 5;
IEnumerable<ExecutedVertexInstance> failures =
this.Job.Vertices.Where(v => v.State == ExecutedVertexInstance.VertexState.Failed).
Where(v => !v.IsManager).
ToList();
int totalFailures = failures.Count();
if (totalFailures < maxFailures)
return Decision.No;
var mostFailures = failures.GroupBy(v => v.Machine).OrderBy(g => -g.Count()).First();
string failMachine = mostFailures.Key;
if (mostFailures.Count() > totalFailures / 3 || mostFailures.Count() > 4)
{
this.Log(DiagnosisMessage.Importance.Final,
"There are " + mostFailures.Count() + " failures on machine " + failMachine,
"Total number of failures is " + totalFailures);
return Decision.Yes;
}
return Decision.Dontknow;
}
/// <summary>
/// Check to see whether a vertex has failed deterministically too many times.
/// </summary>
/// <returns>Identify of the failed vertex, or null if no such vertex exists.</returns>
protected virtual ExecutedVertexInstance DeterministicVertexFailure()
{
string abortmsg = this.Job.AbortingMsg;
if (abortmsg == null)
return null;
// ABORTING: Vertex failed too many times. Vertex 2 (OrderBy__0) number of failed executions 6
Regex manyFaileRegex = new Regex(@"Vertex failed too many times. Vertex (\d+) \((.*)\) number of failed executions (\d+)");
Match m = manyFaileRegex.Match(this.Job.AbortingMsg);
if (!m.Success)
return null;
string name = m.Groups[2].Value;
string failures = m.Groups[3].Value;
this.Log(DiagnosisMessage.Importance.Final, string.Format("Job was aborted because vertex {0} failed {1} times", name, failures), "");
IEnumerable<ExecutedVertexInstance> failed = this.Job.Vertices.Where(vi => vi.Name == name && vi.State == ExecutedVertexInstance.VertexState.Failed).ToList();
if (failed.Count() == 0)
{
this.Log(DiagnosisMessage.Importance.Error, "Cannot find information about failed vertex", name);
return null;
}
return failed.First();
}
/// <summary>
/// Yes if the job dies because a vertex fails too many times to read the main job input.
/// </summary>
/// <returns>A decision indicating whether an input cannot be read.</returns>
protected virtual Decision DeterministicInputFailure()
{
if (string.IsNullOrEmpty(this.Job.AbortingMsg))
return Decision.No;
if (this.Job.AbortingMsg.Contains("read failures"))
{
this.Log(DiagnosisMessage.Importance.Final, "Job cannot read some input data", this.Job.AbortingMsg);
return Decision.Yes;
}
return Decision.Dontknow;
}
/// <summary>
/// Create a suitable Job Failure diagnosis object for the job being analyzed.
/// </summary>
/// <param name="job">Job to diagnose.</param>
/// <param name="manager">Communication manager.</param>
/// <returns>A subclass of JobFailureDiagnosis with the type appropriate for the job.</returns>
/// <param name="plan">Plan of the job being diagnosed.</param>
public static JobFailureDiagnosis CreateJobFailureDiagnosis(DryadLinqJobInfo job, DryadJobStaticPlan plan, CommManager manager)
{
ClusterConfiguration config = job.ClusterConfiguration;
if (config is CacheClusterConfiguration)
config = (config as CacheClusterConfiguration).ActualConfig(job.Summary);
throw new InvalidOperationException("Configuration of type " + config.TypeOfCluster + " not supported for diagnosis");
}
/// <summary>
/// Create a suitable Job Failure diagnosis object for the job being analyzed.
/// </summary>
/// <param name="summary">Job to diagnose.</param>
/// <param name="config">Cluster where job resides.</param>
/// <param name="manager">Communication manager.</param>
/// <returns>A subclass of JobFailureDiagnosis with the type appropriate for the job.</returns>
public static JobFailureDiagnosis CreateJobFailureDiagnosis(ClusterConfiguration config, DryadLinqJobSummary summary, CommManager manager)
{
if (config is CacheClusterConfiguration)
config = (config as CacheClusterConfiguration).ActualConfig(summary);
throw new InvalidOperationException("Configuration of type " + config.TypeOfCluster + " not supported for diagnosis");
}
/// <summary>
/// Look to see whether the vertices failed reading from some common set of machines.
/// This is incomplete: e.g., it does not work for tidyfs streams.
/// </summary>
/// <returns>Yes if there were correlated failures.</returns>
/// <param name="manager">Communication manager.</param>
protected Decision LookForCorrelatedReadFailures(CommManager manager)
{
// if we have more than this many failures we start to worry
const int maxFailures = 5;
IEnumerable<ExecutedVertexInstance> failures =
this.Job.Vertices.Where(v => v.State == ExecutedVertexInstance.VertexState.Failed).
Where(v => !v.IsManager).
ToList();
int totalFailures = failures.Count();
if (totalFailures < maxFailures)
return Decision.No;
List<ChannelEndpointDescription> channelsFailed = new List<ChannelEndpointDescription>();
int verticesDone = 0;
foreach (ExecutedVertexInstance v in failures)
{
var crf = VertexFailureDiagnosis.CreateVertexFailureDiagnosis(this.Job, this.StaticPlan, v, manager).ChannelReadFailure(manager);
if (crf != null)
{
channelsFailed.Add(crf);
}
verticesDone++;
manager.Progress(verticesDone * 100 / totalFailures);
}
if (channelsFailed.Count() < maxFailures)
return Decision.No;
this.Log(DiagnosisMessage.Importance.Final, "There are " + channelsFailed.Count() + " read failures in the job", "");
var files = channelsFailed.Where(ced => ced.UriType == "file").ToList();
if (files.Count() == 0)
{
this.Log(DiagnosisMessage.Importance.Final, "All channels with failures are distributed files", "No further information is available");
return Decision.Dontknow;
}
Decision result = Decision.Dontknow;
var machines = files.Select(f => new UNCPathname(f.LocalPath).Machine).GroupBy(w => w).ToList();
foreach (var m in machines)
{
int failuresOnM = m.Count();
if (failuresOnM > 3)
{
this.Log(DiagnosisMessage.Importance.Final, "There are " + failuresOnM + " read failures reading from machine", m.Key);
result = Decision.Yes;
}
}
return result;
}
}
#endregion
#region COSMOS_DIAGNOSIS
#region JOB_STILL_RUNNING
#endregion
#endregion
#region SCOPE_DIAGNOSIS
#region JOB_STILL_RUNNING
#endregion
#endregion
#region HPC_DIAGNOSIS
#region JOB_STILL_RUNNING
#endregion
#endregion
#region L2H_JOB_DIAGNOSIS
#region JOB_STILL_RUNNING
#endregion
#region HPC_ERRORS
#endregion
#endregion
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
namespace System.IO.Compression
{
//The disposable fields that this class owns get disposed when the ZipArchive it belongs to gets disposed
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public class ZipArchiveEntry
{
#region Fields
private const UInt16 DefaultVersionToExtract = 10;
private ZipArchive _archive;
private readonly Boolean _originallyInArchive;
private readonly Int32 _diskNumberStart;
private ZipVersionNeededValues _versionToExtract;
//Also, always use same for version made by because MSDOS high byte is 0
private BitFlagValues _generalPurposeBitFlag;
private CompressionMethodValues _storedCompressionMethod;
private DateTimeOffset _lastModified;
private Int64 _compressedSize;
private Int64 _uncompressedSize;
private Int64 _offsetOfLocalHeader;
private Int64? _storedOffsetOfCompressedData;
private UInt32 _crc32;
private Byte[] _compressedBytes;
private MemoryStream _storedUncompressedData;
private Boolean _currentlyOpenForWrite;
private Boolean _everOpenedForWrite;
private Stream _outstandingWriteStream;
private String _storedEntryName;
private Byte[] _storedEntryNameBytes;
//only apply to update mode
private List<ZipGenericExtraField> _cdUnknownExtraFields;
private List<ZipGenericExtraField> _lhUnknownExtraFields;
private Byte[] _fileComment;
private CompressionLevel? _compressionLevel;
#endregion Fields
//Initializes, attaches it to archive
internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd, CompressionLevel compressionLevel)
: this(archive, cd)
{
// Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
// as it is a pugable component that completely encapsulates the meaning of compressionLevel.
_compressionLevel = compressionLevel;
}
//Initializes, attaches it to archive
internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd)
{
_archive = archive;
_originallyInArchive = true;
_diskNumberStart = cd.DiskNumberStart;
_versionToExtract = (ZipVersionNeededValues)cd.VersionNeededToExtract;
_generalPurposeBitFlag = (BitFlagValues)cd.GeneralPurposeBitFlag;
CompressionMethod = (CompressionMethodValues)cd.CompressionMethod;
_lastModified = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified));
_compressedSize = cd.CompressedSize;
_uncompressedSize = cd.UncompressedSize;
_offsetOfLocalHeader = cd.RelativeOffsetOfLocalHeader;
/* we don't know this yet: should be _offsetOfLocalHeader + 30 + _storedEntryNameBytes.Length + extrafieldlength
* but entryname/extra length could be different in LH
*/
_storedOffsetOfCompressedData = null;
_crc32 = cd.Crc32;
_compressedBytes = null;
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
_outstandingWriteStream = null;
FullName = DecodeEntryName(cd.Filename);
_lhUnknownExtraFields = null;
//the cd should have these as null if we aren't in Update mode
_cdUnknownExtraFields = cd.ExtraFields;
_fileComment = cd.FileComment;
_compressionLevel = null;
}
//Initializes new entry
internal ZipArchiveEntry(ZipArchive archive, String entryName, CompressionLevel compressionLevel)
: this(archive, entryName)
{
// Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
// as it is a pugable component that completely encapsulates the meaning of compressionLevel.
_compressionLevel = compressionLevel;
}
//Initializes new entry
internal ZipArchiveEntry(ZipArchive archive, String entryName)
{
_archive = archive;
_originallyInArchive = false;
_diskNumberStart = 0;
_versionToExtract = ZipVersionNeededValues.Default; //this must happen before following two assignment
_generalPurposeBitFlag = 0;
CompressionMethod = CompressionMethodValues.Deflate;
_lastModified = DateTimeOffset.Now;
_compressedSize = 0; //we don't know these yet
_uncompressedSize = 0;
_offsetOfLocalHeader = 0;
_storedOffsetOfCompressedData = null;
_crc32 = 0;
_compressedBytes = null;
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
_outstandingWriteStream = null;
FullName = entryName;
_cdUnknownExtraFields = null;
_lhUnknownExtraFields = null;
_fileComment = null;
_compressionLevel = null;
if (_storedEntryNameBytes.Length > UInt16.MaxValue)
throw new ArgumentException(SR.EntryNamesTooLong);
//grab the stream if we're in create mode
if (_archive.Mode == ZipArchiveMode.Create)
{
_archive.AcquireArchiveStream(this);
}
}
/// <summary>
/// The ZipArchive that this entry belongs to. If this entry has been deleted, this will return null.
/// </summary>
public ZipArchive Archive { get { return _archive; } }
/// <summary>
/// The compressed size of the entry. If the archive that the entry belongs to is in Create mode, attempts to get this property will always throw an exception. If the archive that the entry belongs to is in update mode, this property will only be valid if the entry has not been opened.
/// </summary>
/// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception>
public Int64 CompressedLength
{
get
{
Contract.Ensures(Contract.Result<Int64>() >= 0);
if (_everOpenedForWrite)
throw new InvalidOperationException(SR.LengthAfterWrite);
return _compressedSize;
}
}
/// <summary>
/// The relative path of the entry as stored in the Zip archive. Note that Zip archives allow any string to be the path of the entry, including invalid and absolute paths.
/// </summary>
public String FullName
{
get
{
Contract.Ensures(Contract.Result<String>() != null);
return _storedEntryName;
}
private set
{
if (value == null)
throw new ArgumentNullException("FullName");
bool isUTF8;
_storedEntryNameBytes = EncodeEntryName(value, out isUTF8);
_storedEntryName = value;
if (isUTF8)
_generalPurposeBitFlag |= BitFlagValues.UnicodeFileName;
else
_generalPurposeBitFlag &= ~BitFlagValues.UnicodeFileName;
if (ZipHelper.EndsWithDirChar(value))
VersionToExtractAtLeast(ZipVersionNeededValues.ExplicitDirectory);
}
}
/// <summary>
/// The last write time of the entry as stored in the Zip archive. When setting this property, the DateTime will be converted to the
/// Zip timestamp format, which supports a resolution of two seconds. If the data in the last write time field is not a valid Zip timestamp,
/// an indicator value of 1980 January 1 at midnight will be returned.
/// </summary>
/// <exception cref="NotSupportedException">An attempt to set this property was made, but the ZipArchive that this entry belongs to was
/// opened in read-only mode.</exception>
/// <exception cref="ArgumentOutOfRangeException">An attempt was made to set this property to a value that cannot be represented in the
/// Zip timestamp format. The earliest date/time that can be represented is 1980 January 1 0:00:00 (midnight), and the last date/time
/// that can be represented is 2107 December 31 23:59:58 (one second before midnight).</exception>
public DateTimeOffset LastWriteTime
{
get
{
return _lastModified;
}
set
{
ThrowIfInvalidArchive();
if (_archive.Mode == ZipArchiveMode.Read)
throw new NotSupportedException(SR.ReadOnlyArchive);
if (_archive.Mode == ZipArchiveMode.Create && _everOpenedForWrite)
throw new IOException(SR.FrozenAfterWrite);
if (value.DateTime.Year < ZipHelper.ValidZipDate_YearMin || value.DateTime.Year > ZipHelper.ValidZipDate_YearMax)
throw new ArgumentOutOfRangeException("value", SR.DateTimeOutOfRange);
_lastModified = value;
}
}
/// <summary>
/// The uncompressed size of the entry. This property is not valid in Create mode, and it is only valid in Update mode if the entry has not been opened.
/// </summary>
/// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception>
public Int64 Length
{
get
{
Contract.Ensures(Contract.Result<Int64>() >= 0);
if (_everOpenedForWrite)
throw new InvalidOperationException(SR.LengthAfterWrite);
return _uncompressedSize;
}
}
/// <summary>
/// The filename of the entry. This is equivalent to the substring of Fullname that follows the final directory separator character.
/// </summary>
public String Name
{
get
{
Contract.Ensures(Contract.Result<String>() != null);
return Path.GetFileName(FullName);
}
}
/// <summary>
/// Deletes the entry from the archive.
/// </summary>
/// <exception cref="IOException">The entry is already open for reading or writing.</exception>
/// <exception cref="NotSupportedException">The ZipArchive that this entry belongs to was opened in a mode other than ZipArchiveMode.Update. </exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
public void Delete()
{
if (_archive == null)
return;
if (_currentlyOpenForWrite)
throw new IOException(SR.DeleteOpenEntry);
if (_archive.Mode != ZipArchiveMode.Update)
throw new NotSupportedException(SR.DeleteOnlyInUpdate);
_archive.ThrowIfDisposed();
_archive.RemoveEntry(this);
_archive = null;
UnloadStreams();
}
/// <summary>
/// Opens the entry. If the archive that the entry belongs to was opened in Read mode, the returned stream will be readable, and it may or may not be seekable. If Create mode, the returned stream will be writeable and not seekable. If Update mode, the returned stream will be readable, writeable, seekable, and support SetLength.
/// </summary>
/// <returns>A Stream that represents the contents of the entry.</returns>
/// <exception cref="IOException">The entry is already currently open for writing. -or- The entry has been deleted from the archive. -or- The archive that this entry belongs to was opened in ZipArchiveMode.Create, and this entry has already been written to once.</exception>
/// <exception cref="InvalidDataException">The entry is missing from the archive or is corrupt and cannot be read. -or- The entry has been compressed using a compression method that is not supported.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
public Stream Open()
{
Contract.Ensures(Contract.Result<Stream>() != null);
ThrowIfInvalidArchive();
switch (_archive.Mode)
{
case ZipArchiveMode.Read:
return OpenInReadMode(true);
case ZipArchiveMode.Create:
return OpenInWriteMode();
case ZipArchiveMode.Update:
default:
Debug.Assert(_archive.Mode == ZipArchiveMode.Update);
return OpenInUpdateMode();
}
}
/// <summary>
/// Returns the FullName of the entry.
/// </summary>
/// <returns>FullName of the entry</returns>
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return FullName;
}
/*
public void MoveTo(String destinationEntryName)
{
if (destinationEntryName == null)
throw new ArgumentNullException("destinationEntryName");
if (String.IsNullOrEmpty(destinationEntryName))
throw new ArgumentException("destinationEntryName cannot be empty", "destinationEntryName");
if (_archive == null)
throw new InvalidOperationException("Attempt to move a deleted entry");
if (_archive._isDisposed)
throw new ObjectDisposedException(_archive.ToString());
if (_archive.Mode != ZipArchiveMode.Update)
throw new NotSupportedException("MoveTo can only be used when the archive is in Update mode");
String oldFilename = _filename;
_filename = destinationEntryName;
if (_filenameLength > UInt16.MaxValue)
{
_filename = oldFilename;
throw new ArgumentException("Archive entry names must be smaller than 2^16 bytes");
}
}
*/
#region Privates
internal Boolean EverOpenedForWrite { get { return _everOpenedForWrite; } }
private Int64 OffsetOfCompressedData
{
get
{
if (_storedOffsetOfCompressedData == null)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
//by calling this, we are using local header _storedEntryNameBytes.Length and extraFieldLength
//to find start of data, but still using central directory size information
if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader))
throw new InvalidDataException(SR.LocalFileHeaderCorrupt);
_storedOffsetOfCompressedData = _archive.ArchiveStream.Position;
}
return _storedOffsetOfCompressedData.Value;
}
}
private MemoryStream UncompressedData
{
get
{
if (_storedUncompressedData == null)
{
//this means we have never opened it before
//if _uncompressedSize > Int32.MaxValue, it's still okay, because MemoryStream will just
//grow as data is copied into it
_storedUncompressedData = new MemoryStream((Int32)_uncompressedSize);
if (_originallyInArchive)
{
using (Stream decompressor = OpenInReadMode(false))
{
try
{
decompressor.CopyTo(_storedUncompressedData);
}
catch (InvalidDataException)
{
/* this is the case where the archive say the entry is deflate, but deflateStream
* throws an InvalidDataException. This property should only be getting accessed in
* Update mode, so we want to make sure _storedUncompressedData stays null so
* that later when we dispose the archive, this entry loads the compressedBytes, and
* copies them straight over
*/
_storedUncompressedData.Dispose();
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
throw;
}
}
}
//if they start modifying it, we should make sure it will get deflated
CompressionMethod = CompressionMethodValues.Deflate;
}
return _storedUncompressedData;
}
}
private CompressionMethodValues CompressionMethod
{
get { return _storedCompressionMethod; }
set
{
if (value == CompressionMethodValues.Deflate)
VersionToExtractAtLeast(ZipVersionNeededValues.Deflate);
_storedCompressionMethod = value;
}
}
private Encoding DefaultSystemEncoding
{
// On the desktop, this was Encoding.GetEncoding(0), which gives you the encoding object
// that corresponds too the default system codepage.
// However, in ProjectN, not only Encoding.GetEncoding(Int32) is not exposed, but there is also
// no guarantee that a notion of a default system code page exists on the OS.
// In fact, we can really only rely on UTF8 and UTF16 being present on all platforms.
// We fall back to UTF8 as this is what is used by ZIP when as the "unicode encoding".
get
{
return Encoding.UTF8;
// return Encoding.GetEncoding(0);
}
}
private String DecodeEntryName(Byte[] entryNameBytes)
{
Debug.Assert(entryNameBytes != null);
Encoding readEntryNameEncoding;
if ((_generalPurposeBitFlag & BitFlagValues.UnicodeFileName) == 0)
{
readEntryNameEncoding = (_archive == null)
? DefaultSystemEncoding
: _archive.EntryNameEncoding ?? DefaultSystemEncoding;
}
else
{
readEntryNameEncoding = Encoding.UTF8;
}
return new string(readEntryNameEncoding.GetChars(entryNameBytes)); //readEntryNameEncoding.GetString(entryNameBytes);
}
private Byte[] EncodeEntryName(String entryName, out bool isUTF8)
{
Debug.Assert(entryName != null);
Encoding writeEntryNameEncoding;
if (_archive != null && _archive.EntryNameEncoding != null)
writeEntryNameEncoding = _archive.EntryNameEncoding;
else
writeEntryNameEncoding = ZipHelper.RequiresUnicode(entryName)
? Encoding.UTF8
: DefaultSystemEncoding;
isUTF8 = writeEntryNameEncoding.Equals(Encoding.UTF8);
return writeEntryNameEncoding.GetBytes(entryName);
}
/* does almost everything you need to do to forget about this entry
* writes the local header/data, gets rid of all the data,
* closes all of the streams except for the very outermost one that
* the user holds on to and is responsible for closing
*
* after calling this, and only after calling this can we be guaranteed
* that we are reading to write the central directory
*
* should only throw an exception in extremely exceptional cases because it is called from dispose
*/
internal void WriteAndFinishLocalEntry()
{
CloseStreams();
WriteLocalFileHeaderAndDataIfNeeded();
UnloadStreams();
}
//should only throw an exception in extremely exceptional cases because it is called from dispose
internal void WriteCentralDirectoryFileHeader()
{
//This part is simple, because we should definitely know the sizes by this time
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
//_entryname only gets set when we read in or call moveTo. MoveTo does a check, and
//reading in should not be able to produce a entryname longer than UInt16.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= UInt16.MaxValue);
//decide if we need the Zip64 extra field:
Zip64ExtraField zip64ExtraField = new Zip64ExtraField();
UInt32 compressedSizeTruncated, uncompressedSizeTruncated, offsetOfLocalHeaderTruncated;
Boolean zip64Needed = false;
if (SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
)
{
zip64Needed = true;
compressedSizeTruncated = ZipHelper.Mask32Bit;
uncompressedSizeTruncated = ZipHelper.Mask32Bit;
//If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways
zip64ExtraField.CompressedSize = _compressedSize;
zip64ExtraField.UncompressedSize = _uncompressedSize;
}
else
{
compressedSizeTruncated = (UInt32)_compressedSize;
uncompressedSizeTruncated = (UInt32)_uncompressedSize;
}
if (_offsetOfLocalHeader > UInt32.MaxValue
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
)
{
zip64Needed = true;
offsetOfLocalHeaderTruncated = ZipHelper.Mask32Bit;
//If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways
zip64ExtraField.LocalHeaderOffset = _offsetOfLocalHeader;
}
else
{
offsetOfLocalHeaderTruncated = (UInt32)_offsetOfLocalHeader;
}
if (zip64Needed)
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
//determine if we can fit zip64 extra field and original extra fields all in
Int32 bigExtraFieldLength = (zip64Needed ? zip64ExtraField.TotalSize : 0)
+ (_cdUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_cdUnknownExtraFields) : 0);
UInt16 extraFieldLength;
if (bigExtraFieldLength > UInt16.MaxValue)
{
extraFieldLength = (UInt16)(zip64Needed ? zip64ExtraField.TotalSize : 0);
_cdUnknownExtraFields = null;
}
else
{
extraFieldLength = (UInt16)bigExtraFieldLength;
}
writer.Write(ZipCentralDirectoryFileHeader.SignatureConstant);
writer.Write((UInt16)_versionToExtract);
writer.Write((UInt16)_versionToExtract); //this is the version made by field. low byte is version needed, and high byte is 0 for MS DOS
writer.Write((UInt16)_generalPurposeBitFlag);
writer.Write((UInt16)CompressionMethod);
writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); //UInt32
writer.Write(_crc32); //UInt32
writer.Write(compressedSizeTruncated); //UInt32
writer.Write(uncompressedSizeTruncated); //UInt32
writer.Write((UInt16)_storedEntryNameBytes.Length);
writer.Write(extraFieldLength); //UInt16
// This should hold because of how we read it originally in ZipCentralDirectoryFileHeader:
Debug.Assert((_fileComment == null) || (_fileComment.Length <= UInt16.MaxValue));
writer.Write(_fileComment != null ? (UInt16)_fileComment.Length : (UInt16)0); //file comment length
writer.Write((UInt16)0); //disk number start
writer.Write((UInt16)0); //internal file attributes
writer.Write((UInt32)0); //external file attributes
writer.Write(offsetOfLocalHeaderTruncated); //offset of local header
writer.Write(_storedEntryNameBytes);
//write extra fields
if (zip64Needed)
zip64ExtraField.WriteBlock(_archive.ArchiveStream);
if (_cdUnknownExtraFields != null)
ZipGenericExtraField.WriteAllBlocks(_cdUnknownExtraFields, _archive.ArchiveStream);
if (_fileComment != null)
writer.Write(_fileComment);
}
//returns false if fails, will get called on every entry before closing in update mode
//can throw InvalidDataException
internal Boolean LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded()
{
String message;
//we should have made this exact call in _archive.Init through ThrowIfOpenable
Debug.Assert(IsOpenable(false, true, out message));
//load local header's extra fields. it will be null if we couldn't read for some reason
if (_originallyInArchive)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
_lhUnknownExtraFields = ZipLocalFileHeader.GetExtraFields(_archive.ArchiveReader);
}
if (!_everOpenedForWrite && _originallyInArchive)
{
//we know that it is openable at this point
_compressedBytes = new Byte[_compressedSize];
_archive.ArchiveStream.Seek(OffsetOfCompressedData, SeekOrigin.Begin);
//casting _compressedSize to Int32 here is safe because of check in IsOpenable
ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes, (Int32)_compressedSize);
}
return true;
}
internal void ThrowIfNotOpenable(Boolean needToUncompress, Boolean needToLoadIntoMemory)
{
String message;
if (!IsOpenable(needToUncompress, needToLoadIntoMemory, out message))
throw new InvalidDataException(message);
}
private CheckSumAndSizeWriteStream GetDataCompressor(Stream backingStream, Boolean leaveBackingStreamOpen, EventHandler onClose)
{
//stream stack: backingStream -> DeflateStream -> CheckSumWriteStream
//we should always be compressing with deflate. Stored is used for empty files, but we don't actually
//call through this function for that - we just write the stored value in the header
Debug.Assert(CompressionMethod == CompressionMethodValues.Deflate);
Stream compressorStream = _compressionLevel.HasValue
? new DeflateStream(backingStream, _compressionLevel.Value, leaveBackingStreamOpen)
: new DeflateStream(backingStream, CompressionMode.Compress, leaveBackingStreamOpen);
Boolean isIntermediateStream = true;
Boolean leaveCompressorStreamOpenOnClose = leaveBackingStreamOpen && !isIntermediateStream;
CheckSumAndSizeWriteStream checkSumStream =
new CheckSumAndSizeWriteStream(compressorStream, backingStream, leaveCompressorStreamOpenOnClose,
(Int64 initialPosition, Int64 currentPosition, UInt32 checkSum) =>
{
_crc32 = checkSum;
_uncompressedSize = currentPosition;
_compressedSize = backingStream.Position - initialPosition;
if (onClose != null)
onClose(this, EventArgs.Empty);
});
return checkSumStream;
}
private Stream GetDataDecompressor(Stream compressedStreamToRead)
{
Stream uncompressedStream = null;
switch (CompressionMethod)
{
case CompressionMethodValues.Deflate:
uncompressedStream = new DeflateStream(compressedStreamToRead, CompressionMode.Decompress);
break;
case CompressionMethodValues.Stored:
default:
//we can assume that only deflate/stored are allowed because we assume that
//IsOpenable is checked before this function is called
Debug.Assert(CompressionMethod == CompressionMethodValues.Stored);
uncompressedStream = compressedStreamToRead;
break;
}
return uncompressedStream;
}
private Stream OpenInReadMode(Boolean checkOpenable)
{
if (checkOpenable)
ThrowIfNotOpenable(true, false);
Stream compressedStream = new SubReadStream(_archive.ArchiveStream, OffsetOfCompressedData, _compressedSize);
return GetDataDecompressor(compressedStream);
}
private Stream OpenInWriteMode()
{
if (_everOpenedForWrite)
throw new IOException(SR.CreateModeWriteOnceAndOneEntryAtATime);
//we assume that if another entry grabbed the archive stream, that it set this entry's _everOpenedForWrite property to true by calling WriteLocalFileHeaderIfNeeed
Debug.Assert(_archive.IsStillArchiveStreamOwner(this));
_everOpenedForWrite = true;
CheckSumAndSizeWriteStream crcSizeStream = GetDataCompressor(_archive.ArchiveStream, true,
(object o, EventArgs e) =>
{
//release the archive stream
_archive.ReleaseArchiveStream(this);
_outstandingWriteStream = null;
});
_outstandingWriteStream = new DirectToArchiveWriterStream(crcSizeStream, this);
return new WrappedStream(_outstandingWriteStream, (object o, EventArgs e) => _outstandingWriteStream.Dispose());
}
private Stream OpenInUpdateMode()
{
if (_currentlyOpenForWrite)
throw new IOException(SR.UpdateModeOneStream);
ThrowIfNotOpenable(true, true);
_everOpenedForWrite = true;
_currentlyOpenForWrite = true;
//always put it at the beginning for them
UncompressedData.Seek(0, SeekOrigin.Begin);
return new WrappedStream(UncompressedData,
(object o, EventArgs e) =>
{
//once they close, we know uncompressed length, but still not compressed length
//so we don't fill in any size information
//those fields get figured out when we call GetCompressor as we write it to
//the actual archive
_currentlyOpenForWrite = false;
});
}
private Boolean IsOpenable(Boolean needToUncompress, Boolean needToLoadIntoMemory, out String message)
{
message = null;
if (_originallyInArchive)
{
if (needToUncompress)
{
if (CompressionMethod != CompressionMethodValues.Stored &&
CompressionMethod != CompressionMethodValues.Deflate)
{
message = SR.UnsupportedCompression;
return false;
}
}
if (_diskNumberStart != _archive.NumberOfThisDisk)
{
message = SR.SplitSpanned;
return false;
}
if (_offsetOfLocalHeader > _archive.ArchiveStream.Length)
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader))
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
//when this property gets called, some duplicated work
if (OffsetOfCompressedData + _compressedSize > _archive.ArchiveStream.Length)
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
//this limitation exists because a) it is unreasonable to load > 4GB into memory
//but also because the stream reading functions make it hard
if (needToLoadIntoMemory)
{
if (_compressedSize > Int32.MaxValue)
{
message = SR.EntryTooLarge;
return false;
}
}
}
return true;
}
private Boolean SizesTooLarge()
{
return _compressedSize > UInt32.MaxValue || _uncompressedSize > UInt32.MaxValue;
}
//return value is true if we allocated an extra field for 64 bit headers, un/compressed size
private Boolean WriteLocalFileHeader(Boolean isEmptyFile)
{
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
//_entryname only gets set when we read in or call moveTo. MoveTo does a check, and
//reading in should not be able to produce a entryname longer than UInt16.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= UInt16.MaxValue);
//decide if we need the Zip64 extra field:
Zip64ExtraField zip64ExtraField = new Zip64ExtraField();
Boolean zip64Used = false;
UInt32 compressedSizeTruncated, uncompressedSizeTruncated;
//if we already know that we have an empty file don't worry about anything, just do a straight shot of the header
if (isEmptyFile)
{
CompressionMethod = CompressionMethodValues.Stored;
compressedSizeTruncated = 0;
uncompressedSizeTruncated = 0;
Debug.Assert(_compressedSize == 0);
Debug.Assert(_uncompressedSize == 0);
Debug.Assert(_crc32 == 0);
}
else
{
//if we have a non-seekable stream, don't worry about sizes at all, and just set the right bit
//if we are using the data descriptor, then sizes and crc should be set to 0 in the header
if (_archive.Mode == ZipArchiveMode.Create && _archive.ArchiveStream.CanSeek == false && !isEmptyFile)
{
_generalPurposeBitFlag |= BitFlagValues.DataDescriptor;
zip64Used = false;
compressedSizeTruncated = 0;
uncompressedSizeTruncated = 0;
//the crc should not have been set if we are in create mode, but clear it just to be sure
Debug.Assert(_crc32 == 0);
}
else //if we are not in streaming mode, we have to decide if we want to write zip64 headers
{
if (SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| (_archive._forceZip64 && _archive.Mode == ZipArchiveMode.Update)
#endif
)
{
zip64Used = true;
compressedSizeTruncated = ZipHelper.Mask32Bit;
uncompressedSizeTruncated = ZipHelper.Mask32Bit;
//prepare Zip64 extra field object. If we have one of the sizes, the other must go in there
zip64ExtraField.CompressedSize = _compressedSize;
zip64ExtraField.UncompressedSize = _uncompressedSize;
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
}
else
{
zip64Used = false;
compressedSizeTruncated = (UInt32)_compressedSize;
uncompressedSizeTruncated = (UInt32)_uncompressedSize;
}
}
}
//save offset
_offsetOfLocalHeader = writer.BaseStream.Position;
//calculate extra field. if zip64 stuff + original extraField aren't going to fit, dump the original extraField, because this is more important
Int32 bigExtraFieldLength = (zip64Used ? zip64ExtraField.TotalSize : 0)
+ (_lhUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_lhUnknownExtraFields) : 0);
UInt16 extraFieldLength;
if (bigExtraFieldLength > UInt16.MaxValue)
{
extraFieldLength = (UInt16)(zip64Used ? zip64ExtraField.TotalSize : 0);
_lhUnknownExtraFields = null;
}
else
{
extraFieldLength = (UInt16)bigExtraFieldLength;
}
//write header
writer.Write(ZipLocalFileHeader.SignatureConstant);
writer.Write((UInt16)_versionToExtract);
writer.Write((UInt16)_generalPurposeBitFlag);
writer.Write((UInt16)CompressionMethod);
writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); //UInt32
writer.Write(_crc32); //UInt32
writer.Write(compressedSizeTruncated); //UInt32
writer.Write(uncompressedSizeTruncated); //UInt32
writer.Write((UInt16)_storedEntryNameBytes.Length);
writer.Write(extraFieldLength); //UInt16
writer.Write(_storedEntryNameBytes);
if (zip64Used)
zip64ExtraField.WriteBlock(_archive.ArchiveStream);
if (_lhUnknownExtraFields != null)
ZipGenericExtraField.WriteAllBlocks(_lhUnknownExtraFields, _archive.ArchiveStream);
return zip64Used;
}
private void WriteLocalFileHeaderAndDataIfNeeded()
{
//_storedUncompressedData gets frozen here, and is what gets written to the file
if (_storedUncompressedData != null || _compressedBytes != null)
{
if (_storedUncompressedData != null)
{
_uncompressedSize = _storedUncompressedData.Length;
//The compressor fills in CRC and sizes
//The DirectToArchiveWriterStream writes headers and such
using (Stream entryWriter = new DirectToArchiveWriterStream(
GetDataCompressor(_archive.ArchiveStream, true, null),
this))
{
_storedUncompressedData.Seek(0, SeekOrigin.Begin);
_storedUncompressedData.CopyTo(entryWriter);
_storedUncompressedData.Dispose();
_storedUncompressedData = null;
}
}
else
{
// we know the sizes at this point, so just go ahead and write the headers
if (_uncompressedSize == 0)
CompressionMethod = CompressionMethodValues.Stored;
WriteLocalFileHeader(false);
// we just want to copy the compressed bytes straight over, but the stream apis
// don't handle larger than 32 bit values, so we just wrap it in a stream
using (MemoryStream compressedStream = new MemoryStream(_compressedBytes))
{
compressedStream.CopyTo(_archive.ArchiveStream);
}
}
}
else //there is no data in the file, but if we are in update mode, we still need to write a header
{
if (_archive.Mode == ZipArchiveMode.Update || !_everOpenedForWrite)
{
_everOpenedForWrite = true;
WriteLocalFileHeader(true);
}
}
}
/* Using _offsetOfLocalHeader, seeks back to where CRC and sizes should be in the header,
* writes them, then seeks back to where you started
* Assumes that the stream is currently at the end of the data
*/
private void WriteCrcAndSizesInLocalHeader(Boolean zip64HeaderUsed)
{
Int64 finalPosition = _archive.ArchiveStream.Position;
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
Boolean zip64Needed = SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
;
Boolean pretendStreaming = zip64Needed && !zip64HeaderUsed;
UInt32 compressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (UInt32)_compressedSize;
UInt32 uncompressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (UInt32)_uncompressedSize;
/* first step is, if we need zip64, but didn't allocate it, pretend we did a stream write, because
* we can't go back and give ourselves the space that the extra field needs.
* we do this by setting the correct property in the bit flag */
if (pretendStreaming)
{
_generalPurposeBitFlag |= BitFlagValues.DataDescriptor;
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToBitFlagFromHeaderStart,
SeekOrigin.Begin);
writer.Write((UInt16)_generalPurposeBitFlag);
}
/* next step is fill out the 32-bit size values in the normal header. we can't assume that
* they are correct. we also write the CRC */
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToCrcFromHeaderStart,
SeekOrigin.Begin);
if (!pretendStreaming)
{
writer.Write(_crc32);
writer.Write(compressedSizeTruncated);
writer.Write(uncompressedSizeTruncated);
}
else //but if we are pretending to stream, we want to fill in with zeroes
{
writer.Write((UInt32)0);
writer.Write((UInt32)0);
writer.Write((UInt32)0);
}
/* next step: if we wrote the 64 bit header initially, a different implementation might
* try to read it, even if the 32-bit size values aren't masked. thus, we should always put the
* correct size information in there. note that order of uncomp/comp is switched, and these are
* 64-bit values
* also, note that in order for this to be correct, we have to insure that the zip64 extra field
* is alwasy the first extra field that is written */
if (zip64HeaderUsed)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.SizeOfLocalHeader
+ _storedEntryNameBytes.Length + Zip64ExtraField.OffsetToFirstField,
SeekOrigin.Begin);
writer.Write(_uncompressedSize);
writer.Write(_compressedSize);
_archive.ArchiveStream.Seek(finalPosition, SeekOrigin.Begin);
}
// now go to the where we were. assume that this is the end of the data
_archive.ArchiveStream.Seek(finalPosition, SeekOrigin.Begin);
/* if we are pretending we did a stream write, we want to write the data descriptor out
* the data descriptor can have 32-bit sizes or 64-bit sizes. In this case, we always use
* 64-bit sizes */
if (pretendStreaming)
{
writer.Write(_crc32);
writer.Write(_compressedSize);
writer.Write(_uncompressedSize);
}
}
private void WriteDataDescriptor()
{
// data descriptor can be 32-bit or 64-bit sizes. 32-bit is more compatible, so use that if possible
// signature is optional but recommended by the spec
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
writer.Write(ZipLocalFileHeader.DataDescriptorSignature);
writer.Write(_crc32);
if (SizesTooLarge())
{
writer.Write(_compressedSize);
writer.Write(_uncompressedSize);
}
else
{
writer.Write((UInt32)_compressedSize);
writer.Write((UInt32)_uncompressedSize);
}
}
private void UnloadStreams()
{
if (_storedUncompressedData != null)
_storedUncompressedData.Dispose();
_compressedBytes = null;
_outstandingWriteStream = null;
}
private void CloseStreams()
{
//if the user left the stream open, close the underlying stream for them
if (_outstandingWriteStream != null)
{
_outstandingWriteStream.Dispose();
}
}
private void VersionToExtractAtLeast(ZipVersionNeededValues value)
{
if (_versionToExtract < value)
{
_versionToExtract = value;
}
}
private void ThrowIfInvalidArchive()
{
if (_archive == null)
throw new InvalidOperationException(SR.DeletedEntry);
_archive.ThrowIfDisposed();
}
#endregion Privates
#region Nested Types
private class DirectToArchiveWriterStream : Stream
{
#region fields
private Int64 _position;
private CheckSumAndSizeWriteStream _crcSizeStream;
private Boolean _everWritten;
private Boolean _isDisposed;
private ZipArchiveEntry _entry;
private Boolean _usedZip64inLH;
private Boolean _canWrite;
#endregion
#region constructors
//makes the assumption that somewhere down the line, crcSizeStream is eventually writing directly to the archive
//this class calls other functions on ZipArchiveEntry that write directly to the archive
public DirectToArchiveWriterStream(CheckSumAndSizeWriteStream crcSizeStream, ZipArchiveEntry entry)
{
_position = 0;
_crcSizeStream = crcSizeStream;
_everWritten = false;
_isDisposed = false;
_entry = entry;
_usedZip64inLH = false;
_canWrite = true;
}
#endregion
#region properties
public override Int64 Length
{
get
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override Int64 Position
{
get
{
Contract.Ensures(Contract.Result<Int64>() >= 0);
ThrowIfDisposed();
return _position;
}
set
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override Boolean CanRead { get { return false; } }
public override Boolean CanSeek { get { return false; } }
public override Boolean CanWrite { get { return _canWrite; } }
#endregion
#region methods
private void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(this.GetType().ToString(), SR.HiddenStreamName);
}
public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.ReadingNotSupported);
}
public override Int64 Seek(Int64 offset, SeekOrigin origin)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
public override void SetLength(Int64 value)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SetLengthRequiresSeekingAndWriting);
}
//careful: assumes that write is the only way to write to the stream, if writebyte/beginwrite are implemented
//they must set _everWritten, etc.
public override void Write(Byte[] buffer, Int32 offset, Int32 count)
{
//we can't pass the argument checking down a level
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentNeedNonNegative);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentNeedNonNegative);
if ((buffer.Length - offset) < count)
throw new ArgumentException(SR.OffsetLengthInvalid);
Contract.EndContractBlock();
ThrowIfDisposed();
Debug.Assert(CanWrite);
//if we're not actually writing anything, we don't want to trigger the header
if (count == 0)
return;
if (!_everWritten)
{
_everWritten = true;
//write local header, we are good to go
_usedZip64inLH = _entry.WriteLocalFileHeader(false);
}
_crcSizeStream.Write(buffer, offset, count);
_position += count;
}
public override void Flush()
{
ThrowIfDisposed();
Debug.Assert(CanWrite);
_crcSizeStream.Flush();
}
protected override void Dispose(Boolean disposing)
{
if (disposing && !_isDisposed)
{
_crcSizeStream.Dispose(); //now we have size/crc info
if (!_everWritten)
{
//write local header, no data, so we use stored
_entry.WriteLocalFileHeader(true);
}
else
{
//go back and finish writing
if (_entry._archive.ArchiveStream.CanSeek)
//finish writing local header if we have seek capabilities
_entry.WriteCrcAndSizesInLocalHeader(_usedZip64inLH);
else
//write out data descriptor if we don't have seek capabilities
_entry.WriteDataDescriptor();
}
_canWrite = false;
_isDisposed = true;
}
base.Dispose(disposing);
}
#endregion
} // DirectToArchiveWriterStream
[Flags]
private enum BitFlagValues : ushort { DataDescriptor = 0x8, UnicodeFileName = 0x800 }
private enum CompressionMethodValues : ushort { Stored = 0x0, Deflate = 0x8 }
private enum OpenableValues { Openable, FileNonExistent, FileTooLarge }
#endregion Nested Types
} // class ZipArchiveEntry
} // namespace
| |
// 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.Text;
namespace Internal.JitInterface
{
// CorInfoHelpFunc defines the set of helpers (accessed via the ICorDynamicInfo::getHelperFtn())
// These helpers can be called by native code which executes in the runtime.
// Compilers can emit calls to these helpers.
public enum CorInfoHelpFunc
{
CORINFO_HELP_UNDEF, // invalid value. This should never be used
/* Arithmetic helpers */
CORINFO_HELP_DIV, // For the ARM 32-bit integer divide uses a helper call :-(
CORINFO_HELP_MOD,
CORINFO_HELP_UDIV,
CORINFO_HELP_UMOD,
CORINFO_HELP_LLSH,
CORINFO_HELP_LRSH,
CORINFO_HELP_LRSZ,
CORINFO_HELP_LMUL,
CORINFO_HELP_LMUL_OVF,
CORINFO_HELP_ULMUL_OVF,
CORINFO_HELP_LDIV,
CORINFO_HELP_LMOD,
CORINFO_HELP_ULDIV,
CORINFO_HELP_ULMOD,
CORINFO_HELP_LNG2DBL, // Convert a signed int64 to a double
CORINFO_HELP_ULNG2DBL, // Convert a unsigned int64 to a double
CORINFO_HELP_DBL2INT,
CORINFO_HELP_DBL2INT_OVF,
CORINFO_HELP_DBL2LNG,
CORINFO_HELP_DBL2LNG_OVF,
CORINFO_HELP_DBL2UINT,
CORINFO_HELP_DBL2UINT_OVF,
CORINFO_HELP_DBL2ULNG,
CORINFO_HELP_DBL2ULNG_OVF,
CORINFO_HELP_FLTREM,
CORINFO_HELP_DBLREM,
CORINFO_HELP_FLTROUND,
CORINFO_HELP_DBLROUND,
/* Allocating a new object. Always use ICorClassInfo::getNewHelper() to decide
which is the right helper to use to allocate an object of a given type. */
CORINFO_HELP_NEW_CROSSCONTEXT, // cross context new object
CORINFO_HELP_NEWFAST,
CORINFO_HELP_NEWSFAST, // allocator for small, non-finalizer, non-array object
CORINFO_HELP_NEWSFAST_ALIGN8, // allocator for small, non-finalizer, non-array object, 8 byte aligned
CORINFO_HELP_NEW_MDARR, // multi-dim array helper (with or without lower bounds - dimensions passed in as vararg)
CORINFO_HELP_NEW_MDARR_NONVARARG,// multi-dim array helper (with or without lower bounds - dimensions passed in as unmanaged array)
CORINFO_HELP_NEWARR_1_DIRECT, // helper for any one dimensional array creation
CORINFO_HELP_NEWARR_1_OBJ, // optimized 1-D object arrays
CORINFO_HELP_NEWARR_1_VC, // optimized 1-D value class arrays
CORINFO_HELP_NEWARR_1_ALIGN8, // like VC, but aligns the array start
CORINFO_HELP_STRCNS, // create a new string literal
CORINFO_HELP_STRCNS_CURRENT_MODULE, // create a new string literal from the current module (used by NGen code)
/* Object model */
CORINFO_HELP_INITCLASS, // Initialize class if not already initialized
CORINFO_HELP_INITINSTCLASS, // Initialize class for instantiated type
// Use ICorClassInfo::getCastingHelper to determine
// the right helper to use
CORINFO_HELP_ISINSTANCEOFINTERFACE, // Optimized helper for interfaces
CORINFO_HELP_ISINSTANCEOFARRAY, // Optimized helper for arrays
CORINFO_HELP_ISINSTANCEOFCLASS, // Optimized helper for classes
CORINFO_HELP_ISINSTANCEOFANY, // Slow helper for any type
CORINFO_HELP_CHKCASTINTERFACE,
CORINFO_HELP_CHKCASTARRAY,
CORINFO_HELP_CHKCASTCLASS,
CORINFO_HELP_CHKCASTANY,
CORINFO_HELP_CHKCASTCLASS_SPECIAL, // Optimized helper for classes. Assumes that the trivial cases
// has been taken care of by the inlined check
CORINFO_HELP_BOX,
CORINFO_HELP_BOX_NULLABLE, // special form of boxing for Nullable<T>
CORINFO_HELP_UNBOX,
CORINFO_HELP_UNBOX_NULLABLE, // special form of unboxing for Nullable<T>
CORINFO_HELP_GETREFANY, // Extract the byref from a TypedReference, checking that it is the expected type
CORINFO_HELP_ARRADDR_ST, // assign to element of object array with type-checking
CORINFO_HELP_LDELEMA_REF, // does a precise type comparision and returns address
/* Exceptions */
CORINFO_HELP_THROW, // Throw an exception object
CORINFO_HELP_RETHROW, // Rethrow the currently active exception
CORINFO_HELP_USER_BREAKPOINT, // For a user program to break to the debugger
CORINFO_HELP_RNGCHKFAIL, // array bounds check failed
CORINFO_HELP_OVERFLOW, // throw an overflow exception
CORINFO_HELP_THROWDIVZERO, // throw a divide by zero exception
CORINFO_HELP_THROWNULLREF, // throw a null reference exception
CORINFO_HELP_INTERNALTHROW, // Support for really fast jit
CORINFO_HELP_VERIFICATION, // Throw a VerificationException
CORINFO_HELP_SEC_UNMGDCODE_EXCPT, // throw a security unmanaged code exception
CORINFO_HELP_FAIL_FAST, // Kill the process avoiding any exceptions or stack and data dependencies (use for GuardStack unsafe buffer checks)
CORINFO_HELP_METHOD_ACCESS_EXCEPTION,//Throw an access exception due to a failed member/class access check.
CORINFO_HELP_FIELD_ACCESS_EXCEPTION,
CORINFO_HELP_CLASS_ACCESS_EXCEPTION,
CORINFO_HELP_ENDCATCH, // call back into the EE at the end of a catch block
/* Synchronization */
CORINFO_HELP_MON_ENTER,
CORINFO_HELP_MON_EXIT,
CORINFO_HELP_MON_ENTER_STATIC,
CORINFO_HELP_MON_EXIT_STATIC,
CORINFO_HELP_GETCLASSFROMMETHODPARAM, // Given a generics method handle, returns a class handle
CORINFO_HELP_GETSYNCFROMCLASSHANDLE, // Given a generics class handle, returns the sync monitor
// in its ManagedClassObject
/* Security callout support */
CORINFO_HELP_SECURITY_PROLOG, // Required if CORINFO_FLG_SECURITYCHECK is set, or CORINFO_FLG_NOSECURITYWRAP is not set
CORINFO_HELP_SECURITY_PROLOG_FRAMED, // Slow version of CORINFO_HELP_SECURITY_PROLOG. Used for instrumentation.
CORINFO_HELP_METHOD_ACCESS_CHECK, // Callouts to runtime security access checks
CORINFO_HELP_FIELD_ACCESS_CHECK,
CORINFO_HELP_CLASS_ACCESS_CHECK,
CORINFO_HELP_DELEGATE_SECURITY_CHECK, // Callout to delegate security transparency check
/* Verification runtime callout support */
CORINFO_HELP_VERIFICATION_RUNTIME_CHECK, // Do a Demand for UnmanagedCode permission at runtime
/* GC support */
CORINFO_HELP_STOP_FOR_GC, // Call GC (force a GC)
CORINFO_HELP_POLL_GC, // Ask GC if it wants to collect
CORINFO_HELP_STRESS_GC, // Force a GC, but then update the JITTED code to be a noop call
CORINFO_HELP_CHECK_OBJ, // confirm that ECX is a valid object pointer (debugging only)
/* GC Write barrier support */
CORINFO_HELP_ASSIGN_REF, // universal helpers with F_CALL_CONV calling convention
CORINFO_HELP_CHECKED_ASSIGN_REF,
CORINFO_HELP_ASSIGN_REF_ENSURE_NONHEAP, // Do the store, and ensure that the target was not in the heap.
CORINFO_HELP_ASSIGN_BYREF,
CORINFO_HELP_ASSIGN_STRUCT,
/* Accessing fields */
// For COM object support (using COM get/set routines to update object)
// and EnC and cross-context support
CORINFO_HELP_GETFIELD8,
CORINFO_HELP_SETFIELD8,
CORINFO_HELP_GETFIELD16,
CORINFO_HELP_SETFIELD16,
CORINFO_HELP_GETFIELD32,
CORINFO_HELP_SETFIELD32,
CORINFO_HELP_GETFIELD64,
CORINFO_HELP_SETFIELD64,
CORINFO_HELP_GETFIELDOBJ,
CORINFO_HELP_SETFIELDOBJ,
CORINFO_HELP_GETFIELDSTRUCT,
CORINFO_HELP_SETFIELDSTRUCT,
CORINFO_HELP_GETFIELDFLOAT,
CORINFO_HELP_SETFIELDFLOAT,
CORINFO_HELP_GETFIELDDOUBLE,
CORINFO_HELP_SETFIELDDOUBLE,
CORINFO_HELP_GETFIELDADDR,
CORINFO_HELP_GETSTATICFIELDADDR_CONTEXT, // Helper for context-static fields
CORINFO_HELP_GETSTATICFIELDADDR_TLS, // Helper for PE TLS fields
// There are a variety of specialized helpers for accessing static fields. The JIT should use
// ICorClassInfo::getSharedStaticsOrCCtorHelper to determine which helper to use
// Helpers for regular statics
CORINFO_HELP_GETGENERICS_GCSTATIC_BASE,
CORINFO_HELP_GETGENERICS_NONGCSTATIC_BASE,
CORINFO_HELP_GETSHARED_GCSTATIC_BASE,
CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE,
CORINFO_HELP_GETSHARED_GCSTATIC_BASE_NOCTOR,
CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_NOCTOR,
CORINFO_HELP_GETSHARED_GCSTATIC_BASE_DYNAMICCLASS,
CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_DYNAMICCLASS,
// Helper to class initialize shared generic with dynamicclass, but not get static field address
CORINFO_HELP_CLASSINIT_SHARED_DYNAMICCLASS,
// Helpers for thread statics
CORINFO_HELP_GETGENERICS_GCTHREADSTATIC_BASE,
CORINFO_HELP_GETGENERICS_NONGCTHREADSTATIC_BASE,
CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE,
CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE,
CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_NOCTOR,
CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_NOCTOR,
CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_DYNAMICCLASS,
CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_DYNAMICCLASS,
/* Debugger */
CORINFO_HELP_DBG_IS_JUST_MY_CODE, // Check if this is "JustMyCode" and needs to be stepped through.
/* Profiling enter/leave probe addresses */
CORINFO_HELP_PROF_FCN_ENTER, // record the entry to a method (caller)
CORINFO_HELP_PROF_FCN_LEAVE, // record the completion of current method (caller)
CORINFO_HELP_PROF_FCN_TAILCALL, // record the completionof current method through tailcall (caller)
/* Miscellaneous */
CORINFO_HELP_BBT_FCN_ENTER, // record the entry to a method for collecting Tuning data
CORINFO_HELP_PINVOKE_CALLI, // Indirect pinvoke call
CORINFO_HELP_TAILCALL, // Perform a tail call
CORINFO_HELP_GETCURRENTMANAGEDTHREADID,
CORINFO_HELP_INIT_PINVOKE_FRAME, // initialize an inlined PInvoke Frame for the JIT-compiler
CORINFO_HELP_MEMSET, // Init block of memory
CORINFO_HELP_MEMCPY, // Copy block of memory
CORINFO_HELP_RUNTIMEHANDLE_METHOD, // determine a type/field/method handle at run-time
CORINFO_HELP_RUNTIMEHANDLE_METHOD_LOG,// determine a type/field/method handle at run-time, with IBC logging
CORINFO_HELP_RUNTIMEHANDLE_CLASS, // determine a type/field/method handle at run-time
CORINFO_HELP_RUNTIMEHANDLE_CLASS_LOG,// determine a type/field/method handle at run-time, with IBC logging
// These helpers are required for MDIL backward compatibility only. They are not used by current JITed code.
CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPEHANDLE_OBSOLETE, // Convert from a TypeHandle (native structure pointer) to RuntimeTypeHandle at run-time
CORINFO_HELP_METHODDESC_TO_RUNTIMEMETHODHANDLE_OBSOLETE, // Convert from a MethodDesc (native structure pointer) to RuntimeMethodHandle at run-time
CORINFO_HELP_FIELDDESC_TO_RUNTIMEFIELDHANDLE_OBSOLETE, // Convert from a FieldDesc (native structure pointer) to RuntimeFieldHandle at run-time
CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE, // Convert from a TypeHandle (native structure pointer) to RuntimeType at run-time
CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE_MAYBENULL, // Convert from a TypeHandle (native structure pointer) to RuntimeType at run-time, the type may be null
CORINFO_HELP_METHODDESC_TO_STUBRUNTIMEMETHOD, // Convert from a MethodDesc (native structure pointer) to RuntimeMethodHandle at run-time
CORINFO_HELP_FIELDDESC_TO_STUBRUNTIMEFIELD, // Convert from a FieldDesc (native structure pointer) to RuntimeFieldHandle at run-time
CORINFO_HELP_VIRTUAL_FUNC_PTR, // look up a virtual method at run-time
//CORINFO_HELP_VIRTUAL_FUNC_PTR_LOG, // look up a virtual method at run-time, with IBC logging
// Not a real helpers. Instead of taking handle arguments, these helpers point to a small stub that loads the handle argument and calls the static helper.
CORINFO_HELP_READYTORUN_NEW,
CORINFO_HELP_READYTORUN_NEWARR_1,
CORINFO_HELP_READYTORUN_ISINSTANCEOF,
CORINFO_HELP_READYTORUN_CHKCAST,
CORINFO_HELP_READYTORUN_STATIC_BASE,
CORINFO_HELP_READYTORUN_VIRTUAL_FUNC_PTR,
CORINFO_HELP_READYTORUN_GENERIC_HANDLE,
CORINFO_HELP_READYTORUN_DELEGATE_CTOR,
CORINFO_HELP_EE_PRESTUB, // Not real JIT helper. Used in native images.
CORINFO_HELP_EE_PRECODE_FIXUP, // Not real JIT helper. Used for Precode fixup in native images.
CORINFO_HELP_EE_PINVOKE_FIXUP, // Not real JIT helper. Used for PInvoke target fixup in native images.
CORINFO_HELP_EE_VSD_FIXUP, // Not real JIT helper. Used for VSD cell fixup in native images.
CORINFO_HELP_EE_EXTERNAL_FIXUP, // Not real JIT helper. Used for to fixup external method thunks in native images.
CORINFO_HELP_EE_VTABLE_FIXUP, // Not real JIT helper. Used for inherited vtable slot fixup in native images.
CORINFO_HELP_EE_REMOTING_THUNK, // Not real JIT helper. Used for remoting precode in native images.
CORINFO_HELP_EE_PERSONALITY_ROUTINE,// Not real JIT helper. Used in native images.
CORINFO_HELP_EE_PERSONALITY_ROUTINE_FILTER_FUNCLET,// Not real JIT helper. Used in native images to detect filter funclets.
// ASSIGN_REF_EAX - CHECKED_ASSIGN_REF_EBP: NOGC_WRITE_BARRIERS JIT helper calls
//
// For unchecked versions EDX is required to point into GC heap.
//
// NOTE: these helpers are only used for x86.
CORINFO_HELP_ASSIGN_REF_EAX, // EAX holds GC ptr, do a 'mov [EDX], EAX' and inform GC
CORINFO_HELP_ASSIGN_REF_EBX, // EBX holds GC ptr, do a 'mov [EDX], EBX' and inform GC
CORINFO_HELP_ASSIGN_REF_ECX, // ECX holds GC ptr, do a 'mov [EDX], ECX' and inform GC
CORINFO_HELP_ASSIGN_REF_ESI, // ESI holds GC ptr, do a 'mov [EDX], ESI' and inform GC
CORINFO_HELP_ASSIGN_REF_EDI, // EDI holds GC ptr, do a 'mov [EDX], EDI' and inform GC
CORINFO_HELP_ASSIGN_REF_EBP, // EBP holds GC ptr, do a 'mov [EDX], EBP' and inform GC
CORINFO_HELP_CHECKED_ASSIGN_REF_EAX, // These are the same as ASSIGN_REF above ...
CORINFO_HELP_CHECKED_ASSIGN_REF_EBX, // ... but also check if EDX points into heap.
CORINFO_HELP_CHECKED_ASSIGN_REF_ECX,
CORINFO_HELP_CHECKED_ASSIGN_REF_ESI,
CORINFO_HELP_CHECKED_ASSIGN_REF_EDI,
CORINFO_HELP_CHECKED_ASSIGN_REF_EBP,
CORINFO_HELP_LOOP_CLONE_CHOICE_ADDR, // Return the reference to a counter to decide to take cloned path in debug stress.
CORINFO_HELP_DEBUG_LOG_LOOP_CLONING, // Print a message that a loop cloning optimization has occurred in debug mode.
CORINFO_HELP_THROW_ARGUMENTEXCEPTION, // throw ArgumentException
CORINFO_HELP_THROW_ARGUMENTOUTOFRANGEEXCEPTION, // throw ArgumentOutOfRangeException
CORINFO_HELP_JIT_PINVOKE_BEGIN, // Transition to preemptive mode before a P/Invoke, frame is the first argument
CORINFO_HELP_JIT_PINVOKE_END, // Transition to cooperative mode after a P/Invoke, frame is the first argument
CORINFO_HELP_JIT_REVERSE_PINVOKE_ENTER, // Transition to cooperative mode in reverse P/Invoke prolog, frame is the first argument
CORINFO_HELP_JIT_REVERSE_PINVOKE_EXIT, // Transition to preemptive mode in reverse P/Invoke epilog, frame is the first argument
CORINFO_HELP_COUNT,
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using Hydra.Framework.Mapping.CoordinateSystems;
namespace Hydra.Framework.Mapping.Converters.WellKnownText
{
//
// **********************************************************************
/// <summary>
/// Creates an object based on the supplied Well Known Text (WKT).
/// </summary>
// **********************************************************************
//
public class CoordinateSystemWktReader
{
#region Public Static Methods
//
// **********************************************************************
/// <summary>
/// Reads and parses a WKT-formatted projection string.
/// </summary>
/// <param name="wkt">String containing WKT.</param>
/// <returns>Object representation of the WKT.</returns>
/// <exception cref="System.ArgumentException">If a token is not recognised.</exception>
// **********************************************************************
//
public static IInfo Parse(string wkt)
{
IInfo returnObject = null;
StringReader reader = new StringReader(wkt);
WktStreamTokenizer tokenizer = new WktStreamTokenizer(reader);
tokenizer.NextToken();
string objectName = tokenizer.GetStringValue();
switch (objectName)
{
case "UNIT":
returnObject = ReadUnit(tokenizer);
break;
case "SPHEROID":
returnObject = ReadEllipsoid(tokenizer);
break;
case "DATUM":
returnObject = ReadHorizontalDatum(tokenizer);
break;
case "PRIMEM":
returnObject = ReadPrimeMeridian(tokenizer);
break;
case "VERT_CS":
case "GEOGCS":
case "PROJCS":
case "COMPD_CS":
case "GEOCCS":
case "FITTED_CS":
case "LOCAL_CS":
returnObject = ReadCoordinateSystem(wkt, tokenizer);
break;
default:
throw new ArgumentException(String.Format("'{0'} is not recongnized.", objectName));
}
reader.Close();
return returnObject;
}
#endregion
#region Private Static Methods
//
// **********************************************************************
/// <summary>
/// Returns a IUnit given a piece of WKT.
/// </summary>
/// <param name="tokenizer">WktStreamTokenizer that has the WKT.</param>
/// <returns>
/// An object that implements the IUnit interface.
/// </returns>
// **********************************************************************
//
private static IUnit ReadUnit(WktStreamTokenizer tokenizer)
{
tokenizer.ReadToken("[");
string unitName = tokenizer.ReadDoubleQuotedWord();
tokenizer.ReadToken(",");
tokenizer.NextToken();
double unitsPerUnit = tokenizer.GetNumericValue();
string authority = String.Empty;
long authorityCode = -1;
tokenizer.NextToken();
if (tokenizer.GetStringValue() == ",")
{
tokenizer.ReadAuthority(ref authority, ref authorityCode);
tokenizer.ReadToken("]");
}
return new Unit(unitsPerUnit, unitName, authority, authorityCode, String.Empty, String.Empty, String.Empty);
}
//
// **********************************************************************
/// <summary>
/// Returns a <see cref="LinearUnit"/> given a piece of WKT.
/// </summary>
/// <param name="tokenizer">WktStreamTokenizer that has the WKT.</param>
/// <returns>
/// An object that implements the IUnit interface.
/// </returns>
// **********************************************************************
//
private static ILinearUnit ReadLinearUnit(WktStreamTokenizer tokenizer)
{
tokenizer.ReadToken("[");
string unitName = tokenizer.ReadDoubleQuotedWord();
tokenizer.ReadToken(",");
tokenizer.NextToken();
double unitsPerUnit = tokenizer.GetNumericValue();
string authority = String.Empty;
long authorityCode = -1;
tokenizer.NextToken();
if (tokenizer.GetStringValue() == ",")
{
tokenizer.ReadAuthority(ref authority, ref authorityCode);
tokenizer.ReadToken("]");
}
return new LinearUnit(unitsPerUnit, unitName, authority, authorityCode, String.Empty, String.Empty, String.Empty);
}
//
// **********************************************************************
/// <summary>
/// Returns a <see cref="AngularUnit"/> given a piece of WKT.
/// </summary>
/// <param name="tokenizer">WktStreamTokenizer that has the WKT.</param>
/// <returns>
/// An object that implements the IUnit interface.
/// </returns>
// **********************************************************************
//
private static IAngularUnit ReadAngularUnit(WktStreamTokenizer tokenizer)
{
tokenizer.ReadToken("[");
string unitName = tokenizer.ReadDoubleQuotedWord();
tokenizer.ReadToken(",");
tokenizer.NextToken();
double unitsPerUnit = tokenizer.GetNumericValue();
string authority = String.Empty;
long authorityCode = -1;
tokenizer.NextToken();
if (tokenizer.GetStringValue() == ",")
{
tokenizer.ReadAuthority(ref authority, ref authorityCode);
tokenizer.ReadToken("]");
}
return new AngularUnit(unitsPerUnit, unitName, authority, authorityCode, String.Empty, String.Empty, String.Empty);
}
//
// **********************************************************************
/// <summary>
/// Returns a <see cref="AxisInfo"/> given a piece of WKT.
/// </summary>
/// <param name="tokenizer">WktStreamTokenizer that has the WKT.</param>
/// <returns>An AxisInfo object.</returns>
// **********************************************************************
//
private static AxisInfo ReadAxis(WktStreamTokenizer tokenizer)
{
if (tokenizer.GetStringValue() != "AXIS")
tokenizer.ReadToken("AXIS");
tokenizer.ReadToken("[");
string axisName = tokenizer.ReadDoubleQuotedWord();
tokenizer.ReadToken(",");
tokenizer.NextToken();
string unitname = tokenizer.GetStringValue();
tokenizer.ReadToken("]");
switch (unitname.ToUpper())
{
case "DOWN":
return new AxisInfo(axisName, AxisOrientationEnum.Down);
case "EAST":
return new AxisInfo(axisName, AxisOrientationEnum.East);
case "NORTH":
return new AxisInfo(axisName, AxisOrientationEnum.North);
case "OTHER":
return new AxisInfo(axisName, AxisOrientationEnum.Other);
case "SOUTH":
return new AxisInfo(axisName, AxisOrientationEnum.South);
case "UP":
return new AxisInfo(axisName, AxisOrientationEnum.Up);
case "WEST":
return new AxisInfo(axisName, AxisOrientationEnum.West);
default:
throw new ArgumentException("Invalid axis name '" + unitname + "' in WKT");
}
}
//
// **********************************************************************
/// <summary>
/// Reads the coordinate system.
/// </summary>
/// <param name="coordinateSystem">The coordinate system.</param>
/// <param name="tokenizer">The tokenizer.</param>
/// <returns></returns>
// **********************************************************************
//
private static ICoordinateSystem ReadCoordinateSystem(string coordinateSystem, WktStreamTokenizer tokenizer)
{
switch (tokenizer.GetStringValue())
{
case "GEOGCS":
return ReadGeographicCoordinateSystem(tokenizer);
case "PROJCS":
return ReadProjectedCoordinateSystem(tokenizer);
case "COMPD_CS":
case "VERT_CS":
case "GEOCCS":
case "FITTED_CS":
case "LOCAL_CS":
throw new NotSupportedException(String.Format("{0} coordinate system is not supported.", coordinateSystem));
default:
throw new InvalidOperationException(String.Format("{0} coordinate system is not recognized.", coordinateSystem));
}
}
//
// **********************************************************************
/// <summary>
/// Reads either 3, 6 or 7 parameter Bursa-Wolf values from TOWGS84 token
/// </summary>
/// <param name="tokenizer">The tokenizer.</param>
/// <returns></returns>
/// <example>
/// TOWGS84[0,0,0,0,0,0,0]
/// </example>
// **********************************************************************
//
private static Wgs84ConversionInfo ReadWGS84ConversionInfo(WktStreamTokenizer tokenizer)
{
tokenizer.ReadToken("[");
Wgs84ConversionInfo info = new Wgs84ConversionInfo();
tokenizer.NextToken();
info.Dx = tokenizer.GetNumericValue();
tokenizer.ReadToken(",");
tokenizer.NextToken();
info.Dy = tokenizer.GetNumericValue();
tokenizer.ReadToken(",");
tokenizer.NextToken();
info.Dz = tokenizer.GetNumericValue();
tokenizer.NextToken();
if (tokenizer.GetStringValue() == ",")
{
tokenizer.NextToken();
info.Ex = tokenizer.GetNumericValue();
tokenizer.ReadToken(",");
tokenizer.NextToken();
info.Ey = tokenizer.GetNumericValue();
tokenizer.ReadToken(",");
tokenizer.NextToken();
info.Ez = tokenizer.GetNumericValue();
tokenizer.NextToken();
if (tokenizer.GetStringValue() == ",")
{
tokenizer.NextToken();
info.Ppm = tokenizer.GetNumericValue();
}
}
if (tokenizer.GetStringValue() != "]")
tokenizer.ReadToken("]");
return info;
}
//
// **********************************************************************
/// <summary>
/// Reads the ellipsoid.
/// </summary>
/// <param name="tokenizer">The tokenizer.</param>
/// <returns></returns>
/// <example>
/// SPHEROID["Airy 1830",6377563.396,299.3249646,AUTHORITY["EPSG","7001"]]
/// </example>
// **********************************************************************
//
private static IEllipsoid ReadEllipsoid(WktStreamTokenizer tokenizer)
{
tokenizer.ReadToken("[");
string name = tokenizer.ReadDoubleQuotedWord();
tokenizer.ReadToken(",");
tokenizer.NextToken();
double majorAxis = tokenizer.GetNumericValue();
tokenizer.ReadToken(",");
tokenizer.NextToken();
double e = tokenizer.GetNumericValue();
//
// tokenizer.ReadToken(",");
//
tokenizer.NextToken();
string authority = String.Empty;
long authorityCode = -1;
if (tokenizer.GetStringValue() == ",") //Read authority
{
tokenizer.ReadAuthority(ref authority, ref authorityCode);
tokenizer.ReadToken("]");
}
IEllipsoid ellipsoid = new Ellipsoid(majorAxis, 0.0, e, true, LinearUnit.Metre, name, authority, authorityCode, String.Empty, string.Empty, string.Empty);
return ellipsoid;
}
//
// **********************************************************************
/// <summary>
/// Reads the projection.
/// </summary>
/// <param name="tokenizer">The tokenizer.</param>
/// <returns></returns>
// **********************************************************************
//
private static IProjection ReadProjection(WktStreamTokenizer tokenizer)
{
tokenizer.ReadToken("PROJECTION");
tokenizer.ReadToken("[");//[
string projectionName = tokenizer.ReadDoubleQuotedWord();
tokenizer.ReadToken("]");//]
tokenizer.ReadToken(",");//,
tokenizer.ReadToken("PARAMETER");
List<ProjectionParameter> paramList = new List<ProjectionParameter>();
while (tokenizer.GetStringValue() == "PARAMETER")
{
tokenizer.ReadToken("[");
string paramName = tokenizer.ReadDoubleQuotedWord();
tokenizer.ReadToken(",");
tokenizer.NextToken();
double paramValue = tokenizer.GetNumericValue();
tokenizer.ReadToken("]");
tokenizer.ReadToken(",");
paramList.Add(new ProjectionParameter(paramName, paramValue));
tokenizer.NextToken();
}
string authority = String.Empty;
long authorityCode = -1;
IProjection projection = new Projection(projectionName, paramList, projectionName, authority, authorityCode, String.Empty, String.Empty, string.Empty);
return projection;
}
//
// **********************************************************************
/// <summary>
/// Reads the projected coordinate system.
/// </summary>
/// <param name="tokenizer">The tokenizer.</param>
/// <returns></returns>
/// <example>
/// PROJCS[
/// "OSGB 1936 / British National Grid",
/// GEOGCS[
/// "OSGB 1936",
/// DATUM[...]
/// PRIMEM[...]
/// AXIS["Geodetic latitude","NORTH"]
/// AXIS["Geodetic longitude","EAST"]
/// AUTHORITY["EPSG","4277"]
/// ],
/// PROJECTION["Transverse Mercator"],
/// PARAMETER["latitude_of_natural_origin",49],
/// PARAMETER["longitude_of_natural_origin",-2],
/// PARAMETER["scale_factor_at_natural_origin",0.999601272],
/// PARAMETER["false_easting",400000],
/// PARAMETER["false_northing",-100000],
/// AXIS["Easting","EAST"],
/// AXIS["Northing","NORTH"],
/// AUTHORITY["EPSG","27700"]
/// ]
/// </example>
// **********************************************************************
//
private static IProjectedCoordinateSystem ReadProjectedCoordinateSystem(WktStreamTokenizer tokenizer)
{
tokenizer.ReadToken("[");
string name = tokenizer.ReadDoubleQuotedWord();
tokenizer.ReadToken(",");
tokenizer.ReadToken("GEOGCS");
IGeographicCoordinateSystem geographicCS = ReadGeographicCoordinateSystem(tokenizer);
tokenizer.ReadToken(",");
IProjection projection = ReadProjection(tokenizer);
IUnit unit = ReadLinearUnit(tokenizer);
string authority = String.Empty;
long authorityCode = -1;
tokenizer.NextToken();
List<AxisInfo> axes = new List<AxisInfo>(2);
if (tokenizer.GetStringValue() == ",")
{
tokenizer.NextToken();
while (tokenizer.GetStringValue() == "AXIS")
{
axes.Add(ReadAxis(tokenizer));
tokenizer.NextToken();
}
if (tokenizer.GetStringValue() == "AUTHORITY")
{
tokenizer.ReadAuthority(ref authority, ref authorityCode);
tokenizer.ReadToken("]");
}
}
//
// This is default axis values if not specified.
//
if (axes.Count == 0)
{
axes.Add(new AxisInfo("X", AxisOrientationEnum.East));
axes.Add(new AxisInfo("Y", AxisOrientationEnum.North));
}
IProjectedCoordinateSystem projectedCS = new ProjectedCoordinateSystem(geographicCS.HorizontalDatum, geographicCS, unit as LinearUnit, projection,
axes, name, authority, authorityCode, String.Empty, String.Empty, String.Empty);
return projectedCS;
}
//
// **********************************************************************
/// <summary>
/// Reads the geographic coordinate system.
/// </summary>
/// <param name="tokenizer">The tokenizer.</param>
/// <returns></returns>
/// <example>
/// GEOGCS[
/// "OSGB 1936",
/// DATUM["OSGB 1936",SPHEROID["Airy 1830",6377563.396,299.3249646,AUTHORITY["EPSG","7001"]]TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6277"]]
/// PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]]
/// AXIS["Geodetic latitude","NORTH"]
/// AXIS["Geodetic longitude","EAST"]
/// AUTHORITY["EPSG","4277"]
/// ]
/// </example>
// **********************************************************************
//
private static IGeographicCoordinateSystem ReadGeographicCoordinateSystem(WktStreamTokenizer tokenizer)
{
tokenizer.ReadToken("[");
string name = tokenizer.ReadDoubleQuotedWord();
tokenizer.ReadToken(",");
tokenizer.ReadToken("DATUM");
IHorizontalDatum horizontalDatum = ReadHorizontalDatum(tokenizer);
tokenizer.ReadToken(",");
tokenizer.ReadToken("PRIMEM");
IPrimeMeridian primeMeridian = ReadPrimeMeridian(tokenizer);
tokenizer.ReadToken(",");
tokenizer.ReadToken("UNIT");
IAngularUnit angularUnit = ReadAngularUnit(tokenizer);
string authority = String.Empty;
long authorityCode = -1;
tokenizer.NextToken();
List<AxisInfo> info = new List<AxisInfo>(2);
if (tokenizer.GetStringValue() == ",")
{
tokenizer.NextToken();
while (tokenizer.GetStringValue() == "AXIS")
{
info.Add(ReadAxis(tokenizer));
tokenizer.NextToken();
}
if (tokenizer.GetStringValue() == "AUTHORITY")
{
tokenizer.ReadAuthority(ref authority, ref authorityCode);
tokenizer.ReadToken("]");
}
}
//
// This is default axis values if not specified.
//
if (info.Count == 0)
{
info.Add(new AxisInfo("Lon", AxisOrientationEnum.East));
info.Add(new AxisInfo("Lat", AxisOrientationEnum.North));
}
IGeographicCoordinateSystem geographicCS = new GeographicCoordinateSystem(angularUnit, horizontalDatum, primeMeridian, info, name, authority,
authorityCode, String.Empty, String.Empty, String.Empty);
return geographicCS;
}
//
// **********************************************************************
/// <summary>
/// Reads the horizontal datum.
/// </summary>
/// <param name="tokenizer">The tokenizer.</param>
/// <returns></returns>
/// <example>
/// DATUM[
/// "OSGB 1936",
/// SPHEROID["Airy 1830",6377563.396,299.3249646,AUTHORITY["EPSG","7001"]]TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6277"]
/// ]
/// </example>
// **********************************************************************
//
private static IHorizontalDatum ReadHorizontalDatum(WktStreamTokenizer tokenizer)
{
Wgs84ConversionInfo wgsInfo = null;
string authority = String.Empty;
long authorityCode = -1;
tokenizer.ReadToken("[");
string name = tokenizer.ReadDoubleQuotedWord();
tokenizer.ReadToken(",");
tokenizer.ReadToken("SPHEROID");
IEllipsoid ellipsoid = ReadEllipsoid(tokenizer);
tokenizer.NextToken();
while (tokenizer.GetStringValue() == ",")
{
tokenizer.NextToken();
if (tokenizer.GetStringValue() == "TOWGS84")
{
wgsInfo = ReadWGS84ConversionInfo(tokenizer);
tokenizer.NextToken();
}
else if (tokenizer.GetStringValue() == "AUTHORITY")
{
tokenizer.ReadAuthority(ref authority, ref authorityCode);
tokenizer.ReadToken("]");
}
}
//
// make an assumption about the datum type.
//
IHorizontalDatum horizontalDatum = new HorizontalDatum(ellipsoid, wgsInfo, DatumType.HD_Geocentric, name, authority, authorityCode, String.Empty, String.Empty, String.Empty);
return horizontalDatum;
}
//
// **********************************************************************
/// <summary>
/// Reads the prime meridian.
/// </summary>
/// <param name="tokenizer">The tokenizer.</param>
/// <returns></returns>
/// <example>
/// PRIMEM
/// [
/// "Greenwich",0,AUTHORITY["EPSG","8901"]
/// ]
/// </example>
// **********************************************************************
//
private static IPrimeMeridian ReadPrimeMeridian(WktStreamTokenizer tokenizer)
{
tokenizer.ReadToken("[");
string name = tokenizer.ReadDoubleQuotedWord();
tokenizer.ReadToken(",");
tokenizer.NextToken();
double longitude = tokenizer.GetNumericValue();
tokenizer.NextToken();
string authority = String.Empty;
long authorityCode = -1;
if (tokenizer.GetStringValue() == ",")
{
tokenizer.ReadAuthority(ref authority, ref authorityCode);
tokenizer.ReadToken("]");
}
//
// make an assumption about the Angular units - degrees.
//
IPrimeMeridian primeMeridian = new PrimeMeridian(longitude, AngularUnit.Degrees, name, authority, authorityCode, String.Empty, String.Empty, String.Empty);
return primeMeridian;
}
#endregion
}
}
| |
/*
* 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 Python.Runtime;
using Newtonsoft.Json;
using NodaTime;
using NUnit.Framework;
using QuantConnect.Algorithm;
using QuantConnect.Algorithm.Selection;
using QuantConnect.AlgorithmFactory.Python.Wrappers;
using QuantConnect.Configuration;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Custom.IconicTypes;
using QuantConnect.Data.Market;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Securities;
using QuantConnect.Tests.Engine.DataFeeds;
using QuantConnect.Util;
using Bitcoin = QuantConnect.Algorithm.CSharp.LiveTradingFeaturesAlgorithm.Bitcoin;
using HistoryRequest = QuantConnect.Data.HistoryRequest;
namespace QuantConnect.Tests.Algorithm
{
[TestFixture]
public class AlgorithmAddDataTests
{
[Test]
public void DefaultDataFeeds_CanBeOverwritten_Successfully()
{
var algo = new QCAlgorithm();
algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo));
// forex defult - should be quotebar
var forexTrade = algo.AddForex("EURUSD");
Assert.IsTrue(forexTrade.Subscriptions.Count() == 1);
Assert.IsTrue(GetMatchingSubscription(algo, forexTrade.Symbol, typeof(QuoteBar)) != null);
// Change
Config.Set("security-data-feeds", "{ Forex: [\"Trade\"] }");
var dataFeedsConfigString = Config.Get("security-data-feeds");
Dictionary<SecurityType, List<TickType>> dataFeeds = new Dictionary<SecurityType, List<TickType>>();
if (dataFeedsConfigString != string.Empty)
{
dataFeeds = JsonConvert.DeserializeObject<Dictionary<SecurityType, List<TickType>>>(dataFeedsConfigString);
}
algo.SetAvailableDataTypes(dataFeeds);
// new forex - should be tradebar
var forexQuote = algo.AddForex("EURUSD");
Assert.IsTrue(forexQuote.Subscriptions.Count() == 1);
Assert.IsTrue(GetMatchingSubscription(algo, forexQuote.Symbol, typeof(TradeBar)) != null);
// reset to empty string, affects other tests because config is static
Config.Set("security-data-feeds", "");
}
[Test]
public void DefaultDataFeeds_AreAdded_Successfully()
{
var algo = new QCAlgorithm();
algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo));
// forex
var forex = algo.AddSecurity(SecurityType.Forex, "eurusd");
Assert.IsTrue(forex.Subscriptions.Count() == 1);
Assert.IsTrue(GetMatchingSubscription(algo, forex.Symbol, typeof(QuoteBar)) != null);
// equity high resolution
var equityMinute = algo.AddSecurity(SecurityType.Equity, "goog");
Assert.IsTrue(equityMinute.Subscriptions.Count() == 2);
Assert.IsTrue(GetMatchingSubscription(algo, equityMinute.Symbol, typeof(TradeBar)) != null);
Assert.IsTrue(GetMatchingSubscription(algo, equityMinute.Symbol, typeof(QuoteBar)) != null);
// equity low resolution
var equityDaily = algo.AddSecurity(SecurityType.Equity, "goog", Resolution.Daily);
Assert.IsTrue(equityDaily.Subscriptions.Count() == 2);
Assert.IsTrue(GetMatchingSubscription(algo, equityDaily.Symbol, typeof(TradeBar)) != null);
// option
var option = algo.AddSecurity(SecurityType.Option, "goog");
Assert.IsTrue(option.Subscriptions.Count() == 1);
Assert.IsTrue(GetMatchingSubscription(algo, option.Symbol, typeof(ZipEntryName)) != null);
// cfd
var cfd = algo.AddSecurity(SecurityType.Cfd, "abc");
Assert.IsTrue(cfd.Subscriptions.Count() == 1);
Assert.IsTrue(GetMatchingSubscription(algo, cfd.Symbol, typeof(QuoteBar)) != null);
// future
var future = algo.AddSecurity(SecurityType.Future, "ES");
Assert.IsTrue(future.Subscriptions.Count() == 1);
Assert.IsTrue(future.Subscriptions.FirstOrDefault(x => typeof(ZipEntryName).IsAssignableFrom(x.Type)) != null);
// Crypto high resolution
var cryptoMinute = algo.AddSecurity(SecurityType.Equity, "goog");
Assert.IsTrue(cryptoMinute.Subscriptions.Count() == 2);
Assert.IsTrue(GetMatchingSubscription(algo, cryptoMinute.Symbol, typeof(TradeBar)) != null);
Assert.IsTrue(GetMatchingSubscription(algo, cryptoMinute.Symbol, typeof(QuoteBar)) != null);
// Crypto low resolution
var cryptoHourly = algo.AddSecurity(SecurityType.Crypto, "btcusd", Resolution.Hour);
Assert.IsTrue(cryptoHourly.Subscriptions.Count() == 2);
Assert.IsTrue(GetMatchingSubscription(algo, cryptoHourly.Symbol, typeof(TradeBar)) != null);
Assert.IsTrue(GetMatchingSubscription(algo, cryptoHourly.Symbol, typeof(QuoteBar)) != null);
}
[Test]
public void CustomDataTypes_AreAddedToSubscriptions_Successfully()
{
var qcAlgorithm = new QCAlgorithm();
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));
// Add a bitcoin subscription
qcAlgorithm.AddData<Bitcoin>("BTC");
var bitcoinSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.FirstOrDefault(x => x.Type == typeof(Bitcoin));
Assert.AreEqual(bitcoinSubscription.Type, typeof(Bitcoin));
// Add a unlinkedData subscription
qcAlgorithm.AddData<UnlinkedData>("EURCAD");
var unlinkedDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.FirstOrDefault(x => x.Type == typeof(UnlinkedData));
Assert.AreEqual(unlinkedDataSubscription.Type, typeof(UnlinkedData));
}
[Test]
public void OnEndOfTimeStepSeedsUnderlyingSecuritiesThatHaveNoData()
{
var qcAlgorithm = new QCAlgorithm();
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm, new MockDataFeed()));
qcAlgorithm.SetLiveMode(true);
var testHistoryProvider = new TestHistoryProvider();
qcAlgorithm.HistoryProvider = testHistoryProvider;
var option = qcAlgorithm.AddSecurity(SecurityType.Option, testHistoryProvider.underlyingSymbol);
var option2 = qcAlgorithm.AddSecurity(SecurityType.Option, testHistoryProvider.underlyingSymbol2);
Assert.IsFalse(qcAlgorithm.Securities.ContainsKey(option.Symbol.Underlying));
Assert.IsFalse(qcAlgorithm.Securities.ContainsKey(option2.Symbol.Underlying));
qcAlgorithm.OnEndOfTimeStep();
var data = qcAlgorithm.Securities[testHistoryProvider.underlyingSymbol].GetLastData();
var data2 = qcAlgorithm.Securities[testHistoryProvider.underlyingSymbol2].GetLastData();
Assert.IsNotNull(data);
Assert.IsNotNull(data2);
Assert.AreEqual(data.Price, 2);
Assert.AreEqual(data2.Price, 3);
}
[Test, Parallelizable(ParallelScope.Self)]
public void OnEndOfTimeStepDoesNotThrowWhenSeedsSameUnderlyingForTwoSecurities()
{
var qcAlgorithm = new QCAlgorithm();
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm, new MockDataFeed()));
qcAlgorithm.SetLiveMode(true);
var testHistoryProvider = new TestHistoryProvider();
qcAlgorithm.HistoryProvider = testHistoryProvider;
var option = qcAlgorithm.AddOption(testHistoryProvider.underlyingSymbol);
var symbol = Symbol.CreateOption(testHistoryProvider.underlyingSymbol, Market.USA, OptionStyle.American,
OptionRight.Call, 1, new DateTime(2015, 12, 24));
var symbol2 = Symbol.CreateOption(testHistoryProvider.underlyingSymbol, Market.USA, OptionStyle.American,
OptionRight.Put, 1, new DateTime(2015, 12, 24));
var optionContract = qcAlgorithm.AddOptionContract(symbol);
var optionContract2 = qcAlgorithm.AddOptionContract(symbol2);
qcAlgorithm.OnEndOfTimeStep();
var data = qcAlgorithm.Securities[testHistoryProvider.underlyingSymbol].GetLastData();
Assert.AreEqual(testHistoryProvider.LastResolutionRequest, Resolution.Minute);
Assert.IsNotNull(data);
Assert.AreEqual(data.Price, 2);
}
[TestCase("EURUSD", typeof(IndexedLinkedData), SecurityType.Cfd, false, true)]
[TestCase("BTCUSD", typeof(IndexedLinkedData), SecurityType.Crypto, false, true)]
[TestCase("CL", typeof(IndexedLinkedData), SecurityType.Future, true, true)]
[TestCase("EURUSD", typeof(IndexedLinkedData), SecurityType.Forex, false, true)]
[TestCase("AAPL", typeof(IndexedLinkedData), SecurityType.Equity, true, true)]
[TestCase("EURUSD", typeof(UnlinkedData), SecurityType.Cfd, false, false)]
[TestCase("BTCUSD", typeof(UnlinkedData), SecurityType.Crypto, false, false)]
[TestCase("CL", typeof(UnlinkedData), SecurityType.Future, true, false)]
[TestCase("AAPL", typeof(UnlinkedData), SecurityType.Equity, true, false)]
[TestCase("EURUSD", typeof(UnlinkedData), SecurityType.Forex, false, false)]
public void AddDataSecuritySymbolWithUnderlying(string ticker, Type customDataType, SecurityType securityType, bool securityShouldBeMapped, bool customDataShouldBeMapped)
{
SymbolCache.Clear();
var qcAlgorithm = new QCAlgorithm();
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));
Security asset;
switch (securityType)
{
case SecurityType.Cfd:
asset = qcAlgorithm.AddCfd(ticker, Resolution.Daily);
break;
case SecurityType.Crypto:
asset = qcAlgorithm.AddCrypto(ticker, Resolution.Daily);
break;
case SecurityType.Equity:
asset = qcAlgorithm.AddEquity(ticker, Resolution.Daily);
break;
case SecurityType.Forex:
asset = qcAlgorithm.AddForex(ticker, Resolution.Daily);
break;
case SecurityType.Future:
asset = qcAlgorithm.AddFuture(ticker, Resolution.Minute);
break;
default:
throw new Exception($"SecurityType {securityType} is not valid for this test");
}
// Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority
// in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it.
// This covers the case where two idential data subscriptions are created.
var dummy = qcAlgorithm.AddData(customDataType, asset.Symbol, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone);
var customData = qcAlgorithm.AddData(customDataType, asset.Symbol, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone);
Assert.IsTrue(customData.Symbol.HasUnderlying, $"{customDataType.Name} added as {ticker} Symbol with SecurityType {securityType} does not have underlying");
Assert.AreEqual(customData.Symbol.Underlying, asset.Symbol, $"Custom data underlying does not match {securityType} Symbol for {ticker}");
var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First();
var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single();
var assetShouldBeMapped = assetSubscription.TickerShouldBeMapped();
var customShouldBeMapped = customDataSubscription.TickerShouldBeMapped();
Assert.AreEqual(securityShouldBeMapped, assetShouldBeMapped);
Assert.AreEqual(customDataShouldBeMapped, customShouldBeMapped);
Assert.AreNotEqual(assetSubscription, customDataSubscription);
if (assetShouldBeMapped == customShouldBeMapped)
{
Assert.AreEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol);
Assert.AreEqual(asset.Symbol.Value, customData.Symbol.Value.Split('.').First());
}
}
[TestCase("EURUSD", typeof(IndexedLinkedData), SecurityType.Cfd, false, false)]
[TestCase("BTCUSD", typeof(IndexedLinkedData), SecurityType.Crypto, false, false)]
[TestCase("CL", typeof(IndexedLinkedData), SecurityType.Future, false, false)]
[TestCase("EURUSD", typeof(IndexedLinkedData), SecurityType.Forex, false, false)]
[TestCase("AAPL", typeof(IndexedLinkedData), SecurityType.Equity, true, true)]
public void AddDataSecurityTickerWithUnderlying(string ticker, Type customDataType, SecurityType securityType, bool securityShouldBeMapped, bool customDataShouldBeMapped)
{
SymbolCache.Clear();
var qcAlgorithm = new QCAlgorithm();
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));
Security asset;
switch (securityType)
{
case SecurityType.Cfd:
asset = qcAlgorithm.AddCfd(ticker, Resolution.Daily);
break;
case SecurityType.Crypto:
asset = qcAlgorithm.AddCrypto(ticker, Resolution.Daily);
break;
case SecurityType.Equity:
asset = qcAlgorithm.AddEquity(ticker, Resolution.Daily);
break;
case SecurityType.Forex:
asset = qcAlgorithm.AddForex(ticker, Resolution.Daily);
break;
case SecurityType.Future:
asset = qcAlgorithm.AddFuture(ticker, Resolution.Minute);
break;
default:
throw new Exception($"SecurityType {securityType} is not valid for this test");
}
// Aliased value for Futures contains a forward-slash, which causes the
// lookup in the SymbolCache to fail
if (securityType == SecurityType.Future)
{
ticker = asset.Symbol.Value;
}
// Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority
// in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it.
// This covers the case where two idential data subscriptions are created.
var dummy = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone);
var customData = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone);
Assert.IsTrue(customData.Symbol.HasUnderlying, $"Custom data added as {ticker} Symbol with SecurityType {securityType} does not have underlying");
Assert.AreEqual(customData.Symbol.Underlying, asset.Symbol, $"Custom data underlying does not match {securityType} Symbol for {ticker}");
var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First();
var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single();
var assetShouldBeMapped = assetSubscription.TickerShouldBeMapped();
var customShouldBeMapped = customDataSubscription.TickerShouldBeMapped();
if (securityType == SecurityType.Equity)
{
Assert.AreEqual(securityShouldBeMapped, assetShouldBeMapped);
Assert.AreEqual(customDataShouldBeMapped, customShouldBeMapped);
Assert.AreNotEqual(assetSubscription, customDataSubscription);
if (assetShouldBeMapped == customShouldBeMapped)
{
Assert.AreEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol);
Assert.AreEqual(asset.Symbol.Value, customData.Symbol.Value.Split('.').First());
}
}
}
[TestCase("EURUSD", typeof(UnlinkedData), SecurityType.Cfd, false, false)]
[TestCase("BTCUSD", typeof(UnlinkedData), SecurityType.Crypto, false, false)]
[TestCase("CL", typeof(UnlinkedData), SecurityType.Future, true, false)]
[TestCase("AAPL", typeof(UnlinkedData), SecurityType.Equity, true, false)]
[TestCase("EURUSD", typeof(UnlinkedData), SecurityType.Forex, false, false)]
public void AddDataSecurityTickerNoUnderlying(string ticker, Type customDataType, SecurityType securityType, bool securityShouldBeMapped, bool customDataShouldBeMapped)
{
SymbolCache.Clear();
var qcAlgorithm = new QCAlgorithm();
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));
Security asset;
switch (securityType)
{
case SecurityType.Cfd:
asset = qcAlgorithm.AddCfd(ticker, Resolution.Daily);
break;
case SecurityType.Crypto:
asset = qcAlgorithm.AddCrypto(ticker, Resolution.Daily);
break;
case SecurityType.Equity:
asset = qcAlgorithm.AddEquity(ticker, Resolution.Daily);
break;
case SecurityType.Forex:
asset = qcAlgorithm.AddForex(ticker, Resolution.Daily);
break;
case SecurityType.Future:
asset = qcAlgorithm.AddFuture(ticker, Resolution.Minute);
break;
default:
throw new Exception($"SecurityType {securityType} is not valid for this test");
}
// Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority
// in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it.
// This covers the case where two idential data subscriptions are created.
var dummy = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone);
var customData = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone);
// Check to see if we have an underlying symbol when we shouldn't
Assert.IsFalse(customData.Symbol.HasUnderlying, $"{customDataType.Name} has underlying symbol for SecurityType {securityType} with ticker {ticker}");
Assert.AreEqual(customData.Symbol.Underlying, null, $"{customDataType.Name} - Custom data underlying Symbol for SecurityType {securityType} is not null");
var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First();
var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single();
var assetShouldBeMapped = assetSubscription.TickerShouldBeMapped();
var customShouldBeMapped = customDataSubscription.TickerShouldBeMapped();
Assert.AreEqual(securityShouldBeMapped, assetShouldBeMapped);
Assert.AreEqual(customDataShouldBeMapped, customShouldBeMapped);
Assert.AreNotEqual(assetSubscription, customDataSubscription);
if (assetShouldBeMapped == customShouldBeMapped)
{
// Would fail with CL future without this check because MappedSymbol returns "/CL" for the Future symbol
if (assetSubscription.SecurityType == SecurityType.Future)
{
Assert.AreNotEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol);
Assert.AreNotEqual(asset.Symbol.Value, customData.Symbol.Value.Split('.').First());
}
else
{
Assert.AreEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol);
Assert.AreEqual(asset.Symbol.Value, customData.Symbol.Value.Split('.').First());
}
}
}
[Test]
public void AddOptionWithUnderlyingFuture()
{
// Adds an option containing a Future as its underlying Symbol.
// This is an essential step in enabling custom derivatives
// based on any asset class provided to Option. This test
// checks the ability to create Future Options.
var algo = new QCAlgorithm();
algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo));
var underlying = algo.AddFuture("ES", Resolution.Minute, Market.CME);
underlying.SetFilter(0, 365);
var futureOption = algo.AddOption(underlying.Symbol, Resolution.Minute);
Assert.IsTrue(futureOption.Symbol.HasUnderlying);
Assert.AreEqual(underlying.Symbol, futureOption.Symbol.Underlying);
}
[Test]
public void AddFutureOptionContractNonEquityOption()
{
// Adds an option contract containing an underlying future contract.
// We test to make sure that the security returned is a specific option
// contract and with the future as the underlying.
var algo = new QCAlgorithm();
algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo));
var underlying = algo.AddFutureContract(
Symbol.CreateFuture("ES", Market.CME, new DateTime(2021, 3, 19)),
Resolution.Minute);
var futureOptionContract = algo.AddFutureOptionContract(
Symbol.CreateOption(underlying.Symbol, Market.CME, OptionStyle.American, OptionRight.Call, 2550m, new DateTime(2021, 3, 19)),
Resolution.Minute);
Assert.AreEqual(underlying.Symbol, futureOptionContract.Symbol.Underlying);
Assert.AreEqual(underlying, futureOptionContract.Underlying);
Assert.IsFalse(underlying.Symbol.IsCanonical());
Assert.IsFalse(futureOptionContract.Symbol.IsCanonical());
}
[Test]
public void AddFutureOptionAddsUniverseSelectionModel()
{
var algo = new QCAlgorithm();
algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo));
var underlying = algo.AddFuture("ES", Resolution.Minute, Market.CME);
underlying.SetFilter(0, 365);
algo.AddFutureOption(underlying.Symbol, _ => _);
Assert.IsTrue(algo.UniverseSelection is OptionChainedUniverseSelectionModel);
}
[TestCase("AAPL", typeof(IndexedLinkedData), true)]
[TestCase("TWX", typeof(IndexedLinkedData), true)]
[TestCase("FB", typeof(IndexedLinkedData), true)]
[TestCase("NFLX", typeof(IndexedLinkedData), true)]
[TestCase("TWX", typeof(UnlinkedData), false)]
[TestCase("AAPL", typeof(UnlinkedData), false)]
public void AddDataOptionsSymbolHasChainedUnderlyingSymbols(string ticker, Type customDataType, bool customDataShouldBeMapped)
{
SymbolCache.Clear();
var qcAlgorithm = new QCAlgorithm();
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));
var asset = qcAlgorithm.AddOption(ticker);
// Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority
// in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it.
// This covers the case where two idential data subscriptions are created.
var dummy = qcAlgorithm.AddData(customDataType, asset.Symbol, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone);
var customData = qcAlgorithm.AddData(customDataType, asset.Symbol, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone);
// Check to see if we have an underlying symbol when we shouldn't
Assert.IsTrue(customData.Symbol.HasUnderlying, $"{customDataType.Name} - {ticker} has no underlying Symbol");
Assert.AreEqual(customData.Symbol.Underlying, asset.Symbol);
Assert.AreEqual(customData.Symbol.Underlying.Underlying, asset.Symbol.Underlying);
Assert.AreEqual(customData.Symbol.Underlying.Underlying.Underlying, null);
var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single();
var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single();
Assert.IsTrue(assetSubscription.TickerShouldBeMapped());
Assert.AreEqual(customDataShouldBeMapped, customDataSubscription.TickerShouldBeMapped());
Assert.AreEqual($"?{assetSubscription.MappedSymbol}", customDataSubscription.MappedSymbol);
}
[TestCase("AAPL", typeof(IndexedLinkedData))]
[TestCase("TWX", typeof(IndexedLinkedData))]
[TestCase("FB", typeof(IndexedLinkedData))]
[TestCase("NFLX", typeof(IndexedLinkedData))]
public void AddDataOptionsTickerHasChainedUnderlyingSymbol(string ticker, Type customDataType)
{
SymbolCache.Clear();
var qcAlgorithm = new QCAlgorithm();
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));
var asset = qcAlgorithm.AddOption(ticker);
// Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority
// in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it.
// This covers the case where two idential data subscriptions are created.
var dummy = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone);
var customData = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone);
// Check to see if we have an underlying symbol when we shouldn't
Assert.IsTrue(customData.Symbol.HasUnderlying, $"{customDataType.Name} - {ticker} has no underlying Symbol");
Assert.AreNotEqual(customData.Symbol.Underlying, asset.Symbol);
Assert.IsFalse(customData.Symbol.Underlying.HasUnderlying);
Assert.AreEqual(customData.Symbol.Underlying, asset.Symbol.Underlying);
var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single();
var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single();
Assert.IsTrue(assetSubscription.TickerShouldBeMapped());
Assert.IsTrue(customDataSubscription.TickerShouldBeMapped());
Assert.AreEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol);
}
[TestCase("AAPL", typeof(UnlinkedData))]
[TestCase("FDTR", typeof(UnlinkedData))]
public void AddDataOptionsTickerHasNoChainedUnderlyingSymbols(string ticker, Type customDataType)
{
SymbolCache.Clear();
var qcAlgorithm = new QCAlgorithm();
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));
var asset = qcAlgorithm.AddOption(ticker);
// Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority
// in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it.
// This covers the case where two idential data subscriptions are created.
var dummy = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone);
var customData = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone);
// Check to see if we have an underlying symbol when we shouldn't
Assert.IsFalse(customData.Symbol.HasUnderlying, $"{customDataType.Name} has an underlying Symbol");
var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single();
var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single();
Assert.IsTrue(assetSubscription.TickerShouldBeMapped());
Assert.IsFalse(customDataSubscription.TickerShouldBeMapped());
//Assert.AreNotEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol);
}
[Test]
public void PythonCustomDataTypes_AreAddedToSubscriptions_Successfully()
{
var qcAlgorithm = new AlgorithmPythonWrapper("Test_CustomDataAlgorithm");
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));
// Initialize contains the statements:
// self.AddData(Nifty, "NIFTY")
// self.AddData(CustomPythonData, "IBM", Resolution.Daily)
qcAlgorithm.Initialize();
var niftySubscription = qcAlgorithm.SubscriptionManager.Subscriptions.FirstOrDefault(x => x.Symbol.Value == "NIFTY");
Assert.IsNotNull(niftySubscription);
var niftyFactory = (BaseData)ObjectActivator.GetActivator(niftySubscription.Type).Invoke(new object[] { niftySubscription.Type });
Assert.DoesNotThrow(() => niftyFactory.GetSource(niftySubscription, DateTime.UtcNow, false));
var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.FirstOrDefault(x => x.Symbol.Value == "IBM");
Assert.IsNotNull(customDataSubscription);
Assert.IsTrue(customDataSubscription.IsCustomData);
Assert.AreEqual("custom_data.CustomPythonData", customDataSubscription.Type.ToString());
var customDataFactory = (BaseData)ObjectActivator.GetActivator(customDataSubscription.Type).Invoke(new object[] { customDataSubscription.Type });
Assert.DoesNotThrow(() => customDataFactory.GetSource(customDataSubscription, DateTime.UtcNow, false));
}
[Test]
public void PythonCustomDataTypes_AreAddedToConsolidator_Successfully()
{
var qcAlgorithm = new AlgorithmPythonWrapper("Test_CustomDataAlgorithm");
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));
// Initialize contains the statements:
// self.AddData(Nifty, "NIFTY")
// self.AddData(CustomPythonData, "IBM", Resolution.Daily)
qcAlgorithm.Initialize();
var niftyConsolidator = new DynamicDataConsolidator(TimeSpan.FromDays(2));
Assert.DoesNotThrow(() => qcAlgorithm.SubscriptionManager.AddConsolidator("NIFTY", niftyConsolidator));
var customDataConsolidator = new DynamicDataConsolidator(TimeSpan.FromDays(2));
Assert.DoesNotThrow(() => qcAlgorithm.SubscriptionManager.AddConsolidator("IBM", customDataConsolidator));
}
[Test]
public void AddingInvalidDataTypeThrows()
{
var qcAlgorithm = new QCAlgorithm();
qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));
Assert.Throws<ArgumentException>(() => qcAlgorithm.AddData(typeof(double),
"double",
Resolution.Daily,
DateTimeZone.Utc));
}
[Test]
public void AppendsCustomDataTypeName_ToSecurityIdentifierSymbol()
{
const string ticker = "ticker";
var algorithm = Algorithm();
var security = algorithm.AddData<UnlinkedData>(ticker);
Assert.AreEqual(ticker.ToUpperInvariant(), security.Symbol.Value);
Assert.AreEqual($"{ticker.ToUpperInvariant()}.{typeof(UnlinkedData).Name}", security.Symbol.ID.Symbol);
Assert.AreEqual(SecurityIdentifier.GenerateBaseSymbol(typeof(UnlinkedData), ticker), security.Symbol.ID.Symbol);
}
[Test]
public void RegistersSecurityIdentifierSymbol_AsTickerString_InSymbolCache()
{
var algorithm = Algorithm();
Symbol cachedSymbol;
var security = algorithm.AddData<UnlinkedData>("ticker");
var symbolCacheAlias = security.Symbol.ID.Symbol;
Assert.IsTrue(SymbolCache.TryGetSymbol(symbolCacheAlias, out cachedSymbol));
Assert.AreSame(security.Symbol, cachedSymbol);
}
[Test]
public void DoesNotCauseCollision_WhenRegisteringMultipleDifferentCustomDataTypes_WithSameTicker()
{
const string ticker = "ticker";
var algorithm = Algorithm();
var security1 = algorithm.AddData<UnlinkedData>(ticker);
var security2 = algorithm.AddData<Bitcoin>(ticker);
var unlinkedData = algorithm.Securities[security1.Symbol];
Assert.AreSame(security1, unlinkedData);
var bitcoin = algorithm.Securities[security2.Symbol];
Assert.AreSame(security2, bitcoin);
Assert.AreNotSame(unlinkedData, bitcoin);
}
private static SubscriptionDataConfig GetMatchingSubscription(QCAlgorithm algorithm, Symbol symbol, Type type)
{
// find a subscription matchin the requested type with a higher resolution than requested
return algorithm.SubscriptionManager.SubscriptionDataConfigService
.GetSubscriptionDataConfigs(symbol)
.Where(config => type.IsAssignableFrom(config.Type))
.OrderByDescending(s => s.Resolution)
.FirstOrDefault();
}
private static QCAlgorithm Algorithm()
{
var algorithm = new QCAlgorithm();
algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
return algorithm;
}
private class TestHistoryProvider : HistoryProviderBase
{
public string underlyingSymbol = "GOOG";
public string underlyingSymbol2 = "AAPL";
public override int DataPointCount { get; }
public Resolution LastResolutionRequest;
public override void Initialize(HistoryProviderInitializeParameters parameters)
{
throw new NotImplementedException();
}
public override IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> requests, DateTimeZone sliceTimeZone)
{
var now = DateTime.UtcNow;
LastResolutionRequest = requests.First().Resolution;
var tradeBar1 = new TradeBar(now, underlyingSymbol, 1, 1, 1, 1, 1, TimeSpan.FromDays(1));
var tradeBar2 = new TradeBar(now, underlyingSymbol2, 3, 3, 3, 3, 3, TimeSpan.FromDays(1));
var slice1 = new Slice(now, new List<BaseData> { tradeBar1, tradeBar2 },
new TradeBars(now), new QuoteBars(),
new Ticks(), new OptionChains(),
new FuturesChains(), new Splits(),
new Dividends(now), new Delistings(),
new SymbolChangedEvents());
var tradeBar1_2 = new TradeBar(now, underlyingSymbol, 2, 2, 2, 2, 2, TimeSpan.FromDays(1));
var slice2 = new Slice(now, new List<BaseData> { tradeBar1_2 },
new TradeBars(now), new QuoteBars(),
new Ticks(), new OptionChains(),
new FuturesChains(), new Splits(),
new Dividends(now), new Delistings(),
new SymbolChangedEvents());
return new[] { slice1, slice2 };
}
}
}
}
| |
// 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 Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class AttributeSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new AttributeSignatureHelpProvider();
}
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutParameters()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
}
[[|Something($$|]]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <summary>Summary For Attribute</summary>
public SomethingAttribute() { }
}
[[|Something($$|]]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", "Summary For Attribute", null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn1()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public SomethingAttribute(int someInteger, string someString) { }
}
[[|Something($$|]]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <summary>
/// Summary For Attribute
/// </summary>
/// <param name=""someInteger"">Param someInteger</param>
/// <param name=""someString"">Param someString</param>
public SomethingAttribute(int someInteger, string someString) { }
}
[[|Something($$
|]class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someInteger", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn2()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public SomethingAttribute(int someInteger, string someString) { }
}
[[|Something(22, $$|]]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <summary>
/// Summary For Attribute
/// </summary>
/// <param name=""someInteger"">Param someInteger</param>
/// <param name=""someString"">Param someString</param>
public SomethingAttribute(int someInteger, string someString) { }
}
[[|Something(22, $$
|]class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someInteger, string someString)", "Summary For Attribute", "Param someString", currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithClosingParen()
{
var markup = @"
class SomethingAttribute : System.Attribute
{ }
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationSpan1()
{
Test(
@"using System;
class C
{
[[|Obsolete($$|])]
void Foo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationSpan2()
{
Test(
@"using System;
class C
{
[[|Obsolete( $$|])]
void Foo()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationSpan3()
{
Test(
@"using System;
class C
{
[[|Obsolete(
$$|]]
void Foo()
{
}
}");
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestCurrentParameterName()
{
var markup = @"
using System;
class SomethingAttribute : Attribute
{
public SomethingAttribute(int someParameter, bool somethingElse) { }
}
[[|Something(somethingElse: false, someParameter: $$22|])]
class C
{
}";
VerifyCurrentParameterName(markup, "someParameter");
}
#endregion
#region "Setting fields in attributes"
[WorkItem(545425)]
[WorkItem(544139)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithValidField()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo;
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute({CSharpEditorResources.Properties}: [foo = int])", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithInvalidFieldReadonly()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public readonly int foo;
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithInvalidFieldStatic()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public static int foo;
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithInvalidFieldConst()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public const int foo = 42;
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
#endregion
#region "Setting properties in attributes"
[WorkItem(545425)]
[WorkItem(544139)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithValidProperty()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo { get; set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute({CSharpEditorResources.Properties}: [foo = int])", string.Empty, string.Empty, currentParameterIndex: 0));
// TODO: Bug 12319: Enable tests for script when this is fixed.
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithInvalidPropertyStatic()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public static int foo { get; set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithInvalidPropertyNoSetter()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo { get { return 0; } }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithInvalidPropertyNoGetter()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo { set { } }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithInvalidPropertyPrivateGetter()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo { private get; set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithInvalidPropertyPrivateSetter()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
public int foo { get; private set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
#endregion
#region "Setting fields and arguments"
[WorkItem(545425)]
[WorkItem(544139)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithArgumentsAndNamedParameters1()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <param name=""foo"">FooParameter</param>
/// <param name=""bar"">BarParameter</param>
public SomethingAttribute(int foo = 0, string bar = null) { }
public int fieldfoo { get; set; }
public string fieldbar { get; set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int foo = 0], [string bar = null], {CSharpEditorResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "FooParameter", currentParameterIndex: 0));
// TODO: Bug 12319: Enable tests for script when this is fixed.
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[WorkItem(545425)]
[WorkItem(544139)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithArgumentsAndNamedParameters2()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <param name=""foo"">FooParameter</param>
/// <param name=""bar"">BarParameter</param>
public SomethingAttribute(int foo = 0, string bar = null) { }
public int fieldfoo { get; set; }
public string fieldbar { get; set; }
}
[[|Something(22, $$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int foo = 0], [string bar = null], {CSharpEditorResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, "BarParameter", currentParameterIndex: 1));
// TODO: Bug 12319: Enable tests for script when this is fixed.
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[WorkItem(545425)]
[WorkItem(544139)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithArgumentsAndNamedParameters3()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <param name=""foo"">FooParameter</param>
/// <param name=""bar"">BarParameter</param>
public SomethingAttribute(int foo = 0, string bar = null) { }
public int fieldfoo { get; set; }
public string fieldbar { get; set; }
}
[[|Something(22, null, $$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int foo = 0], [string bar = null], {CSharpEditorResources.Properties}: [fieldbar = string], [fieldfoo = int])", string.Empty, string.Empty, currentParameterIndex: 2));
// TODO: Bug 12319: Enable tests for script when this is fixed.
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[WorkItem(545425)]
[WorkItem(544139)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithOptionalArgumentAndNamedParameterWithSameName1()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <param name=""foo"">FooParameter</param>
public SomethingAttribute(int foo = 0) { }
public int foo { get; set; }
}
[[|Something($$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int foo = 0], {CSharpEditorResources.Properties}: [foo = int])", string.Empty, "FooParameter", currentParameterIndex: 0));
// TODO: Bug 12319: Enable tests for script when this is fixed.
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
[WorkItem(545425)]
[WorkItem(544139)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestAttributeWithOptionalArgumentAndNamedParameterWithSameName2()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
/// <param name=""foo"">FooParameter</param>
public SomethingAttribute(int foo = 0) { }
public int foo { get; set; }
}
[[|Something(22, $$|])]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"SomethingAttribute([int foo = 0], {CSharpEditorResources.Properties}: [foo = int])", string.Empty, string.Empty, currentParameterIndex: 1));
// TODO: Bug 12319: Enable tests for script when this is fixed.
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: false);
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerParens()
{
var markup = @"
using System;
class SomethingAttribute : Attribute
{
public SomethingAttribute(int someParameter, bool somethingElse) { }
}
[[|Something($$|])]
class C
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerComma()
{
var markup = @"
using System;
class SomethingAttribute : Attribute
{
public SomethingAttribute(int someParameter, bool somethingElse) { }
}
[[|Something(22,$$|])]
class C
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("SomethingAttribute(int someParameter, bool somethingElse)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestNoInvocationOnSpace()
{
var markup = @"
using System;
class SomethingAttribute : Attribute
{
public SomethingAttribute(int someParameter, bool somethingElse) { }
}
[[|Something(22, $$|])]
class C
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, 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")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Attribute_BrowsableAlways()
{
var markup = @"
[MyAttribute($$
class Program
{
}";
var referencedCode = @"
public class MyAttribute
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public MyAttribute(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Attribute_BrowsableNever()
{
var markup = @"
[MyAttribute($$
class Program
{
}";
var referencedCode = @"
public class MyAttribute
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public MyAttribute(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Attribute_BrowsableAdvanced()
{
var markup = @"
[MyAttribute($$
class Program
{
}";
var referencedCode = @"
public class MyAttribute
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public MyAttribute(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Attribute_BrowsableMixed()
{
var markup = @"
[MyAttribute($$
class Program
{
}";
var referencedCode = @"
public class MyAttribute
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public MyAttribute(int x)
{
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public MyAttribute(int x, int y)
{
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("MyAttribute(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("MyAttribute(int x, int y)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret : System.Attribute
{
}
#endif
[Secret($$
void Foo()
{
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"Secret()\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);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret : System.Attribute
{
}
#endif
#if BAR
[Secret($$
void Foo()
{
}
#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($"Secret()\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);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[WorkItem(1067933)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InvokedWithNoToken()
{
var markup = @"
// [foo($$";
Test(markup);
}
[WorkItem(1081535)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithBadParameterList()
{
var markup = @"
class SomethingAttribute : System.Attribute
{
}
[Something{$$]
class D
{
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
Test(markup, expectedOrderedItems);
}
}
}
| |
// 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.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.HttpLogging
{
/// <summary>
/// Middleware that logs HTTP requests and HTTP responses.
/// </summary>
internal sealed class HttpLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
private readonly IOptionsMonitor<HttpLoggingOptions> _options;
private const int DefaultRequestFieldsMinusHeaders = 7;
private const int DefaultResponseFieldsMinusHeaders = 2;
private const string Redacted = "[Redacted]";
/// <summary>
/// Initializes <see cref="HttpLoggingMiddleware" />.
/// </summary>
/// <param name="next"></param>
/// <param name="options"></param>
/// <param name="logger"></param>
public HttpLoggingMiddleware(RequestDelegate next, IOptionsMonitor<HttpLoggingOptions> options, ILogger<HttpLoggingMiddleware> logger)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
_options = options;
_logger = logger;
}
/// <summary>
/// Invokes the <see cref="HttpLoggingMiddleware" />.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>HttpResponseLog.cs
public Task Invoke(HttpContext context)
{
if (!_logger.IsEnabled(LogLevel.Information))
{
// Logger isn't enabled.
return _next(context);
}
return InvokeInternal(context);
}
private async Task InvokeInternal(HttpContext context)
{
var options = _options.CurrentValue;
RequestBufferingStream? requestBufferingStream = null;
Stream? originalBody = null;
if ((HttpLoggingFields.Request & options.LoggingFields) != HttpLoggingFields.None)
{
var request = context.Request;
var list = new List<KeyValuePair<string, object?>>(
request.Headers.Count + DefaultRequestFieldsMinusHeaders);
if (options.LoggingFields.HasFlag(HttpLoggingFields.RequestProtocol))
{
AddToList(list, nameof(request.Protocol), request.Protocol);
}
if (options.LoggingFields.HasFlag(HttpLoggingFields.RequestMethod))
{
AddToList(list, nameof(request.Method), request.Method);
}
if (options.LoggingFields.HasFlag(HttpLoggingFields.RequestScheme))
{
AddToList(list, nameof(request.Scheme), request.Scheme);
}
if (options.LoggingFields.HasFlag(HttpLoggingFields.RequestPath))
{
AddToList(list, nameof(request.PathBase), request.PathBase);
AddToList(list, nameof(request.Path), request.Path);
}
if (options.LoggingFields.HasFlag(HttpLoggingFields.RequestQuery))
{
AddToList(list, nameof(request.QueryString), request.QueryString.Value);
}
if (options.LoggingFields.HasFlag(HttpLoggingFields.RequestHeaders))
{
FilterHeaders(list, request.Headers, options._internalRequestHeaders);
}
if (options.LoggingFields.HasFlag(HttpLoggingFields.RequestBody))
{
if (MediaTypeHelpers.TryGetEncodingForMediaType(request.ContentType,
options.MediaTypeOptions.MediaTypeStates,
out var encoding))
{
originalBody = request.Body;
requestBufferingStream = new RequestBufferingStream(
request.Body,
options.RequestBodyLogLimit,
_logger,
encoding);
request.Body = requestBufferingStream;
}
else
{
_logger.UnrecognizedMediaType();
}
}
var httpRequestLog = new HttpRequestLog(list);
_logger.RequestLog(httpRequestLog);
}
ResponseBufferingStream? responseBufferingStream = null;
IHttpResponseBodyFeature? originalBodyFeature = null;
try
{
var response = context.Response;
if (options.LoggingFields.HasFlag(HttpLoggingFields.ResponseBody))
{
originalBodyFeature = context.Features.Get<IHttpResponseBodyFeature>()!;
// TODO pool these.
responseBufferingStream = new ResponseBufferingStream(originalBodyFeature,
options.ResponseBodyLogLimit,
_logger,
context,
options.MediaTypeOptions.MediaTypeStates,
options);
response.Body = responseBufferingStream;
context.Features.Set<IHttpResponseBodyFeature>(responseBufferingStream);
}
await _next(context);
if (requestBufferingStream?.HasLogged == false)
{
// If the middleware pipeline didn't read until 0 was returned from readasync,
// make sure we log the request body.
requestBufferingStream.LogRequestBody();
}
if (responseBufferingStream == null || responseBufferingStream.FirstWrite == false)
{
// No body, write headers here.
LogResponseHeaders(response, options, _logger);
}
if (responseBufferingStream != null)
{
var responseBody = responseBufferingStream.GetString(responseBufferingStream.Encoding);
if (!string.IsNullOrEmpty(responseBody))
{
_logger.ResponseBody(responseBody);
}
}
}
finally
{
responseBufferingStream?.Dispose();
if (originalBodyFeature != null)
{
context.Features.Set(originalBodyFeature);
}
requestBufferingStream?.Dispose();
if (originalBody != null)
{
context.Request.Body = originalBody;
}
}
}
private static void AddToList(List<KeyValuePair<string, object?>> list, string key, string? value)
{
list.Add(new KeyValuePair<string, object?>(key, value));
}
public static void LogResponseHeaders(HttpResponse response, HttpLoggingOptions options, ILogger logger)
{
var list = new List<KeyValuePair<string, object?>>(
response.Headers.Count + DefaultResponseFieldsMinusHeaders);
if (options.LoggingFields.HasFlag(HttpLoggingFields.ResponseStatusCode))
{
list.Add(new KeyValuePair<string, object?>(nameof(response.StatusCode), response.StatusCode));
}
if (options.LoggingFields.HasFlag(HttpLoggingFields.ResponseHeaders))
{
FilterHeaders(list, response.Headers, options._internalResponseHeaders);
}
var httpResponseLog = new HttpResponseLog(list);
logger.ResponseLog(httpResponseLog);
}
internal static void FilterHeaders(List<KeyValuePair<string, object?>> keyValues,
IHeaderDictionary headers,
HashSet<string> allowedHeaders)
{
foreach (var (key, value) in headers)
{
if (!allowedHeaders.Contains(key))
{
// Key is not among the "only listed" headers.
keyValues.Add(new KeyValuePair<string, object?>(key, Redacted));
continue;
}
keyValues.Add(new KeyValuePair<string, object?>(key, value.ToString()));
}
}
}
}
| |
namespace dropkick.Tasks.Files
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using DeploymentModel;
using Exceptions;
using log4net;
using Magnum.Extensions;
using Path = FileSystem.Path;
public abstract class BaseIoTask :
BaseTask
{
private readonly ILog _fileLog = Logging.WellKnown.FileChanges;
protected readonly Path _path;
protected BaseIoTask(Path path)
{
_path = path;
}
public void LogFileChange(string format, params object[] args)
{
_fileLog.InfoFormat(format, args);
}
protected void ValidateIsFile(DeploymentResult result, string path)
{
if (!(new FileInfo(_path.GetFullPath(path)).Exists)) result.AddAlert("'{0}' does not exist.".FormatWith(path));
if (!_path.IsFile(path)) result.AddError("'{0}' is not a file.".FormatWith(path));
}
protected void ValidateIsDirectory(DeploymentResult result, string path)
{
if (!(new DirectoryInfo(_path.GetFullPath(path)).Exists)) result.AddAlert("'{0}' does not exist and will be created.".FormatWith(path));
if (!_path.IsDirectory(path)) result.AddError("'{0}' is not a directory.".FormatWith(path));
}
protected void ValidatePath(DeploymentResult result, string path)
{
try
{
if (!_path.IsDirectory(path))
{
throw new DeploymentException("'{0}' is not an acceptable path. Must be a directory".FormatWith(path));
}
}
catch (Exception ex)
{
throw new DeploymentException("'{0}' is not an acceptable path. Must be a directory".FormatWith(path), ex);
}
}
protected void CopyDirectory(DeploymentResult result, DirectoryInfo source, DirectoryInfo destination, IEnumerable<Regex> ignoredPatterns)
{
if (!destination.Exists)
{
destination.Create();
}
else
{
RemoveReadOnlyAttributes(destination, result);
}
// Copy all files.
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files.Where(f => !IsIgnored(ignoredPatterns, f)))
{
string fileDestination = _path.Combine(destination.FullName, file.Name);
CopyFileToFile(result, file, new FileInfo(fileDestination));
}
// Process subdirectories.
DirectoryInfo[] dirs = source.GetDirectories();
foreach (var dir in dirs)
{
// Get destination directory.
string destinationDir = _path.Combine(destination.FullName, dir.Name);
// Call CopyDirectory() recursively.
CopyDirectory(result, dir, new DirectoryInfo(destinationDir), ignoredPatterns);
}
}
/// <summary>
/// Determines whether a string matches the given ignore patterns. This is used
/// to ignore files which shouldn't be copied from the source to target directories,
/// e.g. you may first place an App_Offline.htm file into the directory before copying
/// data to it. You wouldn't want to delete the App_Offline.html file while copying files.
/// </summary>
/// <param name="ignorePatterns"></param>
/// <param name="file"></param>
/// <returns></returns>
protected bool IsIgnored(IEnumerable<Regex> ignorePatterns, FileInfo file)
{
bool returnValue = false;
foreach (Regex ignorePattern in ignorePatterns.OrEmptyListIfNull())
{
if (ignorePattern.IsMatch(file.FullName))
{
returnValue = true;
break;
}
}
return returnValue;
}
/// <summary>
/// Clears the contents of a given directory.
/// </summary>
/// <param name="result">The Deployment results.</param>
/// <param name="directory">The directory to clear.</param>
/// <param name="ignoredPatterns">Regular expressions which match the files to ignore, e.g. "[aA]pp_[Oo]ffline\.htm".</param>
protected void CleanDirectoryContents(DeploymentResult result, DirectoryInfo directory, IList<Regex> ignoredPatterns)
{
if (ignoredPatterns == null) ignoredPatterns = new List<Regex>();
// Delete files
FileInfo[] files = directory.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo file in files.Where(f => !IsIgnored(ignoredPatterns, f)))
{
RemoveReadOnlyAttributes(file, result);
File.Delete(file.FullName);
}
//// Delete subdirectories.
//foreach (DirectoryInfo subdirectory in directory.GetDirectories())
//{
// RemoveReadOnlyAttributes(subdirectory, result);
// Directory.Delete(subdirectory.FullName, true);
//}
result.AddGood("'{0}' cleared.".FormatWith(directory.FullName));
}
protected void DeleteDestinationFirst(DirectoryInfo directory, DeploymentResult result)
{
if (directory.Exists)
{
RemoveReadOnlyAttributes(directory, result);
directory.Delete(true);
result.AddGood("'{0}' was successfully deleted".FormatWith(directory.FullName));
//TODO: a delete list?
}
}
private void RemoveReadOnlyAttributes(DirectoryInfo directory, DeploymentResult result)
{
try
{
directory.Attributes = (directory.Attributes & ~FileAttributes.ReadOnly);
foreach (var subdirectory in directory.GetDirectories("*", SearchOption.AllDirectories))
{
subdirectory.Attributes = (subdirectory.Attributes & ~FileAttributes.ReadOnly);
}
foreach (var file in directory.GetFiles("*", SearchOption.AllDirectories))
{
RemoveReadOnlyAttributes(file, result);
}
}
catch (Exception ex)
{
result.AddAlert("Had an issue when attempting to remove directory readonly attributes:{0}{1}", Environment.NewLine, ex.ToString());
// LogFineGrain("[copy][attributeremoval][warning] Had an error when attempting to remove directory/file attributes:{0}{1}",Environment.NewLine,ex.ToString());
}
}
private static void RemoveReadOnlyAttributes(FileInfo file, DeploymentResult result)
{
if (file.IsReadOnly)
{
file.Attributes = (file.Attributes & ~FileAttributes.ReadOnly);
//File.SetAttributes(file.FullName, File.GetAttributes(file.FullName) & ~FileAttributes.ReadOnly);
//destination.IsReadOnly = false;
}
}
protected void CopyFile(DeploymentResult result, string newFileName, string from, string to)
{
if (ExtensionsToString.IsNotEmpty(newFileName))
CopyFileToFile(result, new FileInfo(from), new FileInfo(_path.Combine(to, newFileName)));
else
CopyFileToDirectory(result, new FileInfo(from), new DirectoryInfo(to));
}
private void CopyFileToDirectory(DeploymentResult result, FileInfo source, DirectoryInfo destination)
{
if (!destination.Exists) destination.Create();
CopyFileToFile(result, source, new FileInfo(_path.Combine(destination.FullName, source.Name)));
}
private void CopyFileToFile(DeploymentResult result, FileInfo source, FileInfo destination)
{
var overwrite = destination.Exists;
if (overwrite)
{
RemoveReadOnlyAttributes(destination, result);
}
source.CopyTo(destination.FullName, true);
string copyLogPrefix = "[copy]";
if (overwrite)
{
copyLogPrefix = "[copy][overwrite]";
}
LogFineGrain("{0} '{1}' -> '{2}'", copyLogPrefix, source.FullName, destination.FullName);
//TODO: Adjust for remote pathing
_fileLog.Info(destination.FullName); //log where files are modified
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using NUnit.Engine.Communication.Messages;
namespace NUnit.Engine.Communication.Protocols
{
/// <summary>
/// BinarySerializationProtocol serializes messages in the following format:
///
/// [Message Length (4 bytes)][Serialized Message Content]
///
/// The message content is in binary form as produced by the .NET BinaryFormatter.
/// Each message of length n is serialized as n + 4 bytes.
/// </summary>
public class BinarySerializationProtocol : ISerializationProtocol
{
/// <summary>
/// Maximum length of a message.
/// </summary>
private const int MAX_MESSAGE_LENGTH = 128 * 1024 * 1024; //128 Megabytes.
/// <summary>
/// This MemoryStream object is used to collect receiving bytes to build messages.
/// </summary>
private MemoryStream _receiveMemoryStream = new MemoryStream();
/// <summary>
/// Serializes a message to a byte array to send to remote application.
/// </summary>
/// <param name="message">Message to be serialized</param>
/// <returns>A byte[] containing the message, serialized as per the protocol.</returns>
public byte[] Encode(object message)
{
//Serialize the message to a byte array
var serializedMessage = SerializeMessage(message);
//Check for message length
var messageLength = serializedMessage.Length;
if (messageLength > MAX_MESSAGE_LENGTH)
{
throw new Exception("Message is too big (" + messageLength + " bytes). Max allowed length is " + MAX_MESSAGE_LENGTH + " bytes.");
}
//Create a byte array including the length of the message (4 bytes) and serialized message content
var bytes = new byte[messageLength + 4];
WriteInt32(bytes, 0, messageLength);
Array.Copy(serializedMessage, 0, bytes, 4, messageLength);
//Return serialized message by this protocol
return bytes;
}
/// <summary>
/// Accept an array of bytes and deserialize the messages that are found.
/// A single call may provide no messages, part of a message, a single
/// message or multiple messages. Unused bytes are saved for use as
/// further calls are made.
/// </summary>
/// <param name="receivedBytes">The byte array to be deserialized</param>
/// <returns>An enumeration of TestEngineMessages</returns>
public IEnumerable<TestEngineMessage> Decode(byte[] receivedBytes)
{
// Write all received bytes to the _receiveMemoryStream, which may
// already contain part of a message from a previous call.
_receiveMemoryStream.Write(receivedBytes, 0, receivedBytes.Length);
//Create a list to collect messages
var messages = new List<TestEngineMessage>();
//Read all available messages and add to messages collection
while (ReadSingleMessage(messages)) { }
return messages;
}
public void Reset()
{
if (_receiveMemoryStream.Length > 0)
{
_receiveMemoryStream = new MemoryStream();
}
}
/// <summary>
/// Serializes a message to a byte array to send to remote application.
/// </summary>
/// <param name="message">Message to be serialized</param>
/// <returns>
/// A byte[] containing the message itself, without a prefixed
/// length, serialized according to the protocol.
/// </returns>
internal byte[] SerializeMessage(object message)
{
using (var memoryStream = new MemoryStream())
{
new BinaryFormatter().Serialize(memoryStream, message);
return memoryStream.ToArray();
}
}
/// <summary>
/// Deserializes a message contained in a byte array.
/// </summary>
/// <param name="bytes">A byte[] containing just the message, without a length prefix</param>
/// <returns>An object representing the message encoded in the byte array</returns>
internal object DeserializeMessage(byte[] bytes)
{
using (var memoryStream = new MemoryStream(bytes))
{
try
{
return new BinaryFormatter().Deserialize(memoryStream);
}
catch (Exception exception)
{
Reset(); // reset the received memory stream before the exception is rethrown - otherwise the same erroneous message is received again and again
throw new SerializationException("error while deserializing message", exception);
}
}
}
/// <summary>
/// This method tries to read a single message and add to the messages collection.
/// </summary>
/// <param name="messages">Messages collection to collect messages</param>
/// <returns>
/// Returns a boolean value indicates that if there is a need to re-call this method.
/// </returns>
/// <exception cref="CommunicationException">Throws CommunicationException if message is bigger than maximum allowed message length.</exception>
private bool ReadSingleMessage(ICollection<TestEngineMessage> messages)
{
//Go to the begining of the stream
_receiveMemoryStream.Position = 0;
//If stream has less than 4 bytes, that means we can not even read length of the message
//So, return false to wait more for bytes from remorte application.
if (_receiveMemoryStream.Length < 4)
{
return false;
}
//Read length of the message
var messageLength = ReadInt32(_receiveMemoryStream);
if (messageLength > MAX_MESSAGE_LENGTH)
{
throw new Exception("Message is too big (" + messageLength + " bytes). Max allowed length is " + MAX_MESSAGE_LENGTH + " bytes.");
}
//If message is zero-length (It must not be but good approach to check it)
if (messageLength == 0)
{
//if no more bytes, return immediately
if (_receiveMemoryStream.Length == 4)
{
_receiveMemoryStream = new MemoryStream(); //Clear the stream
return false;
}
//Create a new memory stream from current except first 4-bytes.
var bytes = _receiveMemoryStream.ToArray();
_receiveMemoryStream = new MemoryStream();
_receiveMemoryStream.Write(bytes, 4, bytes.Length - 4);
return true;
}
//If all bytes of the message is not received yet, return to wait more bytes
if (_receiveMemoryStream.Length < (4 + messageLength))
{
_receiveMemoryStream.Position = _receiveMemoryStream.Length;
return false;
}
//Read bytes of serialized message and deserialize it
var serializedMessageBytes = ReadByteArray(_receiveMemoryStream, messageLength);
messages.Add((TestEngineMessage)DeserializeMessage(serializedMessageBytes));
//Read remaining bytes to an array
var remainingBytes = ReadByteArray(_receiveMemoryStream, (int)(_receiveMemoryStream.Length - (4 + messageLength)));
//Re-create the receive memory stream and write remaining bytes
_receiveMemoryStream = new MemoryStream();
_receiveMemoryStream.Write(remainingBytes, 0, remainingBytes.Length);
//Return true to re-call this method to try to read next message
return (remainingBytes.Length > 4);
}
/// <summary>
/// Writes a int value to a byte array from a starting index.
/// </summary>
/// <param name="buffer">Byte array to write int value</param>
/// <param name="startIndex">Start index of byte array to write</param>
/// <param name="number">An integer value to write</param>
private static void WriteInt32(byte[] buffer, int startIndex, int number)
{
buffer[startIndex] = (byte)((number >> 24) & 0xFF);
buffer[startIndex + 1] = (byte)((number >> 16) & 0xFF);
buffer[startIndex + 2] = (byte)((number >> 8) & 0xFF);
buffer[startIndex + 3] = (byte)((number) & 0xFF);
}
/// <summary>
/// Deserializes and returns a serialized integer.
/// </summary>
/// <returns>Deserialized integer</returns>
private static int ReadInt32(Stream stream)
{
var buffer = ReadByteArray(stream, 4);
return ((buffer[0] << 24) |
(buffer[1] << 16) |
(buffer[2] << 8) |
(buffer[3])
);
}
/// <summary>
/// Reads a byte array with specified length.
/// </summary>
/// <param name="stream">Stream to read from</param>
/// <param name="length">Length of the byte array to read</param>
/// <returns>Read byte array</returns>
/// <exception cref="EndOfStreamException">Throws EndOfStreamException if can not read from stream.</exception>
private static byte[] ReadByteArray(Stream stream, int length)
{
var buffer = new byte[length];
var totalRead = 0;
while (totalRead < length)
{
var read = stream.Read(buffer, totalRead, length - totalRead);
if (read <= 0)
{
throw new EndOfStreamException("Can not read from stream! Input stream is closed.");
}
totalRead += read;
}
return buffer;
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
// Source: UIToolkit -- https://github.com/prime31/UIToolkit/blob/master/Assets/Plugins/MiniJSON.cs
// Based on the JSON parser from
// http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
/// All numbers are parsed to doubles.
/// </summary>
public class NGUIJson
{
private const int TOKEN_NONE = 0;
private const int TOKEN_CURLY_OPEN = 1;
private const int TOKEN_CURLY_CLOSE = 2;
private const int TOKEN_SQUARED_OPEN = 3;
private const int TOKEN_SQUARED_CLOSE = 4;
private const int TOKEN_COLON = 5;
private const int TOKEN_COMMA = 6;
private const int TOKEN_STRING = 7;
private const int TOKEN_NUMBER = 8;
private const int TOKEN_TRUE = 9;
private const int TOKEN_FALSE = 10;
private const int TOKEN_NULL = 11;
private const int BUILDER_CAPACITY = 2000;
/// <summary>
/// On decoding, this value holds the position at which the parse failed (-1 = no error).
/// </summary>
protected static int lastErrorIndex = -1;
protected static string lastDecode = "";
/// <summary>
/// Parse the specified JSon file, loading sprite information for the specified atlas.
/// </summary>
static public void LoadSpriteData (UIAtlas atlas, TextAsset asset)
{
if (asset == null || atlas == null) return;
string jsonString = asset.text;
Hashtable decodedHash = jsonDecode(jsonString) as Hashtable;
if (decodedHash == null)
{
Debug.LogWarning("Unable to parse Json file: " + asset.name);
}
else LoadSpriteData(atlas, decodedHash);
asset = null;
Resources.UnloadUnusedAssets();
}
/// <summary>
/// Parse the specified JSon file, loading sprite information for the specified atlas.
/// </summary>
static public void LoadSpriteData (UIAtlas atlas, string jsonData)
{
if (string.IsNullOrEmpty(jsonData) || atlas == null) return;
Hashtable decodedHash = jsonDecode(jsonData) as Hashtable;
if (decodedHash == null)
{
Debug.LogWarning("Unable to parse the provided Json string");
}
else LoadSpriteData(atlas, decodedHash);
}
/// <summary>
/// Parse the specified JSon file, loading sprite information for the specified atlas.
/// </summary>
static void LoadSpriteData (UIAtlas atlas, Hashtable decodedHash)
{
if (decodedHash == null || atlas == null) return;
List<UISpriteData> oldSprites = atlas.spriteList;
atlas.spriteList = new List<UISpriteData>();
Hashtable frames = (Hashtable)decodedHash["frames"];
foreach (System.Collections.DictionaryEntry item in frames)
{
UISpriteData newSprite = new UISpriteData();
newSprite.name = item.Key.ToString();
bool exists = false;
// Check to see if this sprite exists
foreach (UISpriteData oldSprite in oldSprites)
{
if (oldSprite.name.Equals(newSprite.name, StringComparison.OrdinalIgnoreCase))
{
exists = true;
break;
}
}
// Get rid of the extension if the sprite doesn't exist
// The extension is kept for backwards compatibility so it's still possible to update older atlases.
if (!exists)
{
newSprite.name = newSprite.name.Replace(".png", "");
newSprite.name = newSprite.name.Replace(".tga", "");
}
// Extract the info we need from the TexturePacker json file, mainly uvRect and size
Hashtable table = (Hashtable)item.Value;
Hashtable frame = (Hashtable)table["frame"];
int frameX = int.Parse(frame["x"].ToString());
int frameY = int.Parse(frame["y"].ToString());
int frameW = int.Parse(frame["w"].ToString());
int frameH = int.Parse(frame["h"].ToString());
// Read the rotation value
//newSprite.rotated = (bool)table["rotated"];
newSprite.x = frameX;
newSprite.y = frameY;
newSprite.width = frameW;
newSprite.height = frameH;
// Support for trimmed sprites
Hashtable sourceSize = (Hashtable)table["sourceSize"];
Hashtable spriteSize = (Hashtable)table["spriteSourceSize"];
if (spriteSize != null && sourceSize != null)
{
// TODO: Account for rotated sprites
if (frameW > 0)
{
int spriteX = int.Parse(spriteSize["x"].ToString());
int spriteW = int.Parse(spriteSize["w"].ToString());
int sourceW = int.Parse(sourceSize["w"].ToString());
newSprite.paddingLeft = spriteX;
newSprite.paddingRight = sourceW - (spriteX + spriteW);
}
if (frameH > 0)
{
int spriteY = int.Parse(spriteSize["y"].ToString());
int spriteH = int.Parse(spriteSize["h"].ToString());
int sourceH = int.Parse(sourceSize["h"].ToString());
newSprite.paddingTop = spriteY;
newSprite.paddingBottom = sourceH - (spriteY + spriteH);
}
}
// If the sprite was present before, see if we can copy its inner rect
foreach (UISpriteData oldSprite in oldSprites)
{
if (oldSprite.name.Equals(newSprite.name, StringComparison.OrdinalIgnoreCase))
{
newSprite.borderLeft = oldSprite.borderLeft;
newSprite.borderRight = oldSprite.borderRight;
newSprite.borderBottom = oldSprite.borderBottom;
newSprite.borderTop = oldSprite.borderTop;
}
}
// Add this new sprite
atlas.spriteList.Add(newSprite);
}
// Sort imported sprites alphabetically
atlas.spriteList.Sort(CompareSprites);
Debug.Log("Imported " + atlas.spriteList.Count + " sprites");
}
/// <summary>
/// Sprite comparison function for sorting.
/// </summary>
static int CompareSprites (UISpriteData a, UISpriteData b) { return a.name.CompareTo(b.name); }
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
public static object jsonDecode( string json )
{
// save the string for debug information
NGUIJson.lastDecode = json;
if( json != null )
{
char[] charArray = json.ToCharArray();
int index = 0;
bool success = true;
object value = NGUIJson.parseValue( charArray, ref index, ref success );
if( success )
NGUIJson.lastErrorIndex = -1;
else
NGUIJson.lastErrorIndex = index;
return value;
}
else
{
return null;
}
}
/// <summary>
/// Converts a Hashtable / ArrayList / Dictionary(string,string) object into a JSON string
/// </summary>
/// <param name="json">A Hashtable / ArrayList</param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string jsonEncode( object json )
{
var builder = new StringBuilder( BUILDER_CAPACITY );
var success = NGUIJson.serializeValue( json, builder );
return ( success ? builder.ToString() : null );
}
/// <summary>
/// On decoding, this function returns the position at which the parse failed (-1 = no error).
/// </summary>
/// <returns></returns>
public static bool lastDecodeSuccessful()
{
return ( NGUIJson.lastErrorIndex == -1 );
}
/// <summary>
/// On decoding, this function returns the position at which the parse failed (-1 = no error).
/// </summary>
/// <returns></returns>
public static int getLastErrorIndex()
{
return NGUIJson.lastErrorIndex;
}
/// <summary>
/// If a decoding error occurred, this function returns a piece of the JSON string
/// at which the error took place. To ease debugging.
/// </summary>
/// <returns></returns>
public static string getLastErrorSnippet()
{
if( NGUIJson.lastErrorIndex == -1 )
{
return "";
}
else
{
int startIndex = NGUIJson.lastErrorIndex - 5;
int endIndex = NGUIJson.lastErrorIndex + 15;
if( startIndex < 0 )
startIndex = 0;
if( endIndex >= NGUIJson.lastDecode.Length )
endIndex = NGUIJson.lastDecode.Length - 1;
return NGUIJson.lastDecode.Substring( startIndex, endIndex - startIndex + 1 );
}
}
#region Parsing
protected static Hashtable parseObject( char[] json, ref int index )
{
Hashtable table = new Hashtable();
int token;
// {
nextToken( json, ref index );
bool done = false;
while( !done )
{
token = lookAhead( json, index );
if( token == NGUIJson.TOKEN_NONE )
{
return null;
}
else if( token == NGUIJson.TOKEN_COMMA )
{
nextToken( json, ref index );
}
else if( token == NGUIJson.TOKEN_CURLY_CLOSE )
{
nextToken( json, ref index );
return table;
}
else
{
// name
string name = parseString( json, ref index );
if( name == null )
{
return null;
}
// :
token = nextToken( json, ref index );
if( token != NGUIJson.TOKEN_COLON )
return null;
// value
bool success = true;
object value = parseValue( json, ref index, ref success );
if( !success )
return null;
table[name] = value;
}
}
return table;
}
protected static ArrayList parseArray( char[] json, ref int index )
{
ArrayList array = new ArrayList();
// [
nextToken( json, ref index );
bool done = false;
while( !done )
{
int token = lookAhead( json, index );
if( token == NGUIJson.TOKEN_NONE )
{
return null;
}
else if( token == NGUIJson.TOKEN_COMMA )
{
nextToken( json, ref index );
}
else if( token == NGUIJson.TOKEN_SQUARED_CLOSE )
{
nextToken( json, ref index );
break;
}
else
{
bool success = true;
object value = parseValue( json, ref index, ref success );
if( !success )
return null;
array.Add( value );
}
}
return array;
}
protected static object parseValue( char[] json, ref int index, ref bool success )
{
switch( lookAhead( json, index ) )
{
case NGUIJson.TOKEN_STRING:
return parseString( json, ref index );
case NGUIJson.TOKEN_NUMBER:
return parseNumber( json, ref index );
case NGUIJson.TOKEN_CURLY_OPEN:
return parseObject( json, ref index );
case NGUIJson.TOKEN_SQUARED_OPEN:
return parseArray( json, ref index );
case NGUIJson.TOKEN_TRUE:
nextToken( json, ref index );
return Boolean.Parse( "TRUE" );
case NGUIJson.TOKEN_FALSE:
nextToken( json, ref index );
return Boolean.Parse( "FALSE" );
case NGUIJson.TOKEN_NULL:
nextToken( json, ref index );
return null;
case NGUIJson.TOKEN_NONE:
break;
}
success = false;
return null;
}
protected static string parseString( char[] json, ref int index )
{
string s = "";
char c;
eatWhitespace( json, ref index );
// "
c = json[index++];
bool complete = false;
while( !complete )
{
if( index == json.Length )
break;
c = json[index++];
if( c == '"' )
{
complete = true;
break;
}
else if( c == '\\' )
{
if( index == json.Length )
break;
c = json[index++];
if( c == '"' )
{
s += '"';
}
else if( c == '\\' )
{
s += '\\';
}
else if( c == '/' )
{
s += '/';
}
else if( c == 'b' )
{
s += '\b';
}
else if( c == 'f' )
{
s += '\f';
}
else if( c == 'n' )
{
s += '\n';
}
else if( c == 'r' )
{
s += '\r';
}
else if( c == 't' )
{
s += '\t';
}
else if( c == 'u' )
{
int remainingLength = json.Length - index;
if( remainingLength >= 4 )
{
char[] unicodeCharArray = new char[4];
Array.Copy( json, index, unicodeCharArray, 0, 4 );
// Drop in the HTML markup for the unicode character
s += "&#x" + new string( unicodeCharArray ) + ";";
/*
uint codePoint = UInt32.Parse(new string(unicodeCharArray), NumberStyles.HexNumber);
// convert the integer codepoint to a unicode char and add to string
s += Char.ConvertFromUtf32((int)codePoint);
*/
// skip 4 chars
index += 4;
}
else
{
break;
}
}
}
else
{
s += c;
}
}
if( !complete )
return null;
return s;
}
protected static double parseNumber( char[] json, ref int index )
{
eatWhitespace( json, ref index );
int lastIndex = getLastIndexOfNumber( json, index );
int charLength = ( lastIndex - index ) + 1;
char[] numberCharArray = new char[charLength];
Array.Copy( json, index, numberCharArray, 0, charLength );
index = lastIndex + 1;
return Double.Parse( new string( numberCharArray ) ); // , CultureInfo.InvariantCulture);
}
protected static int getLastIndexOfNumber( char[] json, int index )
{
int lastIndex;
for( lastIndex = index; lastIndex < json.Length; lastIndex++ )
if( "0123456789+-.eE".IndexOf( json[lastIndex] ) == -1 )
{
break;
}
return lastIndex - 1;
}
protected static void eatWhitespace( char[] json, ref int index )
{
for( ; index < json.Length; index++ )
if( " \t\n\r".IndexOf( json[index] ) == -1 )
{
break;
}
}
protected static int lookAhead( char[] json, int index )
{
int saveIndex = index;
return nextToken( json, ref saveIndex );
}
protected static int nextToken( char[] json, ref int index )
{
eatWhitespace( json, ref index );
if( index == json.Length )
{
return NGUIJson.TOKEN_NONE;
}
char c = json[index];
index++;
switch( c )
{
case '{':
return NGUIJson.TOKEN_CURLY_OPEN;
case '}':
return NGUIJson.TOKEN_CURLY_CLOSE;
case '[':
return NGUIJson.TOKEN_SQUARED_OPEN;
case ']':
return NGUIJson.TOKEN_SQUARED_CLOSE;
case ',':
return NGUIJson.TOKEN_COMMA;
case '"':
return NGUIJson.TOKEN_STRING;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return NGUIJson.TOKEN_NUMBER;
case ':':
return NGUIJson.TOKEN_COLON;
}
index--;
int remainingLength = json.Length - index;
// false
if( remainingLength >= 5 )
{
if( json[index] == 'f' &&
json[index + 1] == 'a' &&
json[index + 2] == 'l' &&
json[index + 3] == 's' &&
json[index + 4] == 'e' )
{
index += 5;
return NGUIJson.TOKEN_FALSE;
}
}
// true
if( remainingLength >= 4 )
{
if( json[index] == 't' &&
json[index + 1] == 'r' &&
json[index + 2] == 'u' &&
json[index + 3] == 'e' )
{
index += 4;
return NGUIJson.TOKEN_TRUE;
}
}
// null
if( remainingLength >= 4 )
{
if( json[index] == 'n' &&
json[index + 1] == 'u' &&
json[index + 2] == 'l' &&
json[index + 3] == 'l' )
{
index += 4;
return NGUIJson.TOKEN_NULL;
}
}
return NGUIJson.TOKEN_NONE;
}
#endregion
#region Serialization
protected static bool serializeObjectOrArray( object objectOrArray, StringBuilder builder )
{
if( objectOrArray is Hashtable )
{
return serializeObject( (Hashtable)objectOrArray, builder );
}
else if( objectOrArray is ArrayList )
{
return serializeArray( (ArrayList)objectOrArray, builder );
}
else
{
return false;
}
}
protected static bool serializeObject( Hashtable anObject, StringBuilder builder )
{
builder.Append( "{" );
IDictionaryEnumerator e = anObject.GetEnumerator();
bool first = true;
while( e.MoveNext() )
{
string key = e.Key.ToString();
object value = e.Value;
if( !first )
{
builder.Append( ", " );
}
serializeString( key, builder );
builder.Append( ":" );
if( !serializeValue( value, builder ) )
{
return false;
}
first = false;
}
builder.Append( "}" );
return true;
}
protected static bool serializeDictionary( Dictionary<string,string> dict, StringBuilder builder )
{
builder.Append( "{" );
bool first = true;
foreach( var kv in dict )
{
if( !first )
builder.Append( ", " );
serializeString( kv.Key, builder );
builder.Append( ":" );
serializeString( kv.Value, builder );
first = false;
}
builder.Append( "}" );
return true;
}
protected static bool serializeArray( ArrayList anArray, StringBuilder builder )
{
builder.Append( "[" );
bool first = true;
for( int i = 0; i < anArray.Count; i++ )
{
object value = anArray[i];
if( !first )
{
builder.Append( ", " );
}
if( !serializeValue( value, builder ) )
{
return false;
}
first = false;
}
builder.Append( "]" );
return true;
}
protected static bool serializeValue( object value, StringBuilder builder )
{
// Type t = value.GetType();
// Debug.Log("type: " + t.ToString() + " isArray: " + t.IsArray);
if( value == null )
{
builder.Append( "null" );
}
else if( value.GetType().IsArray )
{
serializeArray( new ArrayList( (ICollection)value ), builder );
}
else if( value is string )
{
serializeString( (string)value, builder );
}
else if( value is Char )
{
serializeString( Convert.ToString( (char)value ), builder );
}
else if( value is Hashtable )
{
serializeObject( (Hashtable)value, builder );
}
else if( value is Dictionary<string,string> )
{
serializeDictionary( (Dictionary<string,string>)value, builder );
}
else if( value is ArrayList )
{
serializeArray( (ArrayList)value, builder );
}
else if( ( value is Boolean ) && ( (Boolean)value == true ) )
{
builder.Append( "true" );
}
else if( ( value is Boolean ) && ( (Boolean)value == false ) )
{
builder.Append( "false" );
}
else if( value.GetType().IsPrimitive )
{
serializeNumber( Convert.ToDouble( value ), builder );
}
else
{
return false;
}
return true;
}
protected static void serializeString( string aString, StringBuilder builder )
{
builder.Append( "\"" );
char[] charArray = aString.ToCharArray();
for( int i = 0; i < charArray.Length; i++ )
{
char c = charArray[i];
if( c == '"' )
{
builder.Append( "\\\"" );
}
else if( c == '\\' )
{
builder.Append( "\\\\" );
}
else if( c == '\b' )
{
builder.Append( "\\b" );
}
else if( c == '\f' )
{
builder.Append( "\\f" );
}
else if( c == '\n' )
{
builder.Append( "\\n" );
}
else if( c == '\r' )
{
builder.Append( "\\r" );
}
else if( c == '\t' )
{
builder.Append( "\\t" );
}
else
{
int codepoint = Convert.ToInt32( c );
if( ( codepoint >= 32 ) && ( codepoint <= 126 ) )
{
builder.Append( c );
}
else
{
builder.Append( "\\u" + Convert.ToString( codepoint, 16 ).PadLeft( 4, '0' ) );
}
}
}
builder.Append( "\"" );
}
protected static void serializeNumber( double number, StringBuilder builder )
{
builder.Append( Convert.ToString( number ) ); // , CultureInfo.InvariantCulture));
}
#endregion
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2017. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Leap.Unity {
public abstract class MultiTypedList {
[Serializable]
public struct Key {
public int id;
public int index;
}
}
/// <summary>
/// Represents an ordered collection of objects of type BaseType.
///
/// Unlike normal List objects, when MultiTypedList is serialized
/// it is able to support a certain amount of polymorphism. To
/// use MultiTypedList you must specify exactly which types could
/// possibly added. You must also pre-declare a non-generic version
/// of the chosen class, much in the same style as UnityEvent.
/// </summary>
public abstract class MultiTypedList<BaseType> : MultiTypedList, IList<BaseType> {
public abstract int Count { get; }
public bool IsReadOnly {
get {
return false;
}
}
public abstract BaseType this[int index] { get; set; }
public abstract void Add(BaseType obj);
public abstract void Clear();
public bool Contains(BaseType item) {
for (int i = 0; i < Count; i++) {
if (this[i].Equals(item)) {
return true;
}
}
return false;
}
public void CopyTo(BaseType[] array, int arrayIndex) {
for (int i = 0; i < Count; i++) {
array[i + arrayIndex] = this[i];
}
}
public Enumerator GetEnumerator() {
return new Enumerator(this);
}
public int IndexOf(BaseType item) {
for (int i = 0; i < Count; i++) {
if (this[i].Equals(item)) {
return i;
}
}
return -1;
}
public abstract void Insert(int index, BaseType item);
public bool Remove(BaseType item) {
int index = IndexOf(item);
if (index >= 0) {
RemoveAt(index);
return true;
} else {
return false;
}
}
public abstract void RemoveAt(int index);
public struct Enumerator : IEnumerator<BaseType> {
private MultiTypedList<BaseType> _list;
private int _index;
private BaseType _current;
public Enumerator(MultiTypedList<BaseType> list) {
_list = list;
_index = 0;
_current = default(BaseType);
}
public BaseType Current {
get {
return _current;
}
}
object IEnumerator.Current {
get {
throw new NotImplementedException();
}
}
public void Dispose() {
_list = null;
_current = default(BaseType);
}
public bool MoveNext() {
if (_index >= _list.Count) {
return false;
} else {
_current = _list[_index++];
return true;
}
}
public void Reset() {
_index = 0;
_current = default(BaseType);
}
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(this);
}
IEnumerator<BaseType> IEnumerable<BaseType>.GetEnumerator() {
return new Enumerator(this);
}
}
public class MultiTypedListUtil {
#if UNITY_EDITOR
public const string ID_NAME_TABLE = "abcdefghijklmnopqrstuvwxyz";
public static Dictionary<int, string> _nameCache = new Dictionary<int, string>();
private static string getName(int id) {
string name;
if (!_nameCache.TryGetValue(id, out name)) {
name = "_" + ID_NAME_TABLE[id];
_nameCache[id] = name;
}
return name;
}
public static SerializedProperty GetTableProperty(SerializedProperty list) {
return list.FindPropertyRelative("_table");
}
public static SerializedProperty GetArrayElementAtIndex(SerializedProperty list, int index) {
var tableProp = GetTableProperty(list);
var idIndexProp = tableProp.GetArrayElementAtIndex(index);
return GetReferenceProperty(list, idIndexProp);
}
public static SerializedProperty GetReferenceProperty(SerializedProperty list, SerializedProperty idIndexProp) {
var idProp = idIndexProp.FindPropertyRelative("id");
var indexProp = idIndexProp.FindPropertyRelative("index");
string listPropName = getName(idProp.intValue);
var listProp = list.FindPropertyRelative(listPropName);
return listProp.GetArrayElementAtIndex(indexProp.intValue);
}
#endif
}
[Serializable]
public class MultiTypedList<BaseType, A, B> : MultiTypedList<BaseType>
where A : BaseType
where B : BaseType {
[SerializeField]
private List<Key> _table = new List<Key>();
[SerializeField]
private List<A> _a = new List<A>();
[SerializeField]
private List<B> _b = new List<B>();
public override int Count {
get {
return _table.Count;
}
}
public override void Add(BaseType obj) {
_table.Add(addInternal(obj));
}
public override void Clear() {
_table.Clear();
_a.Clear();
_b.Clear();
}
public override void Insert(int index, BaseType obj) {
_table.Insert(index, addInternal(obj));
}
public override void RemoveAt(int index) {
var removedKey = _table[index];
_table.RemoveAt(index);
getList(removedKey.id).RemoveAt(removedKey.index);
for (int i = 0; i < _table.Count; i++) {
var key = _table[i];
if (key.id == removedKey.id && key.index > removedKey.index) {
key.index--;
_table[i] = key;
}
}
}
public override BaseType this[int index] {
get {
Key key = _table[index];
return (BaseType)getList(key.id)[key.index];
}
set {
Key oldKey = _table[index];
getList(oldKey.id).RemoveAt(oldKey.index);
Key newKey = addInternal(value);
_table[index] = newKey;
}
}
protected Key addHelper(IList list, BaseType instance, int id) {
Key key = new Key() {
id = id,
index = list.Count
};
list.Add(instance);
return key;
}
protected virtual Key addInternal(BaseType obj) {
if (obj is A) {
return addHelper(_a, obj, 0);
} else if (obj is B) {
return addHelper(_b, obj, 1);
} else {
throw new ArgumentException("This multi typed list does not support type " + obj.GetType().Name);
}
}
protected virtual IList getList(int id) {
if (id == 0) {
return _a;
} else if (id == 1) {
return _b;
} else {
throw new Exception("This multi typed list does not have a list with id " + id);
}
}
}
public class MultiTypedList<BaseType, A, B, C> : MultiTypedList<BaseType, A, B>
where A : BaseType
where B : BaseType
where C : BaseType {
[SerializeField]
private List<C> _c = new List<C>();
protected override Key addInternal(BaseType obj) {
return obj is C ? addHelper(_c, obj, 2) : base.addInternal(obj);
}
protected override IList getList(int id) {
return id == 2 ? _c : base.getList(id);
}
public override void Clear() {
base.Clear();
_c.Clear();
}
}
public class MultiTypedList<BaseType, A, B, C, D> : MultiTypedList<BaseType, A, B, C>
where A : BaseType
where B : BaseType
where C : BaseType
where D : BaseType {
[SerializeField]
private List<D> _d = new List<D>();
protected override Key addInternal(BaseType obj) {
return obj is D ? addHelper(_d, obj, 3) : base.addInternal(obj);
}
protected override IList getList(int id) {
return id == 3 ? _d : base.getList(id);
}
public override void Clear() {
base.Clear();
_d.Clear();
}
}
public class MultiTypedList<BaseType, A, B, C, D, E> : MultiTypedList<BaseType, A, B, C, D>
where A : BaseType
where B : BaseType
where C : BaseType
where D : BaseType
where E : BaseType {
[SerializeField]
private List<E> _e = new List<E>();
protected override Key addInternal(BaseType obj) {
return obj is E ? addHelper(_e, obj, 4) : base.addInternal(obj);
}
protected override IList getList(int id) {
return id == 4 ? _e : base.getList(id);
}
public override void Clear() {
base.Clear();
_e.Clear();
}
}
public class MultiTypedList<BaseType, A, B, C, D, E, F> : MultiTypedList<BaseType, A, B, C, D, E>
where A : BaseType
where B : BaseType
where C : BaseType
where D : BaseType
where E : BaseType
where F : BaseType {
[SerializeField]
private List<F> _f = new List<F>();
protected override Key addInternal(BaseType obj) {
return obj is F ? addHelper(_f, obj, 5) : base.addInternal(obj);
}
protected override IList getList(int id) {
return id == 5 ? _f : base.getList(id);
}
public override void Clear() {
base.Clear();
_f.Clear();
}
}
public class MultiTypedList<BaseType, A, B, C, D, E, F, G> : MultiTypedList<BaseType, A, B, C, D, E, F>
where A : BaseType
where B : BaseType
where C : BaseType
where D : BaseType
where E : BaseType
where F : BaseType
where G : BaseType {
[SerializeField]
private List<G> _g = new List<G>();
protected override Key addInternal(BaseType obj) {
return obj is G ? addHelper(_g, obj, 6) : base.addInternal(obj);
}
protected override IList getList(int id) {
return id == 6 ? _g : base.getList(id);
}
public override void Clear() {
base.Clear();
_g.Clear();
}
}
public class MultiTypedList<BaseType, A, B, C, D, E, F, G, H> : MultiTypedList<BaseType, A, B, C, D, E, F, G>
where A : BaseType
where B : BaseType
where C : BaseType
where D : BaseType
where E : BaseType
where F : BaseType
where G : BaseType
where H : BaseType {
[SerializeField]
private List<H> _h = new List<H>();
protected override Key addInternal(BaseType obj) {
return obj is H ? addHelper(_h, obj, 7) : base.addInternal(obj);
}
protected override IList getList(int id) {
return id == 7 ? _h : base.getList(id);
}
public override void Clear() {
base.Clear();
_h.Clear();
}
}
}
| |
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
/// <summary>
/// Convert.ToString(System.Int32,System.Int32)
/// </summary>
public class ConvertToString18
{
public static int Main()
{
ConvertToString18 testObj = new ConvertToString18();
TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Int32,System.Int32)");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
string c_TEST_DESC = "PosTest1: Verify value is 323 and radix is 2,8,10 or 16... ";
string c_TEST_ID = "P001";
Int32 int32Value = -123;
int radix;
String actualValue;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = "11111111111111111111111110000101";
radix = 2;
String resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 8;
actualValue = "37777777605";
errorDesc = "";
resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 10;
actualValue = "-123";
errorDesc = "";
resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 16;
actualValue = "ffffff85";
errorDesc = "";
resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string c_TEST_DESC = "PosTest2: Verify value is Int32.MaxValue and radix is 2,8,10 or 16... ";
string c_TEST_ID = "P002";
Int32 int32Value = Int32.MaxValue;
int radix;
String actualValue;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = "1111111111111111111111111111111";
radix = 2;
String resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 8;
actualValue = "17777777777";
errorDesc = "";
resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 10;
actualValue = "2147483647";
errorDesc = "";
resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 16;
actualValue = "7fffffff";
errorDesc = "";
resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string c_TEST_DESC = "PosTest3: Verify value is Int32.MinValue and radix is 2,8,10 or 16... ";
string c_TEST_ID = "P003";
Int32 int32Value = Int32.MinValue;
int radix;
String actualValue;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = "10000000000000000000000000000000";
radix = 2;
String resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 8;
actualValue = "20000000000";
errorDesc = "";
resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 10;
actualValue = "-2147483648";
errorDesc = "";
resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 16;
actualValue = "80000000";
errorDesc = "";
resValue = Convert.ToString(int32Value, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(int32Value, radix);
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("015", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTesting
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: the radix is 32...";
const string c_TEST_ID = "N001";
Int32 int32Value = TestLibrary.Generator.GetInt32(-55);
int radix = 32;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToString(int32Value, radix);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected ." + DataString(int32Value, radix));
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + DataString(int32Value, radix));
retVal = false;
}
return retVal;
}
#endregion
#region Help Methods
private string DataString(Int32 int32Value, int radix)
{
string str;
str = string.Format("\n[int32Value value]\n \"{0}\"", int32Value);
str += string.Format("\n[radix value ]\n {0}", radix);
return str;
}
#endregion
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.15.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.TrafficManager
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for EndpointsOperations.
/// </summary>
public static partial class EndpointsOperationsExtensions
{
/// <summary>
/// Update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the Update operation.
/// </param>
public static Endpoint Update(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).UpdateAsync(resourceGroupName, profileName, endpointType, endpointName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the Update operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> UpdateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint.
/// </param>
public static Endpoint Get(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).GetAsync(resourceGroupName, profileName, endpointType, endpointName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> GetAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be created or updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the CreateOrUpdate
/// operation.
/// </param>
public static Endpoint CreateOrUpdate(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters)
{
return Task.Factory.StartNew(s => ((IEndpointsOperations)s).CreateOrUpdateAsync(resourceGroupName, profileName, endpointType, endpointName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be created or updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the CreateOrUpdate
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Endpoint> CreateOrUpdateAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be deleted.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be deleted.
/// </param>
public static void Delete(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName)
{
Task.Factory.StartNew(s => ((IEndpointsOperations)s).DeleteAsync(resourceGroupName, profileName, endpointType, endpointName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a Traffic Manager endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be deleted.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IEndpointsOperations operations, string resourceGroupName, string profileName, string endpointType, string endpointName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointType, endpointName, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Principal;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SecurityUtils = System.ServiceModel.Security.SecurityUtils;
namespace System.ServiceModel.Channels
{
internal class HttpChannelFactory<TChannel>
: TransportChannelFactory<TChannel>,
IHttpTransportFactorySettings
{
private static CacheControlHeaderValue s_requestCacheHeader = new CacheControlHeaderValue { NoCache = true, MaxAge = new TimeSpan(0) };
protected readonly ClientWebSocketFactory _clientWebSocketFactory;
private HttpCookieContainerManager _httpCookieContainerManager;
// Double-checked locking pattern requires volatile for read/write synchronization
private volatile MruCache<Uri, Uri> _credentialCacheUriPrefixCache;
private volatile MruCache<string, string> _credentialHashCache;
private volatile MruCache<string, HttpClient> _httpClientCache;
private IWebProxy _proxy;
private WebProxyFactory _proxyFactory;
private SecurityCredentialsManager _channelCredentials;
private ISecurityCapabilities _securityCapabilities;
private Func<HttpClientHandler, HttpMessageHandler> _httpMessageHandlerFactory;
private Lazy<string> _webSocketSoapContentType;
private SHA512 _hashAlgorithm;
private bool _keepAliveEnabled;
internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
: base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
{
// validate setting interactions
if (bindingElement.TransferMode == TransferMode.Buffered)
{
if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
SR.MaxReceivedMessageSizeMustBeInIntegerRange));
}
if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.MaxBufferSizeMustMatchMaxReceivedMessageSize);
}
}
else
{
if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
}
}
if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
SR.HttpAuthDoesNotSupportRequestStreaming);
}
AllowCookies = bindingElement.AllowCookies;
if (AllowCookies)
{
_httpCookieContainerManager = new HttpCookieContainerManager();
}
if (!bindingElement.AuthenticationScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
bindingElement.AuthenticationScheme));
}
AuthenticationScheme = bindingElement.AuthenticationScheme;
MaxBufferSize = bindingElement.MaxBufferSize;
TransferMode = bindingElement.TransferMode;
_keepAliveEnabled = bindingElement.KeepAliveEnabled;
if (bindingElement.ProxyAddress != null)
{
if (bindingElement.UseDefaultWebProxy)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.UseDefaultWebProxyCantBeUsedWithExplicitProxyAddress));
}
if (bindingElement.ProxyAuthenticationScheme == AuthenticationSchemes.Anonymous)
{
_proxy = new WebProxy(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal);
}
else
{
_proxy = null;
_proxyFactory =
new WebProxyFactory(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal,
bindingElement.ProxyAuthenticationScheme);
}
}
else if (!bindingElement.UseDefaultWebProxy)
{
_proxy = new WebProxy();
}
_channelCredentials = context.BindingParameters.Find<SecurityCredentialsManager>();
_securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context);
_httpMessageHandlerFactory = context.BindingParameters.Find<Func<HttpClientHandler, HttpMessageHandler>>();
WebSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings);
_clientWebSocketFactory = ClientWebSocketFactory.GetFactory();
_webSocketSoapContentType = new Lazy<string>(() => MessageEncoderFactory.CreateSessionEncoder().ContentType, LazyThreadSafetyMode.ExecutionAndPublication);
}
public bool AllowCookies { get; }
public AuthenticationSchemes AuthenticationScheme { get; }
public virtual bool IsChannelBindingSupportEnabled
{
get
{
return false;
}
}
public SecurityTokenManager SecurityTokenManager { get; private set; }
public int MaxBufferSize { get; }
public TransferMode TransferMode { get; }
public override string Scheme
{
get
{
return UriEx.UriSchemeHttp;
}
}
public WebSocketTransportSettings WebSocketSettings { get; }
internal string WebSocketSoapContentType
{
get
{
return _webSocketSoapContentType.Value;
}
}
private HashAlgorithm HashAlgorithm
{
[SecurityCritical]
get
{
if (_hashAlgorithm == null)
{
_hashAlgorithm = SHA512.Create();
}
else
{
_hashAlgorithm.Initialize();
}
return _hashAlgorithm;
}
}
protected ClientWebSocketFactory ClientWebSocketFactory
{
get
{
return _clientWebSocketFactory;
}
}
private bool AuthenticationSchemeMayRequireResend()
{
return AuthenticationScheme != AuthenticationSchemes.Anonymous;
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)_securityCapabilities;
}
if (typeof(T) == typeof(IHttpCookieContainerManager))
{
return (T)(object)GetHttpCookieContainerManager();
}
return base.GetProperty<T>();
}
private HttpCookieContainerManager GetHttpCookieContainerManager()
{
return _httpCookieContainerManager;
}
private Uri GetCredentialCacheUriPrefix(Uri via)
{
Uri result;
if (_credentialCacheUriPrefixCache == null)
{
lock (ThisLock)
{
if (_credentialCacheUriPrefixCache == null)
{
_credentialCacheUriPrefixCache = new MruCache<Uri, Uri>(10);
}
}
}
lock (_credentialCacheUriPrefixCache)
{
if (!_credentialCacheUriPrefixCache.TryGetValue(via, out result))
{
result = new UriBuilder(via.Scheme, via.Host, via.Port).Uri;
_credentialCacheUriPrefixCache.Add(via, result);
}
}
return result;
}
internal async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via,
SecurityTokenProviderContainer tokenProvider, SecurityTokenProviderContainer proxyTokenProvider,
SecurityTokenContainer clientCertificateToken, TimeSpan timeout)
{
var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>();
NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(AuthenticationScheme,
tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, timeout);
if (_httpClientCache == null)
{
lock (ThisLock)
{
if (_httpClientCache == null)
{
_httpClientCache = new MruCache<string, HttpClient>(10);
}
}
}
HttpClient httpClient;
string connectionGroupName = GetConnectionGroupName(credential, authenticationLevelWrapper.Value,
impersonationLevelWrapper.Value,
clientCertificateToken);
X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity;
if (remoteCertificateIdentity != null)
{
connectionGroupName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", connectionGroupName,
remoteCertificateIdentity.Certificates[0].Thumbprint);
}
connectionGroupName = connectionGroupName ?? string.Empty;
bool foundHttpClient;
lock (_httpClientCache)
{
foundHttpClient = _httpClientCache.TryGetValue(connectionGroupName, out httpClient);
}
if (!foundHttpClient)
{
var clientHandler = GetHttpClientHandler(to, clientCertificateToken);
clientHandler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
if (clientHandler.SupportsProxy)
{
if (_proxy != null)
{
clientHandler.Proxy = _proxy;
clientHandler.UseProxy = true;
}
else if (_proxyFactory != null)
{
clientHandler.Proxy = await _proxyFactory.CreateWebProxyAsync(authenticationLevelWrapper.Value,
impersonationLevelWrapper.Value, proxyTokenProvider, timeout);
clientHandler.UseProxy = true;
}
}
clientHandler.UseCookies = AllowCookies;
if (AllowCookies)
{
clientHandler.CookieContainer = _httpCookieContainerManager.CookieContainer;
}
clientHandler.PreAuthenticate = true;
clientHandler.UseDefaultCredentials = false;
if (credential == CredentialCache.DefaultCredentials || credential == null)
{
clientHandler.UseDefaultCredentials = true;
}
else
{
if (Fx.IsUap)
{
clientHandler.Credentials = credential;
}
else
{
CredentialCache credentials = new CredentialCache();
credentials.Add(GetCredentialCacheUriPrefix(via),
AuthenticationSchemesHelper.ToString(AuthenticationScheme), credential);
clientHandler.Credentials = credentials;
}
}
HttpMessageHandler handler = clientHandler;
if (_httpMessageHandlerFactory != null)
{
handler = _httpMessageHandlerFactory(clientHandler);
}
httpClient = new HttpClient(handler);
if (!_keepAliveEnabled)
{
httpClient.DefaultRequestHeaders.ConnectionClose = true;
}
if (IsExpectContinueHeaderRequired && !Fx.IsUap)
{
httpClient.DefaultRequestHeaders.ExpectContinue = true;
}
// We provide our own CancellationToken for each request. Setting HttpClient.Timeout to -1
// prevents a call to CancellationToken.CancelAfter that HttpClient does internally which
// causes TimerQueue contention at high load.
httpClient.Timeout = Timeout.InfiniteTimeSpan;
lock (_httpClientCache)
{
HttpClient tempHttpClient;
if (_httpClientCache.TryGetValue(connectionGroupName, out tempHttpClient))
{
httpClient.Dispose();
httpClient = tempHttpClient;
}
else
{
_httpClientCache.Add(connectionGroupName, httpClient);
}
}
}
return httpClient;
}
internal virtual bool IsExpectContinueHeaderRequired => AuthenticationSchemeMayRequireResend();
internal virtual HttpClientHandler GetHttpClientHandler(EndpointAddress to, SecurityTokenContainer clientCertificateToken)
{
return new HttpClientHandler();
}
internal ICredentials GetCredentials()
{
ICredentials creds = null;
if (AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
creds = CredentialCache.DefaultCredentials;
ClientCredentials credentials = _channelCredentials as ClientCredentials;
if (credentials != null)
{
switch (AuthenticationScheme)
{
case AuthenticationSchemes.Basic:
if (credentials.UserName.UserName == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(ClientCredentials.UserName.UserName));
}
if (credentials.UserName.UserName == string.Empty)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.UserNameCannotBeEmpty);
}
creds = new NetworkCredential(credentials.UserName.UserName, credentials.UserName.Password);
break;
case AuthenticationSchemes.Digest:
if (credentials.HttpDigest.ClientCredential.UserName != string.Empty)
{
creds = credentials.HttpDigest.ClientCredential;
}
break;
case AuthenticationSchemes.Ntlm:
goto case AuthenticationSchemes.Negotiate;
case AuthenticationSchemes.Negotiate:
if (credentials.Windows.ClientCredential.UserName != string.Empty)
{
creds = credentials.Windows.ClientCredential;
}
break;
}
}
}
return creds;
}
internal Exception CreateToMustEqualViaException(Uri to, Uri via)
{
return new ArgumentException(SR.Format(SR.HttpToMustEqualVia, to, via));
}
public override int GetMaxBufferSize()
{
return MaxBufferSize;
}
private SecurityTokenProviderContainer CreateAndOpenTokenProvider(TimeSpan timeout, AuthenticationSchemes authenticationScheme,
EndpointAddress target, Uri via, ChannelParameterCollection channelParameters)
{
SecurityTokenProvider tokenProvider = null;
switch (authenticationScheme)
{
case AuthenticationSchemes.Anonymous:
break;
case AuthenticationSchemes.Basic:
tokenProvider = TransportSecurityHelpers.GetUserNameTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Negotiate:
case AuthenticationSchemes.Ntlm:
tokenProvider = TransportSecurityHelpers.GetSspiTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
case AuthenticationSchemes.Digest:
tokenProvider = TransportSecurityHelpers.GetDigestTokenProvider(SecurityTokenManager, target, via, Scheme, authenticationScheme, channelParameters);
break;
default:
// The setter for this property should prevent this.
throw Fx.AssertAndThrow("CreateAndOpenTokenProvider: Invalid authentication scheme");
}
SecurityTokenProviderContainer result;
if (tokenProvider != null)
{
result = new SecurityTokenProviderContainer(tokenProvider);
result.Open(timeout);
}
else
{
result = null;
}
return result;
}
protected virtual void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
{
if (string.Compare(via.Scheme, "ws", StringComparison.OrdinalIgnoreCase) != 0)
{
ValidateScheme(via);
}
if (MessageVersion.Addressing == AddressingVersion.None && remoteAddress.Uri != via)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateToMustEqualViaException(remoteAddress.Uri, via));
}
}
protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via)
{
if (typeof(TChannel) != typeof(IRequestChannel))
{
remoteAddress = remoteAddress != null && !WebSocketHelper.IsWebSocketUri(remoteAddress.Uri) ?
new EndpointAddress(WebSocketHelper.NormalizeHttpSchemeWithWsScheme(remoteAddress.Uri), remoteAddress) :
remoteAddress;
via = !WebSocketHelper.IsWebSocketUri(via) ? WebSocketHelper.NormalizeHttpSchemeWithWsScheme(via) : via;
}
return OnCreateChannelCore(remoteAddress, via);
}
protected virtual TChannel OnCreateChannelCore(EndpointAddress remoteAddress, Uri via)
{
ValidateCreateChannelParameters(remoteAddress, via);
ValidateWebSocketTransportUsage();
if (typeof(TChannel) == typeof(IRequestChannel))
{
return (TChannel)(object)new HttpClientRequestChannel((HttpChannelFactory<IRequestChannel>)(object)this, remoteAddress, via, ManualAddressing);
}
else
{
return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, _clientWebSocketFactory, remoteAddress, via);
}
}
protected void ValidateWebSocketTransportUsage()
{
Type channelType = typeof(TChannel);
if (channelType == typeof(IRequestChannel) && WebSocketSettings.TransportUsage == WebSocketTransportUsage.Always)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
if (channelType == typeof(IDuplexSessionChannel))
{
if (WebSocketSettings.TransportUsage == WebSocketTransportUsage.Never)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage,
typeof(TChannel),
WebSocketTransportSettings.TransportUsageMethodName,
typeof(WebSocketTransportSettings).Name,
WebSocketSettings.TransportUsage)));
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void InitializeSecurityTokenManager()
{
if (_channelCredentials == null)
{
_channelCredentials = ClientCredentials.CreateDefaultCredentials();
}
SecurityTokenManager = _channelCredentials.CreateSecurityTokenManager();
}
protected virtual bool IsSecurityTokenManagerRequired()
{
return AuthenticationScheme != AuthenticationSchemes.Anonymous;
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnOpenAsync(timeout).ToApm(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
protected override void OnOpen(TimeSpan timeout)
{
if (IsSecurityTokenManagerRequired())
{
InitializeSecurityTokenManager();
}
if (AllowCookies &&
!_httpCookieContainerManager.IsInitialized) // We don't want to overwrite the CookieContainer if someone has set it already.
{
_httpCookieContainerManager.CookieContainer = new CookieContainer();
}
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
OnOpen(timeout);
return TaskHelpers.CompletedTask();
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
return base.OnCloseAsync(timeout);
}
protected override void OnClosed()
{
base.OnClosed();
if (_httpClientCache != null && !_httpClientCache.IsDisposed)
{
lock (_httpClientCache)
{
_httpClientCache.Dispose();
_httpClientCache = null;
}
}
}
private string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential,
AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel)
{
return SecurityUtils.AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
protected virtual string OnGetConnectionGroupPrefix(SecurityTokenContainer clientCertificateToken)
{
return string.Empty;
}
internal static bool IsWindowsAuth(AuthenticationSchemes authScheme)
{
Contract.Assert(authScheme.IsSingleton(), "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value.");
return authScheme == AuthenticationSchemes.Negotiate ||
authScheme == AuthenticationSchemes.Ntlm;
}
private string GetConnectionGroupName(NetworkCredential credential, AuthenticationLevel authenticationLevel,
TokenImpersonationLevel impersonationLevel, SecurityTokenContainer clientCertificateToken)
{
if (_credentialHashCache == null)
{
lock (ThisLock)
{
if (_credentialHashCache == null)
{
_credentialHashCache = new MruCache<string, string>(5);
}
}
}
string inputString = TransferModeHelper.IsRequestStreamed(TransferMode) ? "streamed" : string.Empty;
if (IsWindowsAuth(AuthenticationScheme))
{
inputString = AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel);
}
inputString = string.Concat(OnGetConnectionGroupPrefix(clientCertificateToken), inputString);
string credentialHash = null;
// we have to lock around each call to TryGetValue since the MruCache modifies the
// contents of it's mruList in a single-threaded manner underneath TryGetValue
if (!string.IsNullOrEmpty(inputString))
{
lock (_credentialHashCache)
{
if (!_credentialHashCache.TryGetValue(inputString, out credentialHash))
{
byte[] inputBytes = new UTF8Encoding().GetBytes(inputString);
byte[] digestBytes = HashAlgorithm.ComputeHash(inputBytes);
credentialHash = Convert.ToBase64String(digestBytes);
_credentialHashCache.Add(inputString, credentialHash);
}
}
}
return credentialHash;
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
Uri httpRequestUri = via;
var requestMessage = new HttpRequestMessage(HttpMethod.Post, httpRequestUri);
if (TransferModeHelper.IsRequestStreamed(TransferMode))
{
requestMessage.Headers.TransferEncodingChunked = true;
}
requestMessage.Headers.CacheControl = s_requestCacheHeader;
return requestMessage;
}
private void ApplyManualAddressing(ref EndpointAddress to, ref Uri via, Message message)
{
if (ManualAddressing)
{
Uri toHeader = message.Headers.To;
if (toHeader == null)
{
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.ManualAddressingRequiresAddressedMessages), message);
}
to = new EndpointAddress(toHeader);
if (MessageVersion.Addressing == AddressingVersion.None)
{
via = toHeader;
}
}
// now apply query string property
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
if (!string.IsNullOrEmpty(requestProperty.QueryString))
{
UriBuilder uriBuilder = new UriBuilder(via);
if (requestProperty.QueryString.StartsWith("?", StringComparison.Ordinal))
{
uriBuilder.Query = requestProperty.QueryString.Substring(1);
}
else
{
uriBuilder.Query = requestProperty.QueryString;
}
via = uriBuilder.Uri;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void CreateAndOpenTokenProvidersCore(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
tokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), AuthenticationScheme, to, via, channelParameters);
if (_proxyFactory != null)
{
proxyTokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), _proxyFactory.AuthenticationScheme, to, via, channelParameters);
}
else
{
proxyTokenProvider = null;
}
}
internal void CreateAndOpenTokenProviders(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider)
{
if (!IsSecurityTokenManagerRequired())
{
tokenProvider = null;
proxyTokenProvider = null;
}
else
{
CreateAndOpenTokenProvidersCore(to, via, channelParameters, timeout, out tokenProvider, out proxyTokenProvider);
}
}
internal static bool MapIdentity(EndpointAddress target, AuthenticationSchemes authenticationScheme)
{
if (target.Identity == null)
{
return false;
}
return IsWindowsAuth(authenticationScheme);
}
private bool MapIdentity(EndpointAddress target)
{
return MapIdentity(target, AuthenticationScheme);
}
protected class HttpClientRequestChannel : RequestChannel
{
private SecurityTokenProviderContainer _tokenProvider;
private SecurityTokenProviderContainer _proxyTokenProvider;
public HttpClientRequestChannel(HttpChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing)
: base(factory, to, via, manualAddressing)
{
Factory = factory;
}
public HttpChannelFactory<IRequestChannel> Factory { get; }
protected ChannelParameterCollection ChannelParameters { get; private set; }
public override T GetProperty<T>()
{
if (typeof(T) == typeof(ChannelParameterCollection))
{
if (State == CommunicationState.Created)
{
lock (ThisLock)
{
if (ChannelParameters == null)
{
ChannelParameters = new ChannelParameterCollection();
}
}
}
return (T)(object)ChannelParameters;
}
return base.GetProperty<T>();
}
private void PrepareOpen()
{
Factory.MapIdentity(RemoteAddress);
}
private void CreateAndOpenTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (!ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(RemoteAddress, Via, ChannelParameters, timeoutHelper.RemainingTime(), out _tokenProvider, out _proxyTokenProvider);
}
}
private void CloseTokenProviders(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (_tokenProvider != null)
{
_tokenProvider.Close(timeoutHelper.RemainingTime());
}
}
private void AbortTokenProviders()
{
if (_tokenProvider != null)
{
_tokenProvider.Abort();
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginOpen(this, timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnOpen(TimeSpan timeout)
{
CommunicationObjectInternal.OnOpen(this, timeout);
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
PrepareOpen();
CreateAndOpenTokenProviders(timeout);
return TaskHelpers.CompletedTask();
}
private void PrepareClose(bool aborting)
{
}
protected override void OnAbort()
{
PrepareClose(true);
AbortTokenProviders();
base.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return CommunicationObjectInternal.OnBeginClose(this, timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CommunicationObjectInternal.OnEnd(result);
}
protected override void OnClose(TimeSpan timeout)
{
CommunicationObjectInternal.OnClose(this, timeout);
}
protected internal override async Task OnCloseAsync(TimeSpan timeout)
{
var timeoutHelper = new TimeoutHelper(timeout);
PrepareClose(false);
CloseTokenProviders(timeoutHelper.RemainingTime());
await WaitForPendingRequestsAsync(timeoutHelper.RemainingTime());
}
protected override IAsyncRequest CreateAsyncRequest(Message message)
{
return new HttpClientChannelAsyncRequest(this);
}
internal virtual Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, TimeoutHelper timeoutHelper)
{
return GetHttpClientAsync(to, via, null, timeoutHelper);
}
protected async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, TimeoutHelper timeoutHelper)
{
SecurityTokenProviderContainer requestTokenProvider;
SecurityTokenProviderContainer requestProxyTokenProvider;
if (ManualAddressing)
{
Factory.CreateAndOpenTokenProviders(to, via, ChannelParameters, timeoutHelper.RemainingTime(),
out requestTokenProvider, out requestProxyTokenProvider);
}
else
{
requestTokenProvider = _tokenProvider;
requestProxyTokenProvider = _proxyTokenProvider;
}
try
{
return await Factory.GetHttpClientAsync(to, via, requestTokenProvider, requestProxyTokenProvider, clientCertificateToken, timeoutHelper.RemainingTime());
}
finally
{
if (ManualAddressing)
{
if (requestTokenProvider != null)
{
requestTokenProvider.Abort();
}
}
}
}
internal HttpRequestMessage GetHttpRequestMessage(Uri via)
{
return Factory.GetHttpRequestMessage(via);
}
internal virtual void OnHttpRequestCompleted(HttpRequestMessage request)
{
// empty
}
internal class HttpClientChannelAsyncRequest : IAsyncRequest
{
private static readonly Action<object> s_cancelCts = state =>
{
try
{
((CancellationTokenSource)state).Cancel();
}
catch (ObjectDisposedException)
{
// ignore
}
};
private HttpClientRequestChannel _channel;
private HttpChannelFactory<IRequestChannel> _factory;
private EndpointAddress _to;
private Uri _via;
private HttpRequestMessage _httpRequestMessage;
private HttpResponseMessage _httpResponseMessage;
private HttpAbortReason _abortReason;
private TimeoutHelper _timeoutHelper;
private int _httpRequestCompleted;
private HttpClient _httpClient;
private readonly CancellationTokenSource _httpSendCts;
public HttpClientChannelAsyncRequest(HttpClientRequestChannel channel)
{
_channel = channel;
_to = channel.RemoteAddress;
_via = channel.Via;
_factory = channel.Factory;
_httpSendCts = new CancellationTokenSource();
}
public async Task SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
{
_timeoutHelper = timeoutHelper;
_factory.ApplyManualAddressing(ref _to, ref _via, message);
_httpClient = await _channel.GetHttpClientAsync(_to, _via, _timeoutHelper);
// The _httpRequestMessage field will be set to null by Cleanup() due to faulting
// or aborting, so use a local copy for exception handling within this method.
HttpRequestMessage httpRequestMessage = _channel.GetHttpRequestMessage(_via);
_httpRequestMessage = httpRequestMessage;
Message request = message;
try
{
if (_channel.State != CommunicationState.Opened)
{
// if we were aborted while getting our request or doing correlation,
// we need to abort the request and bail
Cleanup();
_channel.ThrowIfDisposedOrNotOpen();
}
bool suppressEntityBody = PrepareMessageHeaders(request);
if (!suppressEntityBody)
{
httpRequestMessage.Content = MessageContent.Create(_factory, request, _timeoutHelper);
}
if (Fx.IsUap)
{
try
{
// There is a possibility that a HEAD pre-auth request might fail when the actual request
// will succeed. For example, when the web service refuses HEAD requests. We don't want
// to fail the actual request because of some subtlety which causes the HEAD request.
await SendPreauthenticationHeadRequestIfNeeded();
}
catch { /* ignored */ }
}
bool success = false;
var timeoutToken = await _timeoutHelper.GetCancellationTokenAsync();
try
{
using (timeoutToken.Register(s_cancelCts, _httpSendCts))
{
_httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, _httpSendCts.Token);
}
// As we have the response message and no exceptions have been thrown, the request message has completed it's job.
// Calling Dispose() on the request message to free up resources in HttpContent, but keeping the object around
// as we can still query properties once dispose'd.
httpRequestMessage.Dispose();
success = true;
}
catch (HttpRequestException requestException)
{
HttpChannelUtilities.ProcessGetResponseWebException(requestException, httpRequestMessage,
_abortReason);
}
catch (OperationCanceledException)
{
if (timeoutToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
SR.HttpRequestTimedOut, httpRequestMessage.RequestUri, _timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutToken and needs to be handled differently.
throw;
}
}
finally
{
if (!success)
{
Abort(_channel);
}
}
}
finally
{
if (!ReferenceEquals(request, message))
{
request.Close();
}
}
}
private void Cleanup()
{
s_cancelCts(_httpSendCts);
if (_httpRequestMessage != null)
{
var httpRequestMessageSnapshot = _httpRequestMessage;
_httpRequestMessage = null;
TryCompleteHttpRequest(httpRequestMessageSnapshot);
httpRequestMessageSnapshot.Dispose();
}
}
public void Abort(RequestChannel channel)
{
Cleanup();
_abortReason = HttpAbortReason.Aborted;
}
public void Fault(RequestChannel channel)
{
Cleanup();
}
public async Task<Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper)
{
try
{
_timeoutHelper = timeoutHelper;
var responseHelper = new HttpResponseMessageHelper(_httpResponseMessage, _factory);
var replyMessage = await responseHelper.ParseIncomingResponse(timeoutHelper);
TryCompleteHttpRequest(_httpRequestMessage);
return replyMessage;
}
catch (OperationCanceledException)
{
var cancelToken = _timeoutHelper.GetCancellationToken();
if (cancelToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
SR.HttpResponseTimedOut, _httpRequestMessage.RequestUri, timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
throw;
}
}
}
private bool PrepareMessageHeaders(Message message)
{
string action = message.Headers.Action;
if (action != null)
{
action = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", UrlUtility.UrlPathEncode(action));
}
bool suppressEntityBody = message is NullMessage;
object property;
if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
{
HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
_httpRequestMessage.Method = new HttpMethod(requestProperty.Method);
// Query string was applied in HttpChannelFactory.ApplyManualAddressing
WebHeaderCollection requestHeaders = requestProperty.Headers;
suppressEntityBody = suppressEntityBody || requestProperty.SuppressEntityBody;
var headerKeys = requestHeaders.AllKeys;
for (int i = 0; i < headerKeys.Length; i++)
{
string name = headerKeys[i];
string value = requestHeaders[name];
if (string.Compare(name, "accept", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.Accept.TryParseAdd(value);
}
else if (string.Compare(name, "connection", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ConnectionClose = false;
}
else
{
_httpRequestMessage.Headers.Connection.TryParseAdd(value);
}
}
else if (string.Compare(name, "SOAPAction", StringComparison.OrdinalIgnoreCase) == 0)
{
if (action == null)
{
action = value;
}
else
{
if (!String.IsNullOrEmpty(value) && string.Compare(value, action, StringComparison.Ordinal) != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.HttpSoapActionMismatch, action, value)));
}
}
}
else if (string.Compare(name, "content-length", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we write to the content
}
else if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0)
{
// Handled by MessageContent
}
else if (string.Compare(name, "expect", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("100-CONTINUE", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.ExpectContinue = true;
}
else
{
_httpRequestMessage.Headers.Expect.TryParseAdd(value);
}
}
else if (string.Compare(name, "host", StringComparison.OrdinalIgnoreCase) == 0)
{
// this should be controlled through Via
}
else if (string.Compare(name, "referer", StringComparison.OrdinalIgnoreCase) == 0)
{
// referrer is proper spelling, but referer is the what is in the protocol.
_httpRequestMessage.Headers.Referrer = new Uri(value);
}
else if (string.Compare(name, "transfer-encoding", StringComparison.OrdinalIgnoreCase) == 0)
{
if (value.ToUpperInvariant().IndexOf("CHUNKED", StringComparison.OrdinalIgnoreCase) != -1)
{
_httpRequestMessage.Headers.TransferEncodingChunked = true;
}
else
{
_httpRequestMessage.Headers.TransferEncoding.TryParseAdd(value);
}
}
else if (string.Compare(name, "user-agent", StringComparison.OrdinalIgnoreCase) == 0)
{
_httpRequestMessage.Headers.Add(name, value);
}
else if (string.Compare(name, "if-modified-since", StringComparison.OrdinalIgnoreCase) == 0)
{
DateTimeOffset modifiedSinceDate;
if (DateTimeOffset.TryParse(value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeLocal, out modifiedSinceDate))
{
_httpRequestMessage.Headers.IfModifiedSince = modifiedSinceDate;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.HttpIfModifiedSinceParseError, value)));
}
}
else if (string.Compare(name, "date", StringComparison.OrdinalIgnoreCase) == 0)
{
// this will be taken care of by System.Net when we make the request
}
else if (string.Compare(name, "proxy-connection", StringComparison.OrdinalIgnoreCase) == 0)
{
throw ExceptionHelper.PlatformNotSupported("proxy-connection");
}
else if (string.Compare(name, "range", StringComparison.OrdinalIgnoreCase) == 0)
{
// specifying a range doesn't make sense in the context of WCF
}
else
{
try
{
_httpRequestMessage.Headers.Add(name, value);
}
catch (Exception addHeaderException)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(
SR.CopyHttpHeaderFailed,
name,
value,
HttpChannelUtilities.HttpRequestHeadersTypeName),
addHeaderException));
}
}
}
}
if (action != null)
{
if (message.Version.Envelope == EnvelopeVersion.Soap11)
{
_httpRequestMessage.Headers.TryAddWithoutValidation("SOAPAction", action);
}
else if (message.Version.Envelope == EnvelopeVersion.Soap12)
{
// Handled by MessageContent
}
else if (message.Version.Envelope != EnvelopeVersion.None)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.Format(SR.EnvelopeVersionUnknown,
message.Version.Envelope.ToString())));
}
}
// since we don't get the output stream in send when retVal == true,
// we need to disable chunking for some verbs (DELETE/PUT)
if (suppressEntityBody)
{
_httpRequestMessage.Headers.TransferEncodingChunked = false;
}
return suppressEntityBody;
}
public void OnReleaseRequest()
{
TryCompleteHttpRequest(_httpRequestMessage);
}
private void TryCompleteHttpRequest(HttpRequestMessage request)
{
if (request == null)
{
return;
}
if (Interlocked.CompareExchange(ref _httpRequestCompleted, 1, 0) == 0)
{
_channel.OnHttpRequestCompleted(request);
}
}
private async Task SendPreauthenticationHeadRequestIfNeeded()
{
if (!_factory.AuthenticationSchemeMayRequireResend())
{
return;
}
var requestUri = _httpRequestMessage.RequestUri;
// sends a HEAD request to the specificed requestUri for authentication purposes
Contract.Assert(requestUri != null);
HttpRequestMessage headHttpRequestMessage = new HttpRequestMessage()
{
Method = HttpMethod.Head,
RequestUri = requestUri
};
var cancelToken = await _timeoutHelper.GetCancellationTokenAsync();
await _httpClient.SendAsync(headHttpRequestMessage, cancelToken);
}
}
}
private class WebProxyFactory
{
private Uri _address;
private bool _bypassOnLocal;
public WebProxyFactory(Uri address, bool bypassOnLocal, AuthenticationSchemes authenticationScheme)
{
_address = address;
_bypassOnLocal = bypassOnLocal;
if (!authenticationScheme.IsSingleton())
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(nameof(authenticationScheme), SR.Format(SR.HttpRequiresSingleAuthScheme,
authenticationScheme));
}
AuthenticationScheme = authenticationScheme;
}
internal AuthenticationSchemes AuthenticationScheme { get; }
public async Task<IWebProxy> CreateWebProxyAsync(AuthenticationLevel requestAuthenticationLevel, TokenImpersonationLevel requestImpersonationLevel, SecurityTokenProviderContainer tokenProvider, TimeSpan timeout)
{
WebProxy result = new WebProxy(_address, _bypassOnLocal);
if (AuthenticationScheme != AuthenticationSchemes.Anonymous)
{
var impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>();
var authenticationLevelWrapper = new OutWrapper<AuthenticationLevel>();
NetworkCredential credential = await HttpChannelUtilities.GetCredentialAsync(AuthenticationScheme,
tokenProvider, impersonationLevelWrapper, authenticationLevelWrapper, timeout);
// The impersonation level for target auth is also used for proxy auth (by System.Net). Therefore,
// fail if the level stipulated for proxy auth is more restrictive than that for target auth.
if (!TokenImpersonationLevelHelper.IsGreaterOrEqual(impersonationLevelWrapper.Value, requestImpersonationLevel))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.ProxyImpersonationLevelMismatch, impersonationLevelWrapper.Value, requestImpersonationLevel)));
}
// The authentication level for target auth is also used for proxy auth (by System.Net).
// Therefore, fail if proxy auth requires mutual authentication but target auth does not.
if ((authenticationLevelWrapper.Value == AuthenticationLevel.MutualAuthRequired) &&
(requestAuthenticationLevel != AuthenticationLevel.MutualAuthRequired))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(
SR.ProxyAuthenticationLevelMismatch, authenticationLevelWrapper.Value, requestAuthenticationLevel)));
}
CredentialCache credentials = new CredentialCache();
credentials.Add(_address, AuthenticationSchemesHelper.ToString(AuthenticationScheme),
credential);
result.Credentials = credentials;
}
return result;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ArtifactSourceOperations operations.
/// </summary>
internal partial class ArtifactSourceOperations : IServiceOperations<DevTestLabsClient>, IArtifactSourceOperations
{
/// <summary>
/// Initializes a new instance of the ArtifactSourceOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ArtifactSourceOperations(DevTestLabsClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DevTestLabsClient
/// </summary>
public DevTestLabsClient Client { get; private set; }
/// <summary>
/// List artifact sources in a given lab.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ArtifactSource>>> ListWithHttpMessagesAsync(string resourceGroupName, string labName, ODataQuery<ArtifactSource> odataQuery = default(ODataQuery<ArtifactSource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (this.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("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<ArtifactSource>>();
_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 = SafeJsonConvert.DeserializeObject<Page<ArtifactSource>>(_responseContent, this.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 artifact source.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArtifactSource>> GetResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.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("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetResource", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<ArtifactSource>();
_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 = SafeJsonConvert.DeserializeObject<ArtifactSource>(_responseContent, this.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>
/// Create or replace an existing artifact source.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='artifactSource'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArtifactSource>> CreateOrUpdateResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, ArtifactSource artifactSource, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (artifactSource == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "artifactSource");
}
if (this.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("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("artifactSource", artifactSource);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdateResource", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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;
if(artifactSource != null)
{
_requestContent = SafeJsonConvert.SerializeObject(artifactSource, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<ArtifactSource>();
_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 = SafeJsonConvert.DeserializeObject<ArtifactSource>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ArtifactSource>(_responseContent, this.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>
/// Delete artifact source.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.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("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DeleteResource", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Modify properties of artifact sources.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the artifact source.
/// </param>
/// <param name='artifactSource'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ArtifactSource>> PatchResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, ArtifactSource artifactSource, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (artifactSource == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "artifactSource");
}
if (this.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("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("artifactSource", artifactSource);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PatchResource", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/artifactsources/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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;
if(artifactSource != null)
{
_requestContent = SafeJsonConvert.SerializeObject(artifactSource, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<ArtifactSource>();
_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 = SafeJsonConvert.DeserializeObject<ArtifactSource>(_responseContent, this.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>
/// List artifact sources in a given lab.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ArtifactSource>>> 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 += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<ArtifactSource>>();
_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 = SafeJsonConvert.DeserializeObject<Page<ArtifactSource>>(_responseContent, this.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 (C) Microsoft. All rights reserved.
//
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Microsoft.Win32;
using System;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Collections.Generic;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Represent a control panel item
/// </summary>
public sealed class ControlPanelItem
{
/// <summary>
/// Control panel applet name
/// </summary>
public string Name { get; }
/// <summary>
/// Control panel applet canonical name
/// </summary>
public string CanonicalName { get; }
/// <summary>
/// Control panel applet category
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Category { get; }
/// <summary>
/// Control panel applet description
/// </summary>
public string Description { get; }
/// <summary>
/// Control panel applet path
/// </summary>
internal string Path { get; }
/// <summary>
/// Internal constructor for ControlPanelItem
/// </summary>
/// <param name="name"></param>
/// <param name="canonicalName"></param>
/// <param name="category"></param>
/// <param name="description"></param>
/// <param name="path"></param>
internal ControlPanelItem(string name, string canonicalName, string[] category, string description, string path)
{
Name = name;
Path = path;
CanonicalName = canonicalName;
Category = category;
Description = description;
}
/// <summary>
/// ToString method
/// </summary>
/// <returns></returns>
public override string ToString()
{
return this.Name;
}
}
/// <summary>
/// This class implements the base for ControlPanelItem commands
/// </summary>
public abstract class ControlPanelItemBaseCommand : PSCmdlet
{
/// <summary>
/// Locale specific verb action Open string exposed by the control panel item.
/// </summary>
private static string s_verbActionOpenName = null;
/// <summary>
/// Canonical name of the control panel item used as a refernece to fetch the verb
/// action Open string. This control panel item exists on all SKU's.
/// </summary>
private const string RegionCanonicalName = "Microsoft.RegionAndLanguage";
private const string ControlPanelShellFolder = "shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}";
private static readonly string[] s_controlPanelItemFilterList = new string[] { "Folder Options", "Taskbar and Start Menu" };
private const string TestHeadlessServerScript = @"
$result = $false
$serverManagerModule = Get-Module -ListAvailable | ? {$_.Name -eq 'ServerManager'}
if ($serverManagerModule -ne $null)
{
Import-Module ServerManager
$Gui = (Get-WindowsFeature Server-Gui-Shell).Installed
if ($Gui -eq $false)
{
$result = $true
}
}
$result
";
internal readonly Dictionary<string, string> CategoryMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
internal string[] CategoryNames = { "*" };
internal string[] RegularNames = { "*" };
internal string[] CanonicalNames = { "*" };
internal ControlPanelItem[] ControlPanelItems = new ControlPanelItem[0];
/// <summary>
/// Get all executable control panel items
/// </summary>
internal List<ShellFolderItem> AllControlPanelItems
{
get
{
if (_allControlPanelItems == null)
{
_allControlPanelItems = new List<ShellFolderItem>();
string allItemFolderPath = ControlPanelShellFolder + "\\0";
IShellDispatch4 shell2 = (IShellDispatch4)new Shell();
Folder2 allItemFolder = (Folder2)shell2.NameSpace(allItemFolderPath);
FolderItems3 allItems = (FolderItems3)allItemFolder.Items();
bool applyControlPanelItemFilterList = IsServerCoreOrHeadLessServer();
foreach (ShellFolderItem item in allItems)
{
if (applyControlPanelItemFilterList)
{
bool match = false;
foreach (string name in s_controlPanelItemFilterList)
{
if (name.Equals(item.Name, StringComparison.OrdinalIgnoreCase))
{
match = true;
break;
}
}
if (match)
continue;
}
if (ContainVerbOpen(item))
_allControlPanelItems.Add(item);
}
}
return _allControlPanelItems;
}
}
private List<ShellFolderItem> _allControlPanelItems;
#region Cmdlet Overrides
/// <summary>
/// Does the preprocessing for ControlPanelItem cmdlets
/// </summary>
protected override void BeginProcessing()
{
System.OperatingSystem osInfo = System.Environment.OSVersion;
PlatformID platform = osInfo.Platform;
Version version = osInfo.Version;
if (platform.Equals(PlatformID.Win32NT) &&
((version.Major < 6) ||
((version.Major == 6) && (version.Minor < 2))
))
{
// Below Win8, this cmdlet is not supported because of Win8:794135
// throw terminating
string message = string.Format(CultureInfo.InvariantCulture,
ControlPanelResources.ControlPanelItemCmdletNotSupported,
this.CommandInfo.Name);
throw new PSNotSupportedException(message);
}
}
#endregion
/// <summary>
/// Test if an item can be invoked
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
private bool ContainVerbOpen(ShellFolderItem item)
{
bool result = false;
FolderItemVerbs verbs = item.Verbs();
foreach (FolderItemVerb verb in verbs)
{
if (!String.IsNullOrEmpty(verb.Name) &&
(verb.Name.Equals(ControlPanelResources.VerbActionOpen, StringComparison.OrdinalIgnoreCase) ||
CompareVerbActionOpen(verb.Name)))
{
result = true;
break;
}
}
return result;
}
/// <summary>
/// CompareVerbActionOpen is a helper function used to perform locale specific
/// comparision of the verb action Open exposed by various control panel items.
/// </summary>
/// <param name="verbActionName">Locale spcific verb action exposed by the control panel item.</param>
/// <returns>True if the control panel item supports verb action open or else returns false.</returns>
private static bool CompareVerbActionOpen(string verbActionName)
{
if (s_verbActionOpenName == null)
{
const string allItemFolderPath = ControlPanelShellFolder + "\\0";
IShellDispatch4 shell2 = (IShellDispatch4)new Shell();
Folder2 allItemFolder = (Folder2)shell2.NameSpace(allItemFolderPath);
FolderItems3 allItems = (FolderItems3)allItemFolder.Items();
foreach (ShellFolderItem item in allItems)
{
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
canonicalName = !String.IsNullOrEmpty(canonicalName)
? canonicalName.Substring(0, canonicalName.IndexOf("\0", StringComparison.OrdinalIgnoreCase))
: null;
if (canonicalName != null && canonicalName.Equals(RegionCanonicalName, StringComparison.OrdinalIgnoreCase))
{
// The 'Region' control panel item always has '&Open' (english or other locale) as the first verb name
s_verbActionOpenName = item.Verbs().Item(0).Name;
break;
}
}
Dbg.Assert(s_verbActionOpenName != null, "The 'Region' control panel item is available on all SKUs and it always "
+ "has '&Open' as the first verb item, so VerbActionOpenName should never be null at this point");
}
return s_verbActionOpenName.Equals(verbActionName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// IsServerCoreORHeadLessServer is a helper function that checks if the current SKU is a
/// Server Core machine or if the Server-GUI-Shell feature is removed on the machine.
/// </summary>
/// <returns>True if the current SKU is a Server Core machine or if the Server-GUI-Shell
/// feature is removed on the machine or else returns false.</returns>
private bool IsServerCoreOrHeadLessServer()
{
bool result = false;
using (RegistryKey installation = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"))
{
Dbg.Assert(installation != null, "the CurrentVersion subkey should exist");
string installationType = (string)installation.GetValue("InstallationType", "");
if (installationType.Equals("Server Core"))
{
result = true;
}
else if (installationType.Equals("Server"))
{
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
{
ps.AddScript(TestHeadlessServerScript);
Collection<PSObject> psObjectCollection = ps.Invoke(new object[0]);
Dbg.Assert(psObjectCollection != null && psObjectCollection.Count == 1, "invoke should never return null, there should be only one return item");
if (LanguagePrimitives.IsTrue(PSObject.Base(psObjectCollection[0])))
{
result = true;
}
}
}
}
return result;
}
/// <summary>
/// Get the category number and name map
/// </summary>
internal void GetCategoryMap()
{
if (CategoryMap.Count != 0)
{
return;
}
IShellDispatch4 shell2 = (IShellDispatch4)new Shell();
Folder2 categoryFolder = (Folder2)shell2.NameSpace(ControlPanelShellFolder);
FolderItems3 catItems = (FolderItems3)categoryFolder.Items();
foreach (ShellFolderItem category in catItems)
{
string path = category.Path;
string catNum = path.Substring(path.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase) + 1);
CategoryMap.Add(catNum, category.Name);
}
}
/// <summary>
/// Get control panel item by the category
/// </summary>
/// <param name="controlPanelItems"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemByCategory(List<ShellFolderItem> controlPanelItems)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string pattern in CategoryNames)
{
bool found = false;
WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
foreach (ShellFolderItem item in controlPanelItems)
{
string path = item.Path;
int[] categories = (int[])item.ExtendedProperty("System.ControlPanel.Category");
foreach (int cat in categories)
{
string catStr = (string)LanguagePrimitives.ConvertTo(cat, typeof(string), CultureInfo.InvariantCulture);
Dbg.Assert(CategoryMap.ContainsKey(catStr), "the category should be contained in _categoryMap");
string catName = CategoryMap[catStr];
if (!wildcard.IsMatch(catName))
continue;
if (itemSet.Contains(path))
{
found = true;
break;
}
found = true;
itemSet.Add(path);
list.Add(item);
break;
}
}
if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern))
{
string errMsg = StringUtil.Format(ControlPanelResources.NoControlPanelItemFoundForGivenCategory, pattern);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenCategory",
ErrorCategory.InvalidArgument, pattern);
WriteError(error);
}
}
return list;
}
/// <summary>
/// Get control panel item by the regular name
/// </summary>
/// <param name="controlPanelItems"></param>
/// <param name="withCategoryFilter"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemByName(List<ShellFolderItem> controlPanelItems, bool withCategoryFilter)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string pattern in RegularNames)
{
bool found = false;
WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
foreach (ShellFolderItem item in controlPanelItems)
{
string name = item.Name;
string path = item.Path;
if (!wildcard.IsMatch(name))
continue;
if (itemSet.Contains(path))
{
found = true;
continue;
}
found = true;
itemSet.Add(path);
list.Add(item);
}
if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern))
{
string formatString = withCategoryFilter
? ControlPanelResources.NoControlPanelItemFoundForGivenNameWithCategory
: ControlPanelResources.NoControlPanelItemFoundForGivenName;
string errMsg = StringUtil.Format(formatString, pattern);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenName",
ErrorCategory.InvalidArgument, pattern);
WriteError(error);
}
}
return list;
}
/// <summary>
/// Get control panel item by the canonical name
/// </summary>
/// <param name="controlPanelItems"></param>
/// <param name="withCategoryFilter"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemByCanonicalName(List<ShellFolderItem> controlPanelItems, bool withCategoryFilter)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (CanonicalNames == null)
{
bool found = false;
foreach (ShellFolderItem item in controlPanelItems)
{
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
if (canonicalName == null)
{
found = true;
list.Add(item);
}
}
if (!found)
{
string errMsg = withCategoryFilter
? ControlPanelResources.NoControlPanelItemFoundWithNullCanonicalNameWithCategory
: ControlPanelResources.NoControlPanelItemFoundWithNullCanonicalName;
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "",
ErrorCategory.InvalidArgument, CanonicalNames);
WriteError(error);
}
return list;
}
foreach (string pattern in CanonicalNames)
{
bool found = false;
WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
foreach (ShellFolderItem item in controlPanelItems)
{
string path = item.Path;
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
canonicalName = canonicalName != null
? canonicalName.Substring(0, canonicalName.IndexOf("\0", StringComparison.OrdinalIgnoreCase))
: null;
if (canonicalName == null)
{
if (pattern.Equals("*", StringComparison.OrdinalIgnoreCase))
{
found = true;
if (!itemSet.Contains(path))
{
itemSet.Add(path);
list.Add(item);
}
}
}
else
{
if (!wildcard.IsMatch(canonicalName))
continue;
if (itemSet.Contains(path))
{
found = true;
continue;
}
found = true;
itemSet.Add(path);
list.Add(item);
}
}
if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern))
{
string formatString = withCategoryFilter
? ControlPanelResources.NoControlPanelItemFoundForGivenCanonicalNameWithCategory
: ControlPanelResources.NoControlPanelItemFoundForGivenCanonicalName;
string errMsg = StringUtil.Format(formatString, pattern);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenCanonicalName",
ErrorCategory.InvalidArgument, pattern);
WriteError(error);
}
}
return list;
}
/// <summary>
/// Get control panel item by the ControlPanelItem instances
/// </summary>
/// <param name="controlPanelItems"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemsByInstance(List<ShellFolderItem> controlPanelItems)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (ControlPanelItem controlPanelItem in ControlPanelItems)
{
bool found = false;
foreach (ShellFolderItem item in controlPanelItems)
{
string path = item.Path;
if (!controlPanelItem.Path.Equals(path, StringComparison.OrdinalIgnoreCase))
continue;
if (itemSet.Contains(path))
{
found = true;
break;
}
found = true;
itemSet.Add(path);
list.Add(item);
break;
}
if (!found)
{
string errMsg = StringUtil.Format(ControlPanelResources.NoControlPanelItemFoundForGivenInstance,
controlPanelItem.GetType().Name);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenInstance",
ErrorCategory.InvalidArgument, controlPanelItem);
WriteError(error);
}
}
return list;
}
}
/// <summary>
/// Get all control panel items that is available in the "All Control Panel Items" category
/// </summary>
[Cmdlet(VerbsCommon.Get, "ControlPanelItem", DefaultParameterSetName = RegularNameParameterSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=219982")]
[OutputType(typeof(ControlPanelItem))]
public sealed class GetControlPanelItemCommand : ControlPanelItemBaseCommand
{
private const string RegularNameParameterSet = "RegularName";
private const string CanonicalNameParameterSet = "CanonicalName";
#region "Parameters"
/// <summary>
/// Control panel item names
/// </summary>
[Parameter(Position = 0, ParameterSetName = RegularNameParameterSet, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Name
{
get { return RegularNames; }
set
{
RegularNames = value;
_nameSpecified = true;
}
}
private bool _nameSpecified = false;
/// <summary>
/// Canonical names of control panel items
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = CanonicalNameParameterSet)]
[AllowNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CanonicalName
{
get { return CanonicalNames; }
set
{
CanonicalNames = value;
_canonicalNameSpecified = true;
}
}
private bool _canonicalNameSpecified = false;
/// <summary>
/// Category of control panel items
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Category
{
get { return CategoryNames; }
set
{
CategoryNames = value;
_categorySpecified = true;
}
}
private bool _categorySpecified = false;
#endregion "Parameters"
/// <summary>
///
/// </summary>
protected override void ProcessRecord()
{
GetCategoryMap();
List<ShellFolderItem> items = GetControlPanelItemByCategory(AllControlPanelItems);
if (_nameSpecified)
{
items = GetControlPanelItemByName(items, _categorySpecified);
}
else if (_canonicalNameSpecified)
{
items = GetControlPanelItemByCanonicalName(items, _categorySpecified);
}
List<ControlPanelItem> results = new List<ControlPanelItem>();
foreach (ShellFolderItem item in items)
{
string name = item.Name;
string path = item.Path;
string description = (string)item.ExtendedProperty("InfoTip");
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
canonicalName = canonicalName != null
? canonicalName.Substring(0, canonicalName.IndexOf("\0", StringComparison.OrdinalIgnoreCase))
: null;
int[] categories = (int[])item.ExtendedProperty("System.ControlPanel.Category");
string[] cateStrings = new string[categories.Length];
for (int i = 0; i < categories.Length; i++)
{
string catStr = (string)LanguagePrimitives.ConvertTo(categories[i], typeof(string), CultureInfo.InvariantCulture);
Dbg.Assert(CategoryMap.ContainsKey(catStr), "the category should be contained in CategoryMap");
cateStrings[i] = CategoryMap[catStr];
}
ControlPanelItem controlPanelItem = new ControlPanelItem(name, canonicalName, cateStrings, description, path);
results.Add(controlPanelItem);
}
// Sort the reuslts by Canonical Name
results.Sort(CompareControlPanelItems);
foreach (ControlPanelItem controlPanelItem in results)
{
WriteObject(controlPanelItem);
}
}
#region "Private Methods"
private static int CompareControlPanelItems(ControlPanelItem x, ControlPanelItem y)
{
// In the case that at least one of them is null
if (x.CanonicalName == null && y.CanonicalName == null)
return 0;
if (x.CanonicalName == null)
return 1;
if (y.CanonicalName == null)
return -1;
// In the case that both are not null
return string.Compare(x.CanonicalName, y.CanonicalName, StringComparison.OrdinalIgnoreCase);
}
#endregion "Private Methods"
}
/// <summary>
/// Show the specified control panel applet
/// </summary>
[Cmdlet(VerbsCommon.Show, "ControlPanelItem", DefaultParameterSetName = RegularNameParameterSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=219983")]
public sealed class ShowControlPanelItemCommand : ControlPanelItemBaseCommand
{
private const string RegularNameParameterSet = "RegularName";
private const string CanonicalNameParameterSet = "CanonicalName";
private const string ControlPanelItemParameterSet = "ControlPanelItem";
#region "Parameters"
/// <summary>
/// Control panel item names
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = RegularNameParameterSet, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Name
{
get { return RegularNames; }
set { RegularNames = value; }
}
/// <summary>
/// Canonical names of control panel items
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = CanonicalNameParameterSet)]
[AllowNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CanonicalName
{
get { return CanonicalNames; }
set { CanonicalNames = value; }
}
/// <summary>
/// Control panel items returned by Get-ControlPanelItem
/// </summary>
[Parameter(Position = 0, ParameterSetName = ControlPanelItemParameterSet, ValueFromPipeline = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public ControlPanelItem[] InputObject
{
get { return ControlPanelItems; }
set { ControlPanelItems = value; }
}
#endregion "Parameters"
/// <summary>
///
/// </summary>
protected override void ProcessRecord()
{
List<ShellFolderItem> items;
if (ParameterSetName == RegularNameParameterSet)
{
items = GetControlPanelItemByName(AllControlPanelItems, false);
}
else if (ParameterSetName == CanonicalNameParameterSet)
{
items = GetControlPanelItemByCanonicalName(AllControlPanelItems, false);
}
else
{
items = GetControlPanelItemsByInstance(AllControlPanelItems);
}
foreach (ShellFolderItem item in items)
{
item.InvokeVerb();
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using OrchardCore.Admin;
using OrchardCore.AdminMenu.Services;
using OrchardCore.AdminMenu.ViewModels;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Navigation;
namespace OrchardCore.AdminMenu.Controllers
{
[Admin]
public class NodeController : Controller
{
private readonly IAuthorizationService _authorizationService;
private readonly IDisplayManager<MenuItem> _displayManager;
private readonly IEnumerable<IAdminNodeProviderFactory> _factories;
private readonly IAdminMenuService _adminMenuService;
private readonly INotifier _notifier;
private readonly IHtmlLocalizer H;
private readonly IUpdateModelAccessor _updateModelAccessor;
public NodeController(
IAuthorizationService authorizationService,
IDisplayManager<MenuItem> displayManager,
IEnumerable<IAdminNodeProviderFactory> factories,
IAdminMenuService adminMenuService,
IHtmlLocalizer<NodeController> htmlLocalizer,
INotifier notifier,
IUpdateModelAccessor updateModelAccessor)
{
_displayManager = displayManager;
_factories = factories;
_adminMenuService = adminMenuService;
_authorizationService = authorizationService;
_notifier = notifier;
_updateModelAccessor = updateModelAccessor;
H = htmlLocalizer;
}
public async Task<IActionResult> List(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.GetAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id);
if (adminMenu == null)
{
return NotFound();
}
return View(await BuildDisplayViewModel(adminMenu));
}
private async Task<AdminNodeListViewModel> BuildDisplayViewModel(Models.AdminMenu tree)
{
var thumbnails = new Dictionary<string, dynamic>();
foreach (var factory in _factories)
{
var treeNode = factory.Create();
dynamic thumbnail = await _displayManager.BuildDisplayAsync(treeNode, _updateModelAccessor.ModelUpdater, "TreeThumbnail");
thumbnail.TreeNode = treeNode;
thumbnails.Add(factory.Name, thumbnail);
}
var model = new AdminNodeListViewModel
{
AdminMenu = tree,
Thumbnails = thumbnails,
};
return model;
}
public async Task<IActionResult> Create(string id, string type)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.GetAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id);
if (adminMenu == null)
{
return NotFound();
}
var treeNode = _factories.FirstOrDefault(x => x.Name == type)?.Create();
if (treeNode == null)
{
return NotFound();
}
var model = new AdminNodeEditViewModel
{
AdminMenuId = id,
AdminNode = treeNode,
AdminNodeId = treeNode.UniqueId,
AdminNodeType = type,
Editor = await _displayManager.BuildEditorAsync(treeNode, updater: _updateModelAccessor.ModelUpdater, isNew: true)
};
return View(model);
}
[HttpPost]
public async Task<IActionResult> Create(AdminNodeEditViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, model.AdminMenuId);
if (adminMenu == null)
{
return NotFound();
}
var treeNode = _factories.FirstOrDefault(x => x.Name == model.AdminNodeType)?.Create();
if (treeNode == null)
{
return NotFound();
}
dynamic editor = await _displayManager.UpdateEditorAsync(treeNode, updater: _updateModelAccessor.ModelUpdater, isNew: true);
editor.TreeNode = treeNode;
if (ModelState.IsValid)
{
treeNode.UniqueId = model.AdminNodeId;
adminMenu.MenuItems.Add(treeNode);
await _adminMenuService.SaveAsync(adminMenu);
_notifier.Success(H["Admin node added successfully"]);
return RedirectToAction("List", new { id = model.AdminMenuId });
}
model.Editor = editor;
// If we got this far, something failed, redisplay form
return View(model);
}
public async Task<IActionResult> Edit(string id, string treeNodeId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.GetAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id);
if (adminMenu == null)
{
return NotFound();
}
var treeNode = adminMenu.GetMenuItemById(treeNodeId);
if (treeNode == null)
{
return NotFound();
}
var model = new AdminNodeEditViewModel
{
AdminMenuId = id,
AdminNode = treeNode,
AdminNodeId = treeNode.UniqueId,
AdminNodeType = treeNode.GetType().Name,
Priority = treeNode.Priority,
Position = treeNode.Position,
Editor = await _displayManager.BuildEditorAsync(treeNode, updater: _updateModelAccessor.ModelUpdater, isNew: false)
};
model.Editor.TreeNode = treeNode;
return View(model);
}
[HttpPost]
public async Task<IActionResult> Edit(AdminNodeEditViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, model.AdminMenuId);
if (adminMenu == null)
{
return NotFound();
}
var treeNode = adminMenu.GetMenuItemById(model.AdminNodeId);
if (treeNode == null)
{
return NotFound();
}
var editor = await _displayManager.UpdateEditorAsync(treeNode, updater: _updateModelAccessor.ModelUpdater, isNew: false);
if (ModelState.IsValid)
{
treeNode.Priority = model.Priority;
treeNode.Position = model.Position;
await _adminMenuService.SaveAsync(adminMenu);
_notifier.Success(H["Admin node updated successfully"]);
return RedirectToAction(nameof(List), new { id = model.AdminMenuId });
}
_notifier.Error(H["The admin node has validation errors"]);
model.Editor = editor;
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
public async Task<IActionResult> Delete(string id, string treeNodeId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id);
if (adminMenu == null)
{
return NotFound();
}
var treeNode = adminMenu.GetMenuItemById(treeNodeId);
if (treeNode == null)
{
return NotFound();
}
if (adminMenu.RemoveMenuItem(treeNode) == false)
{
return new StatusCodeResult(500);
}
await _adminMenuService.SaveAsync(adminMenu);
_notifier.Success(H["Admin node deleted successfully"]);
return RedirectToAction(nameof(List), new { id });
}
[HttpPost]
public async Task<IActionResult> Toggle(string id, string treeNodeId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, id);
if (adminMenu == null)
{
return NotFound();
}
var treeNode = adminMenu.GetMenuItemById(treeNodeId);
if (treeNode == null)
{
return NotFound();
}
treeNode.Enabled = !treeNode.Enabled;
await _adminMenuService.SaveAsync(adminMenu);
_notifier.Success(H["Admin node toggled successfully"]);
return RedirectToAction(nameof(List), new { id = id });
}
[HttpPost]
public async Task<IActionResult> MoveNode(string treeId, string nodeToMoveId,
string destinationNodeId, int position)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAdminMenu))
{
return Forbid();
}
var adminMenuList = await _adminMenuService.LoadAdminMenuListAsync();
var adminMenu = _adminMenuService.GetAdminMenuById(adminMenuList, treeId);
if ((adminMenu == null) || (adminMenu.MenuItems == null))
{
return NotFound();
}
var nodeToMove = adminMenu.GetMenuItemById(nodeToMoveId);
if (nodeToMove == null)
{
return NotFound();
}
var destinationNode = adminMenu.GetMenuItemById(destinationNodeId); // don't check for null. When null the item will be moved to the root.
if (adminMenu.RemoveMenuItem(nodeToMove) == false)
{
return StatusCode(500);
}
if (adminMenu.InsertMenuItemAt(nodeToMove, destinationNode, position) == false)
{
return StatusCode(500);
}
await _adminMenuService.SaveAsync(adminMenu);
return Ok();
}
}
}
| |
//
// ArtworkManager.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Mono.Unix;
using Gdk;
using Hyena;
using Hyena.Gui;
using Hyena.Collections;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.IO;
using Banshee.ServiceStack;
namespace Banshee.Collection.Gui
{
public class ArtworkManager : IService
{
private Dictionary<int, SurfaceCache> scale_caches = new Dictionary<int, SurfaceCache> ();
private HashSet<int> cacheable_cover_sizes = new HashSet<int> ();
private class SurfaceCache : LruCache<string, Cairo.ImageSurface>
{
public SurfaceCache (int max_items) : base (max_items)
{
}
protected override void ExpireItem (Cairo.ImageSurface item)
{
if (item != null) {
((IDisposable)item).Dispose ();
}
}
}
public ArtworkManager ()
{
AddCachedSize (36);
AddCachedSize (40);
AddCachedSize (42);
AddCachedSize (48);
AddCachedSize (64);
AddCachedSize (90);
AddCachedSize (300);
try {
MigrateCacheDir ();
} catch (Exception e) {
Log.Exception ("Could not migrate album artwork cache directory", e);
}
Banshee.Metadata.MetadataService.Instance.ArtworkUpdated += OnArtworkUpdated;
}
public void Dispose ()
{
Banshee.Metadata.MetadataService.Instance.ArtworkUpdated -= OnArtworkUpdated;
}
private void OnArtworkUpdated (IBasicTrackInfo track)
{
ClearCacheFor (track.ArtworkId, true);
}
public Cairo.ImageSurface LookupSurface (string id)
{
return LookupScaleSurface (id, 0);
}
public Cairo.ImageSurface LookupScaleSurface (string id, int size)
{
return LookupScaleSurface (id, size, false);
}
public Cairo.ImageSurface LookupScaleSurface (string id, int size, bool useCache)
{
SurfaceCache cache = null;
Cairo.ImageSurface surface = null;
if (id == null) {
return null;
}
if (useCache && scale_caches.TryGetValue (size, out cache) && cache.TryGetValue (id, out surface)) {
return surface;
}
Pixbuf pixbuf = LookupScalePixbuf (id, size);
if (pixbuf == null || pixbuf.Handle == IntPtr.Zero) {
return null;
}
try {
surface = PixbufImageSurface.Create (pixbuf);
if (surface == null) {
return null;
}
if (!useCache) {
return surface;
}
if (cache == null) {
int bytes = 4 * size * size;
int max = (1 << 20) / bytes;
ChangeCacheSize (size, max);
cache = scale_caches[size];
}
cache.Add (id, surface);
return surface;
} finally {
DisposePixbuf (pixbuf);
}
}
public Pixbuf LookupPixbuf (string id)
{
return LookupScalePixbuf (id, 0);
}
public Pixbuf LookupScalePixbuf (string id, int size)
{
if (id == null || (size != 0 && size < 10)) {
return null;
}
// Find the scaled, cached file
string path = CoverArtSpec.GetPathForSize (id, size);
if (File.Exists (new SafeUri (path))) {
try {
return new Pixbuf (path);
} catch {
return null;
}
}
string orig_path = CoverArtSpec.GetPathForSize (id, 0);
bool orig_exists = File.Exists (new SafeUri (orig_path));
if (!orig_exists) {
// It's possible there is an image with extension .cover that's waiting
// to be converted into a jpeg
string unconverted_path = System.IO.Path.ChangeExtension (orig_path, "cover");
if (File.Exists (new SafeUri (unconverted_path))) {
try {
Pixbuf pixbuf = new Pixbuf (unconverted_path);
if (pixbuf.Width < 50 || pixbuf.Height < 50) {
Hyena.Log.DebugFormat ("Ignoring cover art {0} because less than 50x50", unconverted_path);
return null;
}
pixbuf.Save (orig_path, "jpeg");
orig_exists = true;
} catch {
} finally {
File.Delete (new SafeUri (unconverted_path));
}
}
}
if (orig_exists && size >= 10) {
try {
Pixbuf pixbuf = new Pixbuf (orig_path);
// Make it square if width and height difference is within 20%
const double max_ratio = 1.2;
double ratio = (double)pixbuf.Height / pixbuf.Width;
int width = size, height = size;
if (ratio > max_ratio) {
width = (int)Math.Round (size / ratio);
}else if (ratio < 1d / max_ratio) {
height = (int)Math.Round (size * ratio);
}
Pixbuf scaled_pixbuf = pixbuf.ScaleSimple (width, height, Gdk.InterpType.Bilinear);
if (IsCachedSize (size)) {
Directory.Create (System.IO.Path.GetDirectoryName (path));
scaled_pixbuf.Save (path, "jpeg");
} else {
Log.InformationFormat ("Uncached artwork size {0} requested", size);
}
DisposePixbuf (pixbuf);
return scaled_pixbuf;
} catch {}
}
return null;
}
public void ClearCacheFor (string id)
{
ClearCacheFor (id, false);
}
public void ClearCacheFor (string id, bool inMemoryCacheOnly)
{
if (String.IsNullOrEmpty (id)) {
return;
}
// Clear from the in-memory cache
foreach (int size in scale_caches.Keys) {
scale_caches[size].Remove (id);
}
if (inMemoryCacheOnly) {
return;
}
// And delete from disk
foreach (int size in CachedSizes ()) {
var uri = new SafeUri (CoverArtSpec.GetPathForSize (id, size));
if (File.Exists (uri)) {
File.Delete (uri);
}
}
}
public void AddCachedSize (int size)
{
cacheable_cover_sizes.Add (size);
}
public bool IsCachedSize (int size)
{
return cacheable_cover_sizes.Contains (size);
}
public IEnumerable<int> CachedSizes ()
{
return cacheable_cover_sizes;
}
public void ChangeCacheSize (int size, int max_count)
{
SurfaceCache cache;
if (scale_caches.TryGetValue (size, out cache)) {
if (max_count > cache.MaxCount) {
Log.DebugFormat (
"Growing surface cache for {0}px images to {1:0.00} MiB ({2} items)",
size, 4 * size * size * max_count / 1048576d, max_count);
cache.MaxCount = max_count;
}
} else {
Log.DebugFormat (
"Creating new surface cache for {0}px images, capped at {1:0.00} MiB ({2} items)",
size, 4 * size * size * max_count / 1048576d, max_count);
scale_caches.Add (size, new SurfaceCache (max_count));
}
}
private static int dispose_count = 0;
public static void DisposePixbuf (Pixbuf pixbuf)
{
if (pixbuf != null && pixbuf.Handle != IntPtr.Zero) {
pixbuf.Dispose ();
pixbuf = null;
// There is an issue with disposing Pixbufs where we need to explicitly
// call the GC otherwise it doesn't get done in a timely way. But if we
// do it every time, it slows things down a lot; so only do it every 100th.
if (++dispose_count % 100 == 0) {
System.GC.Collect ();
dispose_count = 0;
}
}
}
string IService.ServiceName {
get { return "ArtworkManager"; }
}
#region Cache Directory Versioning/Migration
private const int CUR_VERSION = 3;
private void MigrateCacheDir ()
{
int version = CacheVersion;
if (version == CUR_VERSION) {
return;
}
var legacy_root_path = CoverArtSpec.LegacyRootPath;
if (version < 1) {
string legacy_artwork_path = Paths.Combine (LegacyPaths.ApplicationData, "covers");
if (!Directory.Exists (legacy_root_path)) {
Directory.Create (legacy_root_path);
if (Directory.Exists (legacy_artwork_path)) {
Directory.Move (new SafeUri (legacy_artwork_path), new SafeUri (legacy_root_path));
}
}
if (Directory.Exists (legacy_artwork_path)) {
Log.InformationFormat ("Deleting old (Banshee < 1.0) artwork cache directory {0}", legacy_artwork_path);
Directory.Delete (legacy_artwork_path, true);
}
}
if (version < 2) {
int deleted = 0;
foreach (string dir in Directory.GetDirectories (legacy_root_path)) {
int size;
string dirname = System.IO.Path.GetFileName (dir);
if (Int32.TryParse (dirname, out size) && !IsCachedSize (size)) {
Directory.Delete (dir, true);
deleted++;
}
}
if (deleted > 0) {
Log.InformationFormat ("Deleted {0} extraneous album-art cache directories", deleted);
}
}
if (version < 3) {
Log.Information ("Migrating album-art cache directory");
var started = DateTime.Now;
int count = 0;
var root_path = CoverArtSpec.RootPath;
if (!Directory.Exists (root_path)) {
Directory.Create (root_path);
}
string sql = "SELECT Title, ArtistName FROM CoreAlbums";
using (var reader = new HyenaDataReader (ServiceManager.DbConnection.Query (sql))) {
while (reader.Read ()) {
var album = reader.Get<string>(0);
var artist = reader.Get<string>(1);
var old_file = CoverArtSpec.CreateLegacyArtistAlbumId (artist, album);
var new_file = CoverArtSpec.CreateArtistAlbumId (artist, album);
if (String.IsNullOrEmpty (old_file) || String.IsNullOrEmpty (new_file)) {
continue;
}
old_file = String.Format ("{0}.jpg", old_file);
new_file = String.Format ("{0}.jpg", new_file);
var old_path = new SafeUri (Paths.Combine (legacy_root_path, old_file));
var new_path = new SafeUri (Paths.Combine (root_path, new_file));
if (Banshee.IO.File.Exists (old_path) && !Banshee.IO.File.Exists (new_path)) {
Banshee.IO.File.Move (old_path, new_path);
count++;
}
}
}
if (ServiceManager.DbConnection.TableExists ("PodcastSyndications")) {
sql = "SELECT Title FROM PodcastSyndications";
foreach (var title in ServiceManager.DbConnection.QueryEnumerable<string> (sql)) {
var old_digest = CoverArtSpec.LegacyEscapePart (title);
var new_digest = CoverArtSpec.Digest (title);
if (String.IsNullOrEmpty (old_digest) || String.IsNullOrEmpty (new_digest)) {
continue;
}
var old_file = String.Format ("podcast-{0}.jpg", old_digest);
var new_file = String.Format ("podcast-{0}.jpg", new_digest);
var old_path = new SafeUri (Paths.Combine (legacy_root_path, old_file));
var new_path = new SafeUri (Paths.Combine (root_path, new_file));
if (Banshee.IO.File.Exists (old_path) && !Banshee.IO.File.Exists (new_path)) {
Banshee.IO.File.Move (old_path, new_path);
count++;
}
}
}
Directory.Delete (legacy_root_path, true);
Log.InformationFormat ("Migrated {0} files in {1}s", count, DateTime.Now.Subtract(started).TotalSeconds);
}
CacheVersion = CUR_VERSION;
}
private static SafeUri cache_version_file = new SafeUri (Paths.Combine (CoverArtSpec.RootPath, ".cache_version"));
private static int CacheVersion {
get {
var file = cache_version_file;
if (!Banshee.IO.File.Exists (file)) {
file = new SafeUri (Paths.Combine (CoverArtSpec.LegacyRootPath, ".cache_version"));
if (!Banshee.IO.File.Exists (file)) {
file = null;
}
}
if (file != null) {
using (var reader = new System.IO.StreamReader (Banshee.IO.File.OpenRead (file))) {
int version;
if (Int32.TryParse (reader.ReadLine (), out version)) {
return version;
}
}
}
return 0;
}
set {
using (var writer = new System.IO.StreamWriter (Banshee.IO.File.OpenWrite (cache_version_file, true))) {
writer.Write (value.ToString ());
}
}
}
#endregion
}
}
| |
#region PDFsharp Charting - A .NET charting library based on PDFsharp
//
// Authors:
// Niklas Schneider
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// 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.Collections.Generic;
using PdfSharp.Drawing;
using PdfSharp.Charting.Renderers;
namespace PdfSharp.Charting
{
/// <summary>
/// Represents the frame which holds one or more charts.
/// </summary>
public class ChartFrame
{
/// <summary>
/// Initializes a new instance of the ChartFrame class.
/// </summary>
public ChartFrame()
{ }
/// <summary>
/// Initializes a new instance of the ChartFrame class with the specified rectangle.
/// </summary>
public ChartFrame(XRect rect)
{
_location = rect.Location;
_size = rect.Size;
}
/// <summary>
/// Gets or sets the location of the ChartFrame.
/// </summary>
public XPoint Location
{
get { return _location; }
set { _location = value; }
}
XPoint _location;
/// <summary>
/// Gets or sets the size of the ChartFrame.
/// </summary>
public XSize Size
{
get { return _size; }
set { _size = value; }
}
XSize _size;
/// <summary>
/// Adds a chart to the ChartFrame.
/// </summary>
public void Add(Chart chart)
{
if (_chartList == null)
_chartList = new List<Chart>();
_chartList.Add(chart);
}
/// <summary>
/// Draws all charts inside the ChartFrame.
/// </summary>
public void Draw(XGraphics gfx)
{
// Draw frame of ChartFrame. First shadow frame.
const int dx = 5;
const int dy = 5;
gfx.DrawRoundedRectangle(XBrushes.Gainsboro,
_location.X + dx, _location.Y + dy,
_size.Width, _size.Height, 20, 20);
XRect chartRect = new XRect(_location.X, _location.Y, _size.Width, _size.Height);
XLinearGradientBrush brush = new XLinearGradientBrush(chartRect, XColor.FromArgb(0xFFD0DEEF), XColors.White,
XLinearGradientMode.Vertical);
XPen penBorder = new XPen(XColors.SteelBlue, 2.5);
gfx.DrawRoundedRectangle(penBorder, brush,
_location.X, _location.Y, _size.Width, _size.Height,
15, 15);
XGraphicsState state = gfx.Save();
gfx.TranslateTransform(_location.X, _location.Y);
// Calculate rectangle for all charts. Y-Position will be moved for each chart.
int charts = _chartList.Count;
const uint dxChart = 20;
const uint dyChart = 20;
const uint dyBetweenCharts = 30;
XRect rect = new XRect(dxChart, dyChart,
_size.Width - 2 * dxChart,
(_size.Height - (charts - 1) * dyBetweenCharts - 2 * dyChart) / charts);
// draw each chart in list
foreach (Chart chart in _chartList)
{
RendererParameters parms = new RendererParameters(gfx, rect);
parms.DrawingItem = chart;
ChartRenderer renderer = GetChartRenderer(chart, parms);
renderer.Init();
renderer.Format();
renderer.Draw();
rect.Y += rect.Height + dyBetweenCharts;
}
gfx.Restore(state);
// // Calculate rectangle for all charts. Y-Position will be moved for each chart.
// int charts = chartList.Count;
// uint dxChart = 0;
// uint dyChart = 0;
// uint dyBetweenCharts = 0;
// XRect rect = new XRect(dxChart, dyChart,
// size.Width - 2 * dxChart,
// (size.Height - (charts - 1) * dyBetweenCharts - 2 * dyChart) / charts);
//
// // draw each chart in list
// foreach (Chart chart in chartList)
// {
// RendererParameters parms = new RendererParameters(gfx, rect);
// parms.DrawingItem = chart;
//
// ChartRenderer renderer = GetChartRenderer(chart, parms);
// renderer.Init();
// renderer.Format();
// renderer.Draw();
//
// rect.Y += rect.Height + dyBetweenCharts;
// }
}
/// <summary>
/// Draws first chart only.
/// </summary>
public void DrawChart(XGraphics gfx)
{
XGraphicsState state = gfx.Save();
gfx.TranslateTransform(_location.X, _location.Y);
if (_chartList.Count > 0)
{
XRect chartRect = new XRect(0, 0, _size.Width, _size.Height);
Chart chart = (Chart)_chartList[0];
RendererParameters parms = new RendererParameters(gfx, chartRect);
parms.DrawingItem = chart;
ChartRenderer renderer = GetChartRenderer(chart, parms);
renderer.Init();
renderer.Format();
renderer.Draw();
}
gfx.Restore(state);
}
/// <summary>
/// Returns the chart renderer appropriate for the chart.
/// </summary>
private ChartRenderer GetChartRenderer(Chart chart, RendererParameters parms)
{
ChartType chartType = chart.Type;
bool useCombinationRenderer = false;
foreach (Series series in chart._seriesCollection)
{
if (series._chartType != chartType)
{
useCombinationRenderer = true;
break;
}
}
if (useCombinationRenderer)
return new CombinationChartRenderer(parms);
switch (chartType)
{
case ChartType.Line:
return new LineChartRenderer(parms);
case ChartType.Column2D:
case ChartType.ColumnStacked2D:
return new ColumnChartRenderer(parms);
case ChartType.Bar2D:
case ChartType.BarStacked2D:
return new BarChartRenderer(parms);
case ChartType.Area2D:
return new AreaChartRenderer(parms);
case ChartType.Pie2D:
case ChartType.PieExploded2D:
return new PieChartRenderer(parms);
}
return null;
}
/// <summary>
/// Holds the charts which will be drawn inside the ChartFrame.
/// </summary>
List<Chart> _chartList;
}
}
| |
//
// ColumnCellText.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Cairo;
using Hyena.Gui;
using Hyena.Gui.Theming;
using Hyena.Data.Gui.Accessibility;
namespace Hyena.Data.Gui
{
public class ColumnCellText : ColumnCell, ISizeRequestCell, ITextCell, ITooltipCell
{
internal const int Spacing = 4;
public delegate string DataHandler ();
private Pango.Weight font_weight = Pango.Weight.Normal;
private Pango.EllipsizeMode ellipsize_mode = Pango.EllipsizeMode.End;
private Pango.Alignment alignment = Pango.Alignment.Left;
private int text_width;
private int text_height;
private string text_format = null;
protected string MinString, MaxString;
private string last_text = null;
private bool use_markup;
public ColumnCellText (string property, bool expand) : base (property, expand)
{
}
public override Atk.Object GetAccessible (ICellAccessibleParent parent)
{
return new ColumnCellTextAccessible (BoundObject, this, parent);
}
public override string GetTextAlternative (object obj)
{
return GetText (obj);
}
public void SetMinMaxStrings (object min_max)
{
SetMinMaxStrings (min_max, min_max);
}
public void SetMinMaxStrings (object min, object max)
{
// Set the min/max strings from the min/max objects
MinString = GetText (min);
MaxString = GetText (max);
RestrictSize = true;
}
public override void Render (CellContext context, StateType state, double cellWidth, double cellHeight)
{
UpdateText (context, cellWidth);
if (String.IsNullOrEmpty (last_text)) {
return;
}
context.Context.Rectangle (0, 0, cellWidth, cellHeight);
context.Context.Clip ();
context.Context.MoveTo (Spacing, ((int)cellHeight - text_height) / 2);
Cairo.Color color = context.Theme.Colors.GetWidgetColor (
context.TextAsForeground ? GtkColorClass.Foreground : GtkColorClass.Text, state);
color.A = context.Opaque ? 1.0 : 0.5;
context.Context.Color = color;
PangoCairoHelper.ShowLayout (context.Context, context.Layout);
context.Context.ResetClip ();
}
public void UpdateText (CellContext context, double cellWidth)
{
string text = last_text = GetText (BoundObject);
if (String.IsNullOrEmpty (text)) {
return;
}
// TODO why doesn't Spacing (eg 4 atm) work here instead of 8? Rendering
// seems to be off when changed to Spacing/4
context.Layout.Width = (int)((cellWidth - 8) * Pango.Scale.PangoScale);
context.Layout.FontDescription.Weight = font_weight;
context.Layout.Ellipsize = EllipsizeMode;
context.Layout.Alignment = alignment;
UpdateLayout (context.Layout, text);
context.Layout.GetPixelSize (out text_width, out text_height);
is_ellipsized = context.Layout.IsEllipsized;
}
private static char[] lfcr = new char[] {'\n', '\r'};
private void UpdateLayout (Pango.Layout layout, string text)
{
string final_text = GetFormattedText (text);
if (final_text.IndexOfAny (lfcr) >= 0) {
final_text = final_text.Replace ("\r\n", "\x20").Replace ('\n', '\x20').Replace ('\r', '\x20');
}
if (use_markup) {
layout.SetMarkup (final_text);
} else {
layout.SetText (final_text);
}
}
public string GetTooltipMarkup (CellContext cellContext, double columnWidth)
{
UpdateText (cellContext, columnWidth);
return IsEllipsized ? GLib.Markup.EscapeText (Text) : null;
}
protected virtual string GetText (object obj)
{
return obj == null ? String.Empty : obj.ToString ();
}
private string GetFormattedText (string text)
{
if (text_format == null) {
return text;
}
return String.Format (text_format, text);
}
private bool is_ellipsized = false;
public bool IsEllipsized {
get { return is_ellipsized; }
}
public string Text {
get { return last_text; }
}
protected int TextWidth {
get { return text_width; }
}
protected int TextHeight {
get { return text_height; }
}
public string TextFormat {
get { return text_format; }
set { text_format = value; }
}
public Pango.Alignment Alignment {
get { return alignment; }
set { alignment = value; }
}
public virtual Pango.Weight FontWeight {
get { return font_weight; }
set { font_weight = value; }
}
public virtual Pango.EllipsizeMode EllipsizeMode {
get { return ellipsize_mode; }
set { ellipsize_mode = value; }
}
internal static int ComputeRowHeight (Widget widget)
{
int w_width, row_height;
Pango.Layout layout = new Pango.Layout (widget.PangoContext);
layout.SetText ("W");
layout.GetPixelSize (out w_width, out row_height);
layout.Dispose ();
return row_height + 8;
}
#region ISizeRequestCell implementation
public void GetWidthRange (Pango.Layout layout, out int min, out int max)
{
int height;
min = max = -1;
if (!String.IsNullOrEmpty (MinString)) {
UpdateLayout (layout, MinString);
layout.GetPixelSize (out min, out height);
min += 2*Spacing;
//Console.WriteLine ("for {0} got min {1} for {2}", this, min, MinString);
}
if (!String.IsNullOrEmpty (MaxString)) {
UpdateLayout (layout, MaxString);
layout.GetPixelSize (out max, out height);
max += 2*Spacing;
//Console.WriteLine ("for {0} got max {1} for {2}", this, max, MaxString);
}
}
private bool restrict_size = false;
public bool RestrictSize {
get { return restrict_size; }
set { restrict_size = value; }
}
public bool UseMarkup {
get { return use_markup; }
set { use_markup = value; }
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 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 OpenMetaverse;
namespace Aurora.Framework
{
public struct ContactPoint
{
public float PenetrationDepth;
public Vector3 Position;
public Vector3 SurfaceNormal;
public ActorTypes Type;
public ContactPoint(Vector3 position, Vector3 surfaceNormal, float penetrationDepth, ActorTypes type)
{
Type = type;
Position = position;
SurfaceNormal = surfaceNormal;
PenetrationDepth = penetrationDepth;
}
}
public class CollisionEventUpdate : EventArgs
{
// Raising the event on the object, so don't need to provide location.. further up the tree knows that info.
public bool Cleared;
public Dictionary<uint, ContactPoint> m_objCollisionList = new Dictionary<uint, ContactPoint>();
public CollisionEventUpdate(Dictionary<uint, ContactPoint> objCollisionList)
{
m_objCollisionList = objCollisionList;
}
public CollisionEventUpdate()
{
m_objCollisionList = new Dictionary<uint, ContactPoint>();
}
public void addCollider(uint localID, ContactPoint contact)
{
Cleared = false;
/*ContactPoint oldCol;
if(!m_objCollisionList.TryGetValue(localID, out oldCol))
{
*/
lock (m_objCollisionList)
m_objCollisionList[localID] = contact;
/*}
else
{
if(oldCol.PenetrationDepth < contact.PenetrationDepth)
lock(m_objCollisionList)
m_objCollisionList[localID] = contact;
}*/
}
/// <summary>
/// Reset all the info about this collider
/// </summary>
public void Clear()
{
Cleared = true;
lock (m_objCollisionList)
m_objCollisionList.Clear();
}
public CollisionEventUpdate Copy()
{
CollisionEventUpdate c = new CollisionEventUpdate();
lock (m_objCollisionList)
{
foreach (KeyValuePair<uint, ContactPoint> kvp in m_objCollisionList)
c.m_objCollisionList.Add(kvp.Key, kvp.Value);
}
return c;
}
}
public delegate void PositionUpdate(Vector3 position);
public delegate void VelocityUpdate(Vector3 velocity);
public delegate void OrientationUpdate(Quaternion orientation);
public enum ActorTypes
{
Unknown = 0,
Agent = 1,
Prim = 2,
Ground = 3,
Water = 4
}
public abstract class PhysicsCharacter : PhysicsActor
{
public abstract bool IsJumping { get; }
public abstract float SpeedModifier { get; set; }
public abstract bool IsPreJumping { get; }
public abstract bool Flying { get; set; }
public abstract bool SetAlwaysRun { get; set; }
public virtual void AddMovementForce(Vector3 force) { }
public virtual void SetMovementForce(Vector3 force) { }
public virtual void Destroy() { }
public delegate bool checkForRegionCrossing();
public event checkForRegionCrossing OnCheckForRegionCrossing;
public virtual bool CheckForRegionCrossing()
{
// Make a temporary copy of the event to avoid possibility of
// a race condition if the last subscriber unsubscribes
// immediately after the null check and before the event is raised.
checkForRegionCrossing handler = OnCheckForRegionCrossing;
if (handler != null)
return handler();
return false;
}
}
public abstract class PhysicsObject : PhysicsActor
{
public virtual void link(PhysicsObject obj) { }
public virtual void delink() { }
public virtual bool LinkSetIsColliding { get; set; }
public virtual void LockAngularMotion(Vector3 axis) { }
public virtual PrimitiveBaseShape Shape
{
set { if (value == null) throw new ArgumentNullException("value"); }
}
public abstract bool Selected { set; }
public abstract void CrossingFailure();
public virtual void SetMaterial(int material, bool forceMaterialSettings) { }
// set never appears to be called
public virtual int VehicleType { get { return 0; } set { return; } }
public virtual void VehicleFloatParam(int param, float value) { }
public virtual void VehicleVectorParam(int param, Vector3 value) { }
public virtual void VehicleRotationParam(int param, Quaternion rotation) { }
public virtual void VehicleFlags(int param, bool remove) { }
public virtual void SetCameraPos(Quaternion CameraRotation) { }
public virtual bool BuildingRepresentation { get; set; }
public virtual bool BlockPhysicalReconstruction { get; set; }
public abstract float Buoyancy { get; set; }
public abstract Vector3 CenterOfMass { get; }
public abstract Vector3 Torque { get; set; }
public abstract void SubscribeEvents(int ms);
public abstract void UnSubscribeEvents();
//set never appears to be called
public virtual bool VolumeDetect
{
get { return false; }
set { return; }
}
public abstract Vector3 Acceleration { get; }
public abstract void AddAngularForce(Vector3 force, bool pushforce);
public virtual void ClearVelocity()
{
}
public event BlankHandler OnPhysicalRepresentationChanged;
public void FirePhysicalRepresentationChanged()
{
if (OnPhysicalRepresentationChanged != null)
OnPhysicalRepresentationChanged();
}
public virtual void Destroy()
{
}
}
public abstract class PhysicsActor
{
// disable warning: public events
#pragma warning disable 67
public delegate void RequestTerseUpdate();
public delegate void CollisionUpdate(EventArgs e);
public delegate void OutOfBounds(Vector3 pos);
public event RequestTerseUpdate OnRequestTerseUpdate;
public event RequestTerseUpdate OnSignificantMovement;
public event RequestTerseUpdate OnPositionAndVelocityUpdate;
public event CollisionUpdate OnCollisionUpdate;
public event OutOfBounds OnOutOfBounds;
#pragma warning restore 67
public abstract Vector3 Size { get; set; }
public abstract uint LocalID { get; set; }
public UUID UUID { get; set; }
public virtual void RequestPhysicsterseUpdate()
{
// Make a temporary copy of the event to avoid possibility of
// a race condition if the last subscriber unsubscribes
// immediately after the null check and before the event is raised.
RequestTerseUpdate handler = OnRequestTerseUpdate;
if (handler != null)
handler();
}
public virtual void RaiseOutOfBounds(Vector3 pos)
{
// Make a temporary copy of the event to avoid possibility of
// a race condition if the last subscriber unsubscribes
// immediately after the null check and before the event is raised.
OutOfBounds handler = OnOutOfBounds;
if (handler != null)
handler(pos);
}
public virtual void SendCollisionUpdate(EventArgs e)
{
CollisionUpdate handler = OnCollisionUpdate;
if (handler != null)
handler(e);
}
public virtual bool SubscribedToCollisions()
{
return OnCollisionUpdate != null;
}
public virtual void TriggerSignificantMovement()
{
//Call significant movement
RequestTerseUpdate significantMovement = OnSignificantMovement;
if (significantMovement != null)
significantMovement();
}
public virtual void TriggerMovementUpdate()
{
//Call significant movement
RequestTerseUpdate movementUpdate = OnPositionAndVelocityUpdate;
if (movementUpdate != null)
movementUpdate();
}
public abstract Vector3 Position { get; set; }
public abstract float Mass { get; }
public abstract Vector3 Force { get; set; }
public abstract Vector3 Velocity { get; set; }
public abstract float CollisionScore { get; set; }
public abstract Quaternion Orientation { get; set; }
public abstract int PhysicsActorType { get; }
public abstract bool IsPhysical { get; set; }
public abstract bool ThrottleUpdates { get; set; }
public abstract bool IsColliding { get; set; }
public abstract bool IsTruelyColliding { get; set; }
public abstract bool FloatOnWater { set; }
public abstract Vector3 RotationalVelocity { get; set; }
public abstract void AddForce(Vector3 force, bool pushforce);
public abstract bool SubscribedEvents();
public abstract void SendCollisions();
public abstract void AddCollisionEvent(uint localID, ContactPoint contact);
public virtual void ForceSetVelocity(Vector3 velocity)
{
}
public virtual void ForceSetPosition(Vector3 position)
{
}
}
public class NullObjectPhysicsActor : PhysicsObject
{
public override Vector3 Position
{
get { return Vector3.Zero; }
set { return; }
}
public override uint LocalID
{
get { return 0; }
set { return; }
}
public override bool Selected
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override Vector3 Size
{
get { return Vector3.Zero; }
set { return; }
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 Velocity
{
get { return Vector3.Zero; }
set { return; }
}
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set { }
}
public override Vector3 Acceleration
{
get { return Vector3.Zero; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool IsColliding { get; set; }
public override bool IsTruelyColliding { get; set; }
public override int PhysicsActorType
{
get { return (int) ActorTypes.Ground; }
}
public override Vector3 RotationalVelocity
{
get { return Vector3.Zero; }
set { return; }
}
public override void CrossingFailure()
{
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
public override void SendCollisions()
{
}
public override void AddCollisionEvent(uint CollidedWith, ContactPoint contact)
{
}
}
public class NullCharacterPhysicsActor : PhysicsCharacter
{
public override bool IsJumping
{
get { return false; }
}
public override bool IsPreJumping
{
get { return false; }
}
public override float SpeedModifier
{
get { return 1.0f; }
set { }
}
public override Vector3 Position
{
get { return Vector3.Zero; }
set { return; }
}
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
get { return 0; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override Vector3 Size
{
get { return Vector3.Zero; }
set { return; }
}
public override float Mass
{
get { return 0f; }
}
public override Vector3 Force
{
get { return Vector3.Zero; }
set { return; }
}
public override Vector3 Velocity
{
get { return Vector3.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set { }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool Flying
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool IsTruelyColliding { get; set; }
public override bool IsColliding { get; set; }
public override int PhysicsActorType
{
get { return (int) ActorTypes.Unknown; }
}
public override Vector3 RotationalVelocity
{
get { return Vector3.Zero; }
set { return; }
}
public override void AddForce(Vector3 force, bool pushforce)
{
}
public override bool SubscribedEvents()
{
return false;
}
public override void SendCollisions()
{
}
public override void AddCollisionEvent(uint CollidedWith, ContactPoint contact)
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using AccountActivityDemo.Areas.HelpPage.ModelDescriptions;
using AccountActivityDemo.Areas.HelpPage.Models;
namespace AccountActivityDemo.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
public static partial class SkipUrlEncodingOperationsExtensions
{
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetMethodPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodPathValidAsync(unencodedPathParam), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodPathValidAsync( this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetPathPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetPathPathValidAsync(unencodedPathParam), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetPathPathValidAsync( this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetPathPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// An unencoded path parameter with value 'path1/path2/path3'. Possible
/// values for this parameter include: 'path1/path2/path3'
/// </param>
public static void GetSwaggerPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetSwaggerPathValidAsync(unencodedPathParam), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// An unencoded path parameter with value 'path1/path2/path3'. Possible
/// values for this parameter include: 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetSwaggerPathValidAsync( this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetSwaggerPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetMethodQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodQueryValidAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodQueryValidAsync( this ISkipUrlEncodingOperations operations, string q1, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
public static void GetMethodQueryNull(this ISkipUrlEncodingOperations operations, string q1 = default(string))
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodQueryNullAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodQueryNullAsync( this ISkipUrlEncodingOperations operations, string q1 = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodQueryNullWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetPathQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetPathQueryValidAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetPathQueryValidAsync( this ISkipUrlEncodingOperations operations, string q1, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetPathQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// An unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'. Possible values for this parameter
/// include: 'value1&q2=value2&q3=value3'
/// </param>
public static void GetSwaggerQueryValid(this ISkipUrlEncodingOperations operations, string q1 = default(string))
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetSwaggerQueryValidAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// An unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'. Possible values for this parameter
/// include: 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetSwaggerQueryValidAsync( this ISkipUrlEncodingOperations operations, string q1 = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetSwaggerQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Dynamic;
using System.Linq;
using System.Text;
namespace Massive.Oracle {
public static class ObjectExtensions {
/// <summary>
/// Extension method for adding in a bunch of parameters
/// </summary>
public static void AddParams(this DbCommand cmd, params object[] args) {
foreach (var item in args) {
AddParam(cmd, item);
}
}
/// <summary>
/// Extension for adding single parameter
/// </summary>
public static void AddParam(this DbCommand cmd, object item) {
var p = cmd.CreateParameter();
p.ParameterName = string.Format(":{0}", cmd.Parameters.Count);
if (item == null) {
p.Value = DBNull.Value;
} else {
if (item.GetType() == typeof(Guid)) {
p.Value = item.ToString();
p.DbType = DbType.String;
p.Size = 4000;
} else if (item.GetType() == typeof(ExpandoObject)) {
var d = (IDictionary<string, object>)item;
p.Value = d.Values.FirstOrDefault();
} else {
p.Value = item;
}
if (item.GetType() == typeof(string))
p.Size = ((string)item).Length > 4000 ? -1 : 4000;
}
cmd.Parameters.Add(p);
}
/// <summary>
/// Turns an IDataReader to a Dynamic list of things
/// </summary>
public static List<dynamic> ToExpandoList(this IDataReader rdr) {
var result = new List<dynamic>();
while (rdr.Read()) {
result.Add(rdr.RecordToExpando());
}
return result;
}
public static dynamic RecordToExpando(this IDataReader rdr) {
dynamic e = new ExpandoObject();
var d = e as IDictionary<string, object>;
object[] values = new object[rdr.FieldCount];
rdr.GetValues(values);
for(int i = 0; i < values.Length; i++)
{
var v = values[i];
d.Add(rdr.GetName(i), DBNull.Value.Equals(v) ? null : v);
}
return e;
}
/// <summary>
/// Turns the object into an ExpandoObject
/// </summary>
public static dynamic ToExpando(this object o) {
if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case
var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection))) {
var nv = (NameValueCollection)o;
nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i));
} else {
var props = o.GetType().GetProperties();
foreach (var item in props) {
d.Add(item.Name, item.GetValue(o, null));
}
}
return result;
}
/// <summary>
/// Turns the object into a Dictionary
/// </summary>
public static IDictionary<string, object> ToDictionary(this object thingy) {
return (IDictionary<string, object>)thingy.ToExpando();
}
}
/// <summary>
/// Convenience class for opening/executing data
/// </summary>
public static class DB {
public static DynamicModel Current {
get {
if (ConfigurationManager.ConnectionStrings.Count > 1) {
return new DynamicModel(ConfigurationManager.ConnectionStrings[1].Name);
}
throw new InvalidOperationException("Need a connection string name - can't determine what it is");
}
}
}
/// <summary>
/// A class that wraps your database table in Dynamic Funtime
/// </summary>
public class DynamicModel : DynamicObject {
DbProviderFactory _factory;
string ConnectionString;
string _sequence;
public static DynamicModel Open(string connectionStringName) {
dynamic dm = new DynamicModel(connectionStringName);
return dm;
}
public DynamicModel(string connectionStringName, string tableName = "",
string primaryKeyField = "", string descriptorField = "", string sequence = "") {
TableName = tableName == "" ? this.GetType().Name : tableName;
PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;
DescriptorField = descriptorField;
_sequence = sequence == "" ? ConfigurationManager.AppSettings["default_seq"] : sequence;
var _providerName = "System.Data.OracleClient";
var _connectionStringKey = ConfigurationManager.ConnectionStrings[connectionStringName];
if (_connectionStringKey == null) {
ConnectionString = connectionStringName;
} else {
ConnectionString = _connectionStringKey.ConnectionString;
if (!string.IsNullOrEmpty(_connectionStringKey.ProviderName)) {
_providerName = _connectionStringKey.ProviderName;
}
}
_factory = DbProviderFactories.GetFactory(_providerName);
}
/// <summary>
/// Creates a new Expando from a Form POST - white listed against the columns in the DB
/// </summary>
public dynamic CreateFrom(NameValueCollection coll) {
dynamic result = new ExpandoObject();
var dc = (IDictionary<string, object>)result;
var schema = Schema;
//loop the collection, setting only what's in the Schema
foreach (var item in coll.Keys) {
var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == item.ToString().ToLower());
if (exists) {
var key = item.ToString();
var val = coll[key];
dc.Add(key, val);
}
}
return result;
}
/// <summary>
/// Gets a default value for the column
/// </summary>
public dynamic DefaultValue(dynamic column) {
dynamic result = null;
string def = column.COLUMN_DEFAULT;
if (String.IsNullOrEmpty(def)) {
result = null;
} else if (def == "getdate()" || def == "(getdate())") {
result = DateTime.Now.ToShortDateString();
} else if (def == "newid()") {
result = Guid.NewGuid().ToString();
} else {
result = def.Replace("(", "").Replace(")", "");
}
return result;
}
/// <summary>
/// Creates an empty Expando set with defaults from the DB
/// </summary>
public dynamic Prototype {
get {
dynamic result = new ExpandoObject();
var schema = Schema;
foreach (dynamic column in schema) {
var dc = (IDictionary<string, object>)result;
dc.Add(column.COLUMN_NAME, DefaultValue(column));
}
result._Table = this;
return result;
}
}
public string DescriptorField { get; protected set; }
/// <summary>
/// List out all the schema bits for use with ... whatever
/// </summary>
IEnumerable<dynamic> _schema;
public IEnumerable<dynamic> Schema {
get {
if (_schema == null)
_schema = Query("SELECT * FROM USER_TAB_COLUMNS WHERE TABLE_NAME = :0", TableName);
return _schema;
}
}
/// <summary>
/// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert
/// </summary>
public virtual IEnumerable<dynamic> Query(string sql, params object[] args) {
using (var conn = OpenConnection()) {
var rdr = CreateCommand(sql, conn, args).ExecuteReader();
while (rdr.Read()) {
yield return rdr.RecordToExpando(); ;
}
}
}
public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args) {
using (var rdr = CreateCommand(sql, connection, args).ExecuteReader()) {
while (rdr.Read()) {
yield return rdr.RecordToExpando(); ;
}
}
}
/// <summary>
/// Returns a single result
/// </summary>
public virtual object Scalar(string sql, params object[] args) {
object result = null;
using (var conn = OpenConnection()) {
result = CreateCommand(sql, conn, args).ExecuteScalar();
}
return result;
}
/// <summary>
/// Creates a DBCommand that you can use for loving your database.
/// </summary>
public DbCommand CreateCommand(string sql, DbConnection conn, params object[] args) {
var result = _factory.CreateCommand();
result.Connection = conn;
result.CommandText = sql;
if (args.Length > 0)
result.AddParams(args);
return result;
}
/// <summary>
/// Returns and OpenConnection
/// </summary>
public virtual DbConnection OpenConnection() {
var result = _factory.CreateConnection();
result.ConnectionString = ConnectionString;
result.Open();
return result;
}
/// <summary>
/// Builds a set of Insert and Update commands based on the passed-on objects.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual List<DbCommand> BuildCommands(params object[] things) {
var commands = new List<DbCommand>();
foreach (var item in things) {
if (HasPrimaryKey(item)) {
commands.Add(CreateUpdateCommand(item.ToExpando(), GetPrimaryKey(item)));
} else {
commands.Add(CreateInsertCommand(item.ToExpando()));
}
}
return commands;
}
public virtual int Execute(DbCommand command) {
return Execute(new DbCommand[] { command });
}
public virtual int Execute(string sql, params object[] args) {
return Execute(CreateCommand(sql, null, args));
}
/// <summary>
/// Executes a series of DBCommands in a transaction
/// </summary>
public virtual int Execute(IEnumerable<DbCommand> commands) {
var result = 0;
using (var conn = OpenConnection()) {
using (var tx = conn.BeginTransaction()) {
foreach (var cmd in commands) {
cmd.Connection = conn;
cmd.Transaction = tx;
result += cmd.ExecuteNonQuery();
}
tx.Commit();
}
}
return result;
}
public virtual string PrimaryKeyField { get; set; }
/// <summary>
/// Conventionally introspects the object passed in for a field that
/// looks like a PK. If you've named your PrimaryKeyField, this becomes easy
/// </summary>
public virtual bool HasPrimaryKey(object o) {
return o.ToDictionary().ContainsKey(PrimaryKeyField);
}
/// <summary>
/// If the object passed in has a property with the same name as your PrimaryKeyField
/// it is returned here.
/// </summary>
public virtual object GetPrimaryKey(object o) {
object result = null;
o.ToDictionary().TryGetValue(PrimaryKeyField, out result);
return result;
}
public virtual string TableName { get; set; }
/// <summary>
/// Returns all records complying with the passed-in WHERE clause and arguments,
/// ordered as specified, limited (TOP) by limit.
/// </summary>
public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args) {
string sql = BuildSelect(where, orderBy, limit);
return Query(string.Format(sql, columns, TableName), args);
}
private static string BuildSelect(string where, string orderBy, int limit) {
string sql = "SELECT {0} FROM {1} ";
if (!string.IsNullOrEmpty(where))
sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where;
if (limit > 0) sql += " AND ROWNUM <=" + limit;
if (!String.IsNullOrEmpty(orderBy))
sql += orderBy.Trim().StartsWith("order by", StringComparison.OrdinalIgnoreCase) ? orderBy : " ORDER BY " + orderBy;
return sql;
}
/// <summary>
/// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords.
/// </summary>
public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) {
dynamic result = new ExpandoObject();
var countSQL = string.Format("SELECT COUNT({0}) FROM {1} ", PrimaryKeyField, TableName);
if (String.IsNullOrEmpty(orderBy))
orderBy = PrimaryKeyField;
if (!string.IsNullOrEmpty(where)) {
if (!where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase)) {
where = "WHERE " + where;
}
}
var sql = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, pageSize, orderBy, TableName, where);
var pageStart = (currentPage - 1) * pageSize;
sql += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize));
countSQL += where;
result.TotalRecords = Scalar(countSQL, args);
result.TotalPages = result.TotalRecords / pageSize;
if (result.TotalRecords % pageSize > 0)
result.TotalPages += 1;
result.Items = Query(string.Format(sql, columns, TableName), args);
return result;
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(string where, params object[] args) {
var sql = string.Format("SELECT * FROM {0} WHERE {1}", TableName, where);
return Query(sql, args).FirstOrDefault();
}
/// <summary>
/// Returns a single row from the database
/// </summary>
public virtual dynamic Single(object key, string columns = "*") {
var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = :0", columns, TableName, PrimaryKeyField);
return Query(sql, key).FirstOrDefault();
}
/// <summary>
/// This will return a string/object dictionary for dropdowns etc
/// </summary>
public virtual IDictionary<string, object> KeyValues(string orderBy = "") {
if (String.IsNullOrEmpty(DescriptorField))
throw new InvalidOperationException("There's no DescriptorField set - do this in your constructor to describe the text value you want to see");
var sql = string.Format("SELECT {0},{1} FROM {2} ", PrimaryKeyField, DescriptorField, TableName);
if (!String.IsNullOrEmpty(orderBy))
sql += "ORDER BY " + orderBy;
var results = Query(sql).ToList().Cast<IDictionary<string, object>>();
return results.ToDictionary(key => key[PrimaryKeyField].ToString(), value => value[DescriptorField]);
}
/// <summary>
/// This will return an Expando as a Dictionary
/// </summary>
public virtual IDictionary<string, object> ItemAsDictionary(ExpandoObject item) {
return (IDictionary<string, object>)item;
}
//Checks to see if a key is present based on the passed-in value
public virtual bool ItemContainsKey(string key, ExpandoObject item) {
var dc = ItemAsDictionary(item);
return dc.ContainsKey(key);
}
/// <summary>
/// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction.
/// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects
/// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs
/// </summary>
public virtual int Save(params object[] things) {
foreach (var item in things) {
if (!IsValid(item)) {
throw new InvalidOperationException("Can't save this item: " + String.Join("; ", Errors.ToArray()));
}
}
var commands = BuildCommands(things);
return Execute(commands);
}
public virtual DbCommand CreateInsertCommand(dynamic expando) {
DbCommand result = null;
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var sbVals = new StringBuilder();
var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})";
result = CreateCommand(stub, null);
int counter = 0;
foreach (var item in settings) {
sbKeys.AppendFormat("{0},", item.Key);
sbVals.AppendFormat(":{0},", counter.ToString());
result.AddParam(item.Value);
counter++;
}
if (counter > 0) {
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1);
var vals = sbVals.ToString().Substring(0, sbVals.Length - 1);
var sql = string.Format(stub, TableName, keys, vals);
result.CommandText = sql;
} else throw new InvalidOperationException("Can't parse this object to the database - there are no properties set");
return result;
}
/// <summary>
/// Creates a command for use with transactions - internal stuff mostly, but here for you to play with
/// </summary>
public virtual DbCommand CreateUpdateCommand(dynamic expando, object key) {
var settings = (IDictionary<string, object>)expando;
var sbKeys = new StringBuilder();
var stub = "UPDATE {0} SET {1} WHERE {2} = :{3}";
var args = new List<object>();
var result = CreateCommand(stub, null);
int counter = 0;
foreach (var item in settings) {
var val = item.Value;
if (!item.Key.Equals(PrimaryKeyField, StringComparison.OrdinalIgnoreCase) && item.Value != null) {
result.AddParam(val);
sbKeys.AppendFormat("{0} = :{1}, \r\n", item.Key, counter.ToString());
counter++;
}
}
if (counter > 0) {
//add the key
result.AddParam(key);
//strip the last commas
var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4);
result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter);
} else throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs");
return result;
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public virtual DbCommand CreateDeleteCommand(string where = "", object key = null, params object[] args) {
var sql = string.Format("DELETE FROM {0} ", TableName);
if (key != null) {
sql += string.Format("WHERE {0}=:0", PrimaryKeyField);
args = new object[] { key };
} else if (!string.IsNullOrEmpty(where)) {
sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where;
}
return CreateCommand(sql, null, args);
}
public bool IsValid(dynamic item) {
Errors.Clear();
Validate(item);
return Errors.Count == 0;
}
//Temporary holder for error messages
public IList<string> Errors = new List<string>();
/// <summary>
/// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString
/// </summary>
public virtual dynamic Insert(object o) {
var ex = o.ToExpando();
if (!IsValid(ex)) {
throw new InvalidOperationException("Can't insert: " + String.Join("; ", Errors.ToArray()));
}
if (BeforeSave(ex)) {
using (dynamic conn = OpenConnection()) {
var cmd = CreateInsertCommand(ex);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
if (!string.IsNullOrEmpty(_sequence))
{
cmd.CommandText = "SELECT " + _sequence + ".NEXTVAL as newID FROM DUAL";
ex.ID = cmd.ExecuteScalar();
}
Inserted(ex);
}
return ex;
} else {
return null;
}
}
/// <summary>
/// Updates a record in the database. You can pass in an Anonymous object, an ExpandoObject,
/// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString
/// </summary>
public virtual int Update(object o, object key) {
var ex = o.ToExpando();
if (!IsValid(ex)) {
throw new InvalidOperationException("Can't Update: " + String.Join("; ", Errors.ToArray()));
}
var result = 0;
if (BeforeSave(ex)) {
result = Execute(CreateUpdateCommand(ex, key));
Updated(ex);
}
return result;
}
/// <summary>
/// Removes one or more records from the DB according to the passed-in WHERE
/// </summary>
public int Delete(object key = null, string where = "", params object[] args) {
var deleted = this.Single(key);
var result = 0;
if (BeforeDelete(deleted)) {
result = Execute(CreateDeleteCommand(where: where, key: key, args: args));
Deleted(deleted);
}
return result;
}
public void DefaultTo(string key, object value, dynamic item) {
if (!ItemContainsKey(key, item)) {
var dc = (IDictionary<string, object>)item;
dc[key] = value;
}
}
//Hooks
public virtual void Validate(dynamic item) { }
public virtual void Inserted(dynamic item) { }
public virtual void Updated(dynamic item) { }
public virtual void Deleted(dynamic item) { }
public virtual bool BeforeDelete(dynamic item) { return true; }
public virtual bool BeforeSave(dynamic item) { return true; }
//validation methods
public virtual void ValidatesPresenceOf(object value, string message = "Required") {
if (value == null)
Errors.Add(message);
if (String.IsNullOrEmpty(value.ToString()))
Errors.Add(message);
}
//fun methods
public virtual void ValidatesNumericalityOf(object value, string message = "Should be a number") {
var type = value.GetType().Name;
var numerics = new string[] { "Int32", "Int16", "Int64", "Decimal", "Double", "Single", "Float" };
if (!numerics.Contains(type)) {
Errors.Add(message);
}
}
public virtual void ValidateIsCurrency(object value, string message = "Should be money") {
if (value == null)
Errors.Add(message);
decimal val = decimal.MinValue;
decimal.TryParse(value.ToString(), out val);
if (val == decimal.MinValue)
Errors.Add(message);
}
public int Count() {
return Count(TableName);
}
public int Count(string tableName, string where="") {
return (int)Scalar("SELECT COUNT(*) FROM " + tableName+" "+where);
}
/// <summary>
/// A helpful query tool
/// </summary>
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {
//parse the method
var constraints = new List<string>();
var counter = 0;
var info = binder.CallInfo;
// accepting named args only... SKEET!
if (info.ArgumentNames.Count != args.Length) {
throw new InvalidOperationException("Please use named arguments for this type of query - the column name, orderby, columns, etc");
}
//first should be "FindBy, Last, Single, First"
var op = binder.Name;
var columns = " * ";
string orderBy = string.Format(" ORDER BY {0}", PrimaryKeyField);
string sql = "";
string where = "";
var whereArgs = new List<object>();
//loop the named args - see if we have order, columns and constraints
if (info.ArgumentNames.Count > 0) {
for (int i = 0; i < args.Length; i++) {
var name = info.ArgumentNames[i].ToLower();
switch (name) {
case "orderby":
orderBy = " ORDER BY " + args[i];
break;
case "columns":
columns = args[i].ToString();
break;
default:
constraints.Add(string.Format(" {0} = :{1}", name, counter));
whereArgs.Add(args[i]);
counter++;
break;
}
}
}
//Build the WHERE bits
if (constraints.Count > 0) {
where = " WHERE " + string.Join(" AND ", constraints.ToArray());
}
//probably a bit much here but... yeah this whole thing needs to be refactored...
if (op.ToLower() == "count") {
result = Scalar("SELECT COUNT(*) FROM " + TableName + where, whereArgs.ToArray());
} else if (op.ToLower() == "sum") {
result = Scalar("SELECT SUM(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
} else if (op.ToLower() == "max") {
result = Scalar("SELECT MAX(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
} else if (op.ToLower() == "min") {
result = Scalar("SELECT MIN(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
} else if (op.ToLower() == "avg") {
result = Scalar("SELECT AVG(" + columns + ") FROM " + TableName + where, whereArgs.ToArray());
} else {
//build the SQL
var justOne = op.StartsWith("First") || op.StartsWith("Last") || op.StartsWith("Get") || op.StartsWith("Single");
//Be sure to sort by DESC on the PK (PK Sort is the default)
if (op.StartsWith("Last")) {
sql = "SELECT " + columns + " FROM " + TableName + where + (string.IsNullOrEmpty(where) ? "" : " AND ") + " ROWNUM=1 ";
orderBy = orderBy + " DESC ";
} else {
//default to multiple
sql = "SELECT " + columns + " FROM " + TableName + where;
}
if (justOne) {
//return a single record
result = Query(sql + orderBy, whereArgs.ToArray()).FirstOrDefault();
} else {
//return lots
result = Query(sql + orderBy, whereArgs.ToArray());
}
}
return true;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// VirtualNetworkGatewaysOperations operations.
/// </summary>
public partial interface IVirtualNetworkGatewaysOperations
{
/// <summary>
/// Creates or updates a virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update virtual network gateway
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified virtual network gateway by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual network gateways by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the connections in a virtual network gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnectionListEntity>>> ListConnectionsWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Resets the primary of the virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='gatewayVip'>
/// Virtual network gateway vip address supplied to the begin reset of
/// the active-active feature enabled gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> ResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generates VPN client package for P2S client of the virtual network
/// gateway in the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN
/// client package operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> GeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generates VPN profile for P2S client of the virtual network gateway
/// in the specified resource group. Used for IKEV2 and radius based
/// authentication.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN
/// client package operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> GenerateVpnProfileWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets pre-generated VPN profile for P2S client of the virtual
/// network gateway in the specified resource group. The profile needs
/// to be generated first using generateVpnProfile.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> GetVpnProfilePacakgeUrlWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The GetBgpPeerStatus operation retrieves the status of all BGP
/// peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer to retrieve the status of.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<BgpPeerStatusListResult>> GetBgpPeerStatusWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway has learned, including routes learned from BGP peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<GatewayRouteListResult>> GetLearnedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway is advertising to the specified peer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<GatewayRouteListResult>> GetAdvertisedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update virtual network gateway
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified virtual network gateway.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Resets the primary of the virtual network gateway in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='gatewayVip'>
/// Virtual network gateway vip address supplied to the begin reset of
/// the active-active feature enabled gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<VirtualNetworkGateway>> BeginResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string gatewayVip = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generates VPN client package for P2S client of the virtual network
/// gateway in the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN
/// client package operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> BeginGeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Generates VPN profile for P2S client of the virtual network gateway
/// in the specified resource group. Used for IKEV2 and radius based
/// authentication.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the generate virtual network gateway VPN
/// client package operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> BeginGenerateVpnProfileWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets pre-generated VPN profile for P2S client of the virtual
/// network gateway in the specified resource group. The profile needs
/// to be generated first using generateVpnProfile.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<string>> BeginGetVpnProfilePacakgeUrlWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The GetBgpPeerStatus operation retrieves the status of all BGP
/// peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer to retrieve the status of.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<BgpPeerStatusListResult>> BeginGetBgpPeerStatusWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway has learned, including routes learned from BGP peers.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<GatewayRouteListResult>> BeginGetLearnedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// This operation retrieves a list of routes the virtual network
/// gateway is advertising to the specified peer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkGatewayName'>
/// The name of the virtual network gateway.
/// </param>
/// <param name='peer'>
/// The IP address of the peer
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<GatewayRouteListResult>> BeginGetAdvertisedRoutesWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, string peer, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all virtual network gateways by resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the connections in a virtual network gateway.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnectionListEntity>>> ListConnectionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Spanner.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Spanner.Common.V1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using gcsv = Google.Cloud.Spanner.V1;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedSpannerClientSnippets
{
/// <summary>Snippet for CreateSession</summary>
public void CreateSessionRequestObject()
{
// Snippet: CreateSession(CreateSessionRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
CreateSessionRequest request = new CreateSessionRequest
{
DatabaseAsDatabaseName = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"),
Session = new Session(),
};
// Make the request
Session response = spannerClient.CreateSession(request);
// End snippet
}
/// <summary>Snippet for CreateSessionAsync</summary>
public async Task CreateSessionRequestObjectAsync()
{
// Snippet: CreateSessionAsync(CreateSessionRequest, CallSettings)
// Additional: CreateSessionAsync(CreateSessionRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
CreateSessionRequest request = new CreateSessionRequest
{
DatabaseAsDatabaseName = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"),
Session = new Session(),
};
// Make the request
Session response = await spannerClient.CreateSessionAsync(request);
// End snippet
}
/// <summary>Snippet for CreateSession</summary>
public void CreateSession()
{
// Snippet: CreateSession(string, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
string database = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]";
// Make the request
Session response = spannerClient.CreateSession(database);
// End snippet
}
/// <summary>Snippet for CreateSessionAsync</summary>
public async Task CreateSessionAsync()
{
// Snippet: CreateSessionAsync(string, CallSettings)
// Additional: CreateSessionAsync(string, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
string database = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]";
// Make the request
Session response = await spannerClient.CreateSessionAsync(database);
// End snippet
}
/// <summary>Snippet for CreateSession</summary>
public void CreateSessionResourceNames()
{
// Snippet: CreateSession(DatabaseName, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
DatabaseName database = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]");
// Make the request
Session response = spannerClient.CreateSession(database);
// End snippet
}
/// <summary>Snippet for CreateSessionAsync</summary>
public async Task CreateSessionResourceNamesAsync()
{
// Snippet: CreateSessionAsync(DatabaseName, CallSettings)
// Additional: CreateSessionAsync(DatabaseName, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
DatabaseName database = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]");
// Make the request
Session response = await spannerClient.CreateSessionAsync(database);
// End snippet
}
/// <summary>Snippet for BatchCreateSessions</summary>
public void BatchCreateSessionsRequestObject()
{
// Snippet: BatchCreateSessions(BatchCreateSessionsRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
BatchCreateSessionsRequest request = new BatchCreateSessionsRequest
{
DatabaseAsDatabaseName = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"),
SessionTemplate = new Session(),
SessionCount = 0,
};
// Make the request
BatchCreateSessionsResponse response = spannerClient.BatchCreateSessions(request);
// End snippet
}
/// <summary>Snippet for BatchCreateSessionsAsync</summary>
public async Task BatchCreateSessionsRequestObjectAsync()
{
// Snippet: BatchCreateSessionsAsync(BatchCreateSessionsRequest, CallSettings)
// Additional: BatchCreateSessionsAsync(BatchCreateSessionsRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
BatchCreateSessionsRequest request = new BatchCreateSessionsRequest
{
DatabaseAsDatabaseName = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"),
SessionTemplate = new Session(),
SessionCount = 0,
};
// Make the request
BatchCreateSessionsResponse response = await spannerClient.BatchCreateSessionsAsync(request);
// End snippet
}
/// <summary>Snippet for BatchCreateSessions</summary>
public void BatchCreateSessions()
{
// Snippet: BatchCreateSessions(string, int, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
string database = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]";
int sessionCount = 0;
// Make the request
BatchCreateSessionsResponse response = spannerClient.BatchCreateSessions(database, sessionCount);
// End snippet
}
/// <summary>Snippet for BatchCreateSessionsAsync</summary>
public async Task BatchCreateSessionsAsync()
{
// Snippet: BatchCreateSessionsAsync(string, int, CallSettings)
// Additional: BatchCreateSessionsAsync(string, int, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
string database = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]";
int sessionCount = 0;
// Make the request
BatchCreateSessionsResponse response = await spannerClient.BatchCreateSessionsAsync(database, sessionCount);
// End snippet
}
/// <summary>Snippet for BatchCreateSessions</summary>
public void BatchCreateSessionsResourceNames()
{
// Snippet: BatchCreateSessions(DatabaseName, int, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
DatabaseName database = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]");
int sessionCount = 0;
// Make the request
BatchCreateSessionsResponse response = spannerClient.BatchCreateSessions(database, sessionCount);
// End snippet
}
/// <summary>Snippet for BatchCreateSessionsAsync</summary>
public async Task BatchCreateSessionsResourceNamesAsync()
{
// Snippet: BatchCreateSessionsAsync(DatabaseName, int, CallSettings)
// Additional: BatchCreateSessionsAsync(DatabaseName, int, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
DatabaseName database = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]");
int sessionCount = 0;
// Make the request
BatchCreateSessionsResponse response = await spannerClient.BatchCreateSessionsAsync(database, sessionCount);
// End snippet
}
/// <summary>Snippet for GetSession</summary>
public void GetSessionRequestObject()
{
// Snippet: GetSession(GetSessionRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
GetSessionRequest request = new GetSessionRequest
{
SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
};
// Make the request
Session response = spannerClient.GetSession(request);
// End snippet
}
/// <summary>Snippet for GetSessionAsync</summary>
public async Task GetSessionRequestObjectAsync()
{
// Snippet: GetSessionAsync(GetSessionRequest, CallSettings)
// Additional: GetSessionAsync(GetSessionRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
GetSessionRequest request = new GetSessionRequest
{
SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
};
// Make the request
Session response = await spannerClient.GetSessionAsync(request);
// End snippet
}
/// <summary>Snippet for GetSession</summary>
public void GetSession()
{
// Snippet: GetSession(string, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
// Make the request
Session response = spannerClient.GetSession(name);
// End snippet
}
/// <summary>Snippet for GetSessionAsync</summary>
public async Task GetSessionAsync()
{
// Snippet: GetSessionAsync(string, CallSettings)
// Additional: GetSessionAsync(string, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
// Make the request
Session response = await spannerClient.GetSessionAsync(name);
// End snippet
}
/// <summary>Snippet for GetSession</summary>
public void GetSessionResourceNames()
{
// Snippet: GetSession(SessionName, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName name = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
// Make the request
Session response = spannerClient.GetSession(name);
// End snippet
}
/// <summary>Snippet for GetSessionAsync</summary>
public async Task GetSessionResourceNamesAsync()
{
// Snippet: GetSessionAsync(SessionName, CallSettings)
// Additional: GetSessionAsync(SessionName, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName name = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
// Make the request
Session response = await spannerClient.GetSessionAsync(name);
// End snippet
}
/// <summary>Snippet for ListSessions</summary>
public void ListSessionsRequestObject()
{
// Snippet: ListSessions(ListSessionsRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
ListSessionsRequest request = new ListSessionsRequest
{
DatabaseAsDatabaseName = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"),
Filter = "",
};
// Make the request
PagedEnumerable<ListSessionsResponse, Session> response = spannerClient.ListSessions(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Session item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListSessionsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Session item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Session> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Session item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSessionsAsync</summary>
public async Task ListSessionsRequestObjectAsync()
{
// Snippet: ListSessionsAsync(ListSessionsRequest, CallSettings)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
ListSessionsRequest request = new ListSessionsRequest
{
DatabaseAsDatabaseName = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]"),
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListSessionsResponse, Session> response = spannerClient.ListSessionsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Session item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListSessionsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Session item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Session> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Session item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSessions</summary>
public void ListSessions()
{
// Snippet: ListSessions(string, string, int?, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
string database = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]";
// Make the request
PagedEnumerable<ListSessionsResponse, Session> response = spannerClient.ListSessions(database);
// Iterate over all response items, lazily performing RPCs as required
foreach (Session item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListSessionsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Session item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Session> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Session item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSessionsAsync</summary>
public async Task ListSessionsAsync()
{
// Snippet: ListSessionsAsync(string, string, int?, CallSettings)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
string database = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]";
// Make the request
PagedAsyncEnumerable<ListSessionsResponse, Session> response = spannerClient.ListSessionsAsync(database);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Session item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListSessionsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Session item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Session> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Session item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSessions</summary>
public void ListSessionsResourceNames()
{
// Snippet: ListSessions(DatabaseName, string, int?, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
DatabaseName database = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]");
// Make the request
PagedEnumerable<ListSessionsResponse, Session> response = spannerClient.ListSessions(database);
// Iterate over all response items, lazily performing RPCs as required
foreach (Session item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListSessionsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Session item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Session> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Session item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListSessionsAsync</summary>
public async Task ListSessionsResourceNamesAsync()
{
// Snippet: ListSessionsAsync(DatabaseName, string, int?, CallSettings)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
DatabaseName database = DatabaseName.FromProjectInstanceDatabase("[PROJECT]", "[INSTANCE]", "[DATABASE]");
// Make the request
PagedAsyncEnumerable<ListSessionsResponse, Session> response = spannerClient.ListSessionsAsync(database);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Session item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListSessionsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Session item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Session> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Session item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for DeleteSession</summary>
public void DeleteSessionRequestObject()
{
// Snippet: DeleteSession(DeleteSessionRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
DeleteSessionRequest request = new DeleteSessionRequest
{
SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
};
// Make the request
spannerClient.DeleteSession(request);
// End snippet
}
/// <summary>Snippet for DeleteSessionAsync</summary>
public async Task DeleteSessionRequestObjectAsync()
{
// Snippet: DeleteSessionAsync(DeleteSessionRequest, CallSettings)
// Additional: DeleteSessionAsync(DeleteSessionRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
DeleteSessionRequest request = new DeleteSessionRequest
{
SessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
};
// Make the request
await spannerClient.DeleteSessionAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteSession</summary>
public void DeleteSession()
{
// Snippet: DeleteSession(string, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
// Make the request
spannerClient.DeleteSession(name);
// End snippet
}
/// <summary>Snippet for DeleteSessionAsync</summary>
public async Task DeleteSessionAsync()
{
// Snippet: DeleteSessionAsync(string, CallSettings)
// Additional: DeleteSessionAsync(string, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
// Make the request
await spannerClient.DeleteSessionAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteSession</summary>
public void DeleteSessionResourceNames()
{
// Snippet: DeleteSession(SessionName, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName name = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
// Make the request
spannerClient.DeleteSession(name);
// End snippet
}
/// <summary>Snippet for DeleteSessionAsync</summary>
public async Task DeleteSessionResourceNamesAsync()
{
// Snippet: DeleteSessionAsync(SessionName, CallSettings)
// Additional: DeleteSessionAsync(SessionName, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName name = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
// Make the request
await spannerClient.DeleteSessionAsync(name);
// End snippet
}
/// <summary>Snippet for ExecuteSql</summary>
public void ExecuteSqlRequestObject()
{
// Snippet: ExecuteSql(ExecuteSqlRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
ExecuteSqlRequest request = new ExecuteSqlRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Sql = "",
Params = new Struct(),
ParamTypes =
{
{
"",
new gcsv::Type()
},
},
ResumeToken = ByteString.Empty,
QueryMode = ExecuteSqlRequest.Types.QueryMode.Normal,
PartitionToken = ByteString.Empty,
Seqno = 0L,
QueryOptions = new ExecuteSqlRequest.Types.QueryOptions(),
RequestOptions = new RequestOptions(),
};
// Make the request
ResultSet response = spannerClient.ExecuteSql(request);
// End snippet
}
/// <summary>Snippet for ExecuteSqlAsync</summary>
public async Task ExecuteSqlRequestObjectAsync()
{
// Snippet: ExecuteSqlAsync(ExecuteSqlRequest, CallSettings)
// Additional: ExecuteSqlAsync(ExecuteSqlRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
ExecuteSqlRequest request = new ExecuteSqlRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Sql = "",
Params = new Struct(),
ParamTypes =
{
{
"",
new gcsv::Type()
},
},
ResumeToken = ByteString.Empty,
QueryMode = ExecuteSqlRequest.Types.QueryMode.Normal,
PartitionToken = ByteString.Empty,
Seqno = 0L,
QueryOptions = new ExecuteSqlRequest.Types.QueryOptions(),
RequestOptions = new RequestOptions(),
};
// Make the request
ResultSet response = await spannerClient.ExecuteSqlAsync(request);
// End snippet
}
/// <summary>Snippet for ExecuteStreamingSql</summary>
public async Task ExecuteStreamingSqlRequestObject()
{
// Snippet: ExecuteStreamingSql(ExecuteSqlRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
ExecuteSqlRequest request = new ExecuteSqlRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Sql = "",
Params = new Struct(),
ParamTypes =
{
{
"",
new gcsv::Type()
},
},
ResumeToken = ByteString.Empty,
QueryMode = ExecuteSqlRequest.Types.QueryMode.Normal,
PartitionToken = ByteString.Empty,
Seqno = 0L,
QueryOptions = new ExecuteSqlRequest.Types.QueryOptions(),
RequestOptions = new RequestOptions(),
};
// Make the request, returning a streaming response
SpannerClient.ExecuteStreamingSqlStream response = spannerClient.ExecuteStreamingSql(request);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<PartialResultSet> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
PartialResultSet responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for ExecuteBatchDml</summary>
public void ExecuteBatchDmlRequestObject()
{
// Snippet: ExecuteBatchDml(ExecuteBatchDmlRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
ExecuteBatchDmlRequest request = new ExecuteBatchDmlRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Statements =
{
new ExecuteBatchDmlRequest.Types.Statement(),
},
Seqno = 0L,
RequestOptions = new RequestOptions(),
};
// Make the request
ExecuteBatchDmlResponse response = spannerClient.ExecuteBatchDml(request);
// End snippet
}
/// <summary>Snippet for ExecuteBatchDmlAsync</summary>
public async Task ExecuteBatchDmlRequestObjectAsync()
{
// Snippet: ExecuteBatchDmlAsync(ExecuteBatchDmlRequest, CallSettings)
// Additional: ExecuteBatchDmlAsync(ExecuteBatchDmlRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
ExecuteBatchDmlRequest request = new ExecuteBatchDmlRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Statements =
{
new ExecuteBatchDmlRequest.Types.Statement(),
},
Seqno = 0L,
RequestOptions = new RequestOptions(),
};
// Make the request
ExecuteBatchDmlResponse response = await spannerClient.ExecuteBatchDmlAsync(request);
// End snippet
}
/// <summary>Snippet for Read</summary>
public void ReadRequestObject()
{
// Snippet: Read(ReadRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
ReadRequest request = new ReadRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Table = "",
Index = "",
Columns = { "", },
KeySet = new KeySet(),
Limit = 0L,
ResumeToken = ByteString.Empty,
PartitionToken = ByteString.Empty,
RequestOptions = new RequestOptions(),
};
// Make the request
ResultSet response = spannerClient.Read(request);
// End snippet
}
/// <summary>Snippet for ReadAsync</summary>
public async Task ReadRequestObjectAsync()
{
// Snippet: ReadAsync(ReadRequest, CallSettings)
// Additional: ReadAsync(ReadRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
ReadRequest request = new ReadRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Table = "",
Index = "",
Columns = { "", },
KeySet = new KeySet(),
Limit = 0L,
ResumeToken = ByteString.Empty,
PartitionToken = ByteString.Empty,
RequestOptions = new RequestOptions(),
};
// Make the request
ResultSet response = await spannerClient.ReadAsync(request);
// End snippet
}
/// <summary>Snippet for StreamingRead</summary>
public async Task StreamingReadRequestObject()
{
// Snippet: StreamingRead(ReadRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
ReadRequest request = new ReadRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Table = "",
Index = "",
Columns = { "", },
KeySet = new KeySet(),
Limit = 0L,
ResumeToken = ByteString.Empty,
PartitionToken = ByteString.Empty,
RequestOptions = new RequestOptions(),
};
// Make the request, returning a streaming response
SpannerClient.StreamingReadStream response = spannerClient.StreamingRead(request);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<PartialResultSet> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
PartialResultSet responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for BeginTransaction</summary>
public void BeginTransactionRequestObject()
{
// Snippet: BeginTransaction(BeginTransactionRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
BeginTransactionRequest request = new BeginTransactionRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Options = new TransactionOptions(),
RequestOptions = new RequestOptions(),
};
// Make the request
Transaction response = spannerClient.BeginTransaction(request);
// End snippet
}
/// <summary>Snippet for BeginTransactionAsync</summary>
public async Task BeginTransactionRequestObjectAsync()
{
// Snippet: BeginTransactionAsync(BeginTransactionRequest, CallSettings)
// Additional: BeginTransactionAsync(BeginTransactionRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
BeginTransactionRequest request = new BeginTransactionRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Options = new TransactionOptions(),
RequestOptions = new RequestOptions(),
};
// Make the request
Transaction response = await spannerClient.BeginTransactionAsync(request);
// End snippet
}
/// <summary>Snippet for BeginTransaction</summary>
public void BeginTransaction()
{
// Snippet: BeginTransaction(string, TransactionOptions, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
string session = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
TransactionOptions options = new TransactionOptions();
// Make the request
Transaction response = spannerClient.BeginTransaction(session, options);
// End snippet
}
/// <summary>Snippet for BeginTransactionAsync</summary>
public async Task BeginTransactionAsync()
{
// Snippet: BeginTransactionAsync(string, TransactionOptions, CallSettings)
// Additional: BeginTransactionAsync(string, TransactionOptions, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
string session = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
TransactionOptions options = new TransactionOptions();
// Make the request
Transaction response = await spannerClient.BeginTransactionAsync(session, options);
// End snippet
}
/// <summary>Snippet for BeginTransaction</summary>
public void BeginTransactionResourceNames()
{
// Snippet: BeginTransaction(SessionName, TransactionOptions, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName session = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions options = new TransactionOptions();
// Make the request
Transaction response = spannerClient.BeginTransaction(session, options);
// End snippet
}
/// <summary>Snippet for BeginTransactionAsync</summary>
public async Task BeginTransactionResourceNamesAsync()
{
// Snippet: BeginTransactionAsync(SessionName, TransactionOptions, CallSettings)
// Additional: BeginTransactionAsync(SessionName, TransactionOptions, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName session = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions options = new TransactionOptions();
// Make the request
Transaction response = await spannerClient.BeginTransactionAsync(session, options);
// End snippet
}
/// <summary>Snippet for Commit</summary>
public void CommitRequestObject()
{
// Snippet: Commit(CommitRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
CommitRequest request = new CommitRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
TransactionId = ByteString.Empty,
Mutations = { new Mutation(), },
ReturnCommitStats = false,
RequestOptions = new RequestOptions(),
};
// Make the request
CommitResponse response = spannerClient.Commit(request);
// End snippet
}
/// <summary>Snippet for CommitAsync</summary>
public async Task CommitRequestObjectAsync()
{
// Snippet: CommitAsync(CommitRequest, CallSettings)
// Additional: CommitAsync(CommitRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
CommitRequest request = new CommitRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
TransactionId = ByteString.Empty,
Mutations = { new Mutation(), },
ReturnCommitStats = false,
RequestOptions = new RequestOptions(),
};
// Make the request
CommitResponse response = await spannerClient.CommitAsync(request);
// End snippet
}
/// <summary>Snippet for Commit</summary>
public void Commit1()
{
// Snippet: Commit(string, ByteString, IEnumerable<Mutation>, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
string session = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
ByteString transactionId = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = spannerClient.Commit(session, transactionId, mutations);
// End snippet
}
/// <summary>Snippet for CommitAsync</summary>
public async Task Commit1Async()
{
// Snippet: CommitAsync(string, ByteString, IEnumerable<Mutation>, CallSettings)
// Additional: CommitAsync(string, ByteString, IEnumerable<Mutation>, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
string session = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
ByteString transactionId = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = await spannerClient.CommitAsync(session, transactionId, mutations);
// End snippet
}
/// <summary>Snippet for Commit</summary>
public void Commit1ResourceNames()
{
// Snippet: Commit(SessionName, ByteString, IEnumerable<Mutation>, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName session = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = spannerClient.Commit(session, transactionId, mutations);
// End snippet
}
/// <summary>Snippet for CommitAsync</summary>
public async Task Commit1ResourceNamesAsync()
{
// Snippet: CommitAsync(SessionName, ByteString, IEnumerable<Mutation>, CallSettings)
// Additional: CommitAsync(SessionName, ByteString, IEnumerable<Mutation>, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName session = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.Empty;
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = await spannerClient.CommitAsync(session, transactionId, mutations);
// End snippet
}
/// <summary>Snippet for Commit</summary>
public void Commit2()
{
// Snippet: Commit(string, TransactionOptions, IEnumerable<Mutation>, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
string session = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
TransactionOptions singleUseTransaction = new TransactionOptions();
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = spannerClient.Commit(session, singleUseTransaction, mutations);
// End snippet
}
/// <summary>Snippet for CommitAsync</summary>
public async Task Commit2Async()
{
// Snippet: CommitAsync(string, TransactionOptions, IEnumerable<Mutation>, CallSettings)
// Additional: CommitAsync(string, TransactionOptions, IEnumerable<Mutation>, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
string session = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
TransactionOptions singleUseTransaction = new TransactionOptions();
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = await spannerClient.CommitAsync(session, singleUseTransaction, mutations);
// End snippet
}
/// <summary>Snippet for Commit</summary>
public void Commit2ResourceNames()
{
// Snippet: Commit(SessionName, TransactionOptions, IEnumerable<Mutation>, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName session = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions singleUseTransaction = new TransactionOptions();
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = spannerClient.Commit(session, singleUseTransaction, mutations);
// End snippet
}
/// <summary>Snippet for CommitAsync</summary>
public async Task Commit2ResourceNamesAsync()
{
// Snippet: CommitAsync(SessionName, TransactionOptions, IEnumerable<Mutation>, CallSettings)
// Additional: CommitAsync(SessionName, TransactionOptions, IEnumerable<Mutation>, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName session = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions singleUseTransaction = new TransactionOptions();
IEnumerable<Mutation> mutations = new Mutation[] { new Mutation(), };
// Make the request
CommitResponse response = await spannerClient.CommitAsync(session, singleUseTransaction, mutations);
// End snippet
}
/// <summary>Snippet for Rollback</summary>
public void RollbackRequestObject()
{
// Snippet: Rollback(RollbackRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
RollbackRequest request = new RollbackRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
TransactionId = ByteString.Empty,
};
// Make the request
spannerClient.Rollback(request);
// End snippet
}
/// <summary>Snippet for RollbackAsync</summary>
public async Task RollbackRequestObjectAsync()
{
// Snippet: RollbackAsync(RollbackRequest, CallSettings)
// Additional: RollbackAsync(RollbackRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
RollbackRequest request = new RollbackRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
TransactionId = ByteString.Empty,
};
// Make the request
await spannerClient.RollbackAsync(request);
// End snippet
}
/// <summary>Snippet for Rollback</summary>
public void Rollback()
{
// Snippet: Rollback(string, ByteString, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
string session = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
ByteString transactionId = ByteString.Empty;
// Make the request
spannerClient.Rollback(session, transactionId);
// End snippet
}
/// <summary>Snippet for RollbackAsync</summary>
public async Task RollbackAsync()
{
// Snippet: RollbackAsync(string, ByteString, CallSettings)
// Additional: RollbackAsync(string, ByteString, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
string session = "projects/[PROJECT]/instances/[INSTANCE]/databases/[DATABASE]/sessions/[SESSION]";
ByteString transactionId = ByteString.Empty;
// Make the request
await spannerClient.RollbackAsync(session, transactionId);
// End snippet
}
/// <summary>Snippet for Rollback</summary>
public void RollbackResourceNames()
{
// Snippet: Rollback(SessionName, ByteString, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName session = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.Empty;
// Make the request
spannerClient.Rollback(session, transactionId);
// End snippet
}
/// <summary>Snippet for RollbackAsync</summary>
public async Task RollbackResourceNamesAsync()
{
// Snippet: RollbackAsync(SessionName, ByteString, CallSettings)
// Additional: RollbackAsync(SessionName, ByteString, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName session = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.Empty;
// Make the request
await spannerClient.RollbackAsync(session, transactionId);
// End snippet
}
/// <summary>Snippet for PartitionQuery</summary>
public void PartitionQueryRequestObject()
{
// Snippet: PartitionQuery(PartitionQueryRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
PartitionQueryRequest request = new PartitionQueryRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Sql = "",
Params = new Struct(),
ParamTypes =
{
{
"",
new gcsv::Type()
},
},
PartitionOptions = new PartitionOptions(),
};
// Make the request
PartitionResponse response = spannerClient.PartitionQuery(request);
// End snippet
}
/// <summary>Snippet for PartitionQueryAsync</summary>
public async Task PartitionQueryRequestObjectAsync()
{
// Snippet: PartitionQueryAsync(PartitionQueryRequest, CallSettings)
// Additional: PartitionQueryAsync(PartitionQueryRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
PartitionQueryRequest request = new PartitionQueryRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Sql = "",
Params = new Struct(),
ParamTypes =
{
{
"",
new gcsv::Type()
},
},
PartitionOptions = new PartitionOptions(),
};
// Make the request
PartitionResponse response = await spannerClient.PartitionQueryAsync(request);
// End snippet
}
/// <summary>Snippet for PartitionRead</summary>
public void PartitionReadRequestObject()
{
// Snippet: PartitionRead(PartitionReadRequest, CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
PartitionReadRequest request = new PartitionReadRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Table = "",
Index = "",
Columns = { "", },
KeySet = new KeySet(),
PartitionOptions = new PartitionOptions(),
};
// Make the request
PartitionResponse response = spannerClient.PartitionRead(request);
// End snippet
}
/// <summary>Snippet for PartitionReadAsync</summary>
public async Task PartitionReadRequestObjectAsync()
{
// Snippet: PartitionReadAsync(PartitionReadRequest, CallSettings)
// Additional: PartitionReadAsync(PartitionReadRequest, CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
PartitionReadRequest request = new PartitionReadRequest
{
SessionAsSessionName = SessionName.FromProjectInstanceDatabaseSession("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Transaction = new TransactionSelector(),
Table = "",
Index = "",
Columns = { "", },
KeySet = new KeySet(),
PartitionOptions = new PartitionOptions(),
};
// Make the request
PartitionResponse response = await spannerClient.PartitionReadAsync(request);
// End snippet
}
}
}
| |
// 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.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections;
namespace System.Transactions
{
internal enum EnlistmentType
{
Volatile = 0,
Durable = 1,
PromotableSinglePhase = 2
}
internal enum NotificationCall
{
// IEnlistmentNotification
Prepare = 0,
Commit = 1,
Rollback = 2,
InDoubt = 3,
// ISinglePhaseNotification
SinglePhaseCommit = 4,
// IPromotableSinglePhaseNotification
Promote = 5
}
internal enum TransactionScopeResult
{
CreatedTransaction = 0,
UsingExistingCurrent = 1,
TransactionPassed = 2,
DependentTransactionPassed = 3,
NoTransaction = 4
}
internal enum TransactionExceptionType
{
InvalidOperationException = 0,
TransactionAbortedException = 1,
TransactionException = 2,
TransactionInDoubtException = 3,
TransactionManagerCommunicationException = 4,
UnrecognizedRecoveryInformation = 5
}
internal enum TraceSourceType
{
TraceSourceBase = 0,
TraceSourceLtm = 1,
TraceSourceDistributed = 2
}
/// <summary>Provides an event source for tracing Transactions information.</summary>
[EventSource(
Name = "System.Transactions.TransactionsEventSource",
Guid = "8ac2d80a-1f1a-431b-ace4-bff8824aef0b",
LocalizationResources = "FxResources.System.Transactions.Local.SR")]
internal sealed class TransactionsEtwProvider : EventSource
{
/// <summary>
/// Defines the singleton instance for the Transactions ETW provider.
/// The Transactions provider GUID is {8ac2d80a-1f1a-431b-ace4-bff8824aef0b}.
/// </summary>
///
internal static readonly TransactionsEtwProvider Log = new TransactionsEtwProvider();
/// <summary>Prevent external instantiation. All logging should go through the Log instance.</summary>
private TransactionsEtwProvider() { }
/// <summary>Enabled for all keywords.</summary>
private const EventKeywords ALL_KEYWORDS = (EventKeywords)(-1);
//-----------------------------------------------------------------------------------
//
// Transactions Event IDs (must be unique)
//
/// <summary>The event ID for configured default timeout adjusted event.</summary>
private const int CONFIGURED_DEFAULT_TIMEOUT_ADJUSTED_EVENTID = 1;
/// <summary>The event ID for the enlistment abort event.</summary>
private const int ENLISTMENT_ABORTED_EVENTID = 2;
/// <summary>The event ID for the enlistment commit event.</summary>
private const int ENLISTMENT_COMMITTED_EVENTID = 3;
/// <summary>The event ID for the enlistment done event.</summary>
private const int ENLISTMENT_DONE_EVENTID = 4;
/// <summary>The event ID for the enlistment status.</summary>
private const int ENLISTMENT_EVENTID = 5;
/// <summary>The event ID for the enlistment forcerollback event.</summary>
private const int ENLISTMENT_FORCEROLLBACK_EVENTID = 6;
/// <summary>The event ID for the enlistment indoubt event.</summary>
private const int ENLISTMENT_INDOUBT_EVENTID = 7;
/// <summary>The event ID for the enlistment prepared event.</summary>
private const int ENLISTMENT_PREPARED_EVENTID = 8;
/// <summary>The event ID for exception consumed event.</summary>
private const int EXCEPTION_CONSUMED_BASE_EVENTID = 9;
/// <summary>The event ID for exception consumed event.</summary>
private const int EXCEPTION_CONSUMED_LTM_EVENTID = 10;
/// <summary>The event ID for method enter event.</summary>
private const int METHOD_ENTER_LTM_EVENTID = 11;
/// <summary>The event ID for method exit event.</summary>
private const int METHOD_EXIT_LTM_EVENTID = 12;
/// <summary>The event ID for method enter event.</summary>
private const int METHOD_ENTER_BASE_EVENTID = 13;
/// <summary>The event ID for method exit event.</summary>
private const int METHOD_EXIT_BASE_EVENTID = 14;
/// <summary>The event ID for method enter event.</summary>
private const int METHOD_ENTER_DISTRIBUTED_EVENTID = 15;
/// <summary>The event ID for method exit event.</summary>
private const int METHOD_EXIT_DISTRIBUTED_EVENTID = 16;
/// <summary>The event ID for transaction aborted event.</summary>
private const int TRANSACTION_ABORTED_EVENTID = 17;
/// <summary>The event ID for the transaction clone create event.</summary>
private const int TRANSACTION_CLONECREATE_EVENTID = 18;
/// <summary>The event ID for the transaction commit event.</summary>
private const int TRANSACTION_COMMIT_EVENTID = 19;
/// <summary>The event ID for transaction committed event.</summary>
private const int TRANSACTION_COMMITTED_EVENTID = 20;
/// <summary>The event ID for when we encounter a new Transactions object that hasn't had its name traced to the trace file.</summary>
private const int TRANSACTION_CREATED_EVENTID = 21;
/// <summary>The event ID for the transaction dependent clone complete event.</summary>
private const int TRANSACTION_DEPENDENT_CLONE_COMPLETE_EVENTID = 22;
/// <summary>The event ID for the transaction exception event.</summary>
private const int TRANSACTION_EXCEPTION_LTM_EVENTID = 23;
/// <summary>The event ID for the transaction exception event.</summary>
private const int TRANSACTION_EXCEPTION_BASE_EVENTID = 24;
/// <summary>The event ID for transaction indoubt event.</summary>
private const int TRANSACTION_INDOUBT_EVENTID = 25;
/// <summary>The event ID for the transaction invalid operation event.</summary>
private const int TRANSACTION_INVALID_OPERATION_EVENTID = 26;
/// <summary>The event ID for transaction promoted event.</summary>
private const int TRANSACTION_PROMOTED_EVENTID = 27;
/// <summary>The event ID for the transaction rollback event.</summary>
private const int TRANSACTION_ROLLBACK_EVENTID = 28;
/// <summary>The event ID for the transaction serialized event.</summary>
private const int TRANSACTION_SERIALIZED_EVENTID = 29;
/// <summary>The event ID for transaction timeout event.</summary>
private const int TRANSACTION_TIMEOUT_EVENTID = 30;
/// <summary>The event ID for transactionmanager recovery complete event.</summary>
private const int TRANSACTIONMANAGER_RECOVERY_COMPLETE_EVENTID = 31;
/// <summary>The event ID for transactionmanager reenlist event.</summary>
private const int TRANSACTIONMANAGER_REENLIST_EVENTID = 32;
/// <summary>The event ID for transactionscope created event.</summary>
private const int TRANSACTIONSCOPE_CREATED_EVENTID = 33;
/// <summary>The event ID for transactionscope current changed event.</summary>
private const int TRANSACTIONSCOPE_CURRENT_CHANGED_EVENTID = 34;
/// <summary>The event ID for transactionscope nested incorrectly event.</summary>
private const int TRANSACTIONSCOPE_DISPOSED_EVENTID = 35;
/// <summary>The event ID for transactionscope incomplete event.</summary>
private const int TRANSACTIONSCOPE_INCOMPLETE_EVENTID = 36;
/// <summary>The event ID for transactionscope internal error event.</summary>
private const int TRANSACTIONSCOPE_INTERNAL_ERROR_EVENTID = 37;
/// <summary>The event ID for transactionscope nested incorrectly event.</summary>
private const int TRANSACTIONSCOPE_NESTED_INCORRECTLY_EVENTID = 38;
/// <summary>The event ID for transactionscope timeout event.</summary>
private const int TRANSACTIONSCOPE_TIMEOUT_EVENTID = 39;
/// <summary>The event ID for enlistment event.</summary>
private const int TRANSACTIONSTATE_ENLIST_EVENTID = 40;
//-----------------------------------------------------------------------------------
//
// Transactions Events
//
private const string NullInstance = "(null)";
//-----------------------------------------------------------------------------------
//
// Transactions Events
//
[NonEvent]
public static string IdOf(object value) => value != null ? value.GetType().Name + "#" + GetHashCode(value) : NullInstance;
[NonEvent]
public static int GetHashCode(object value) => value?.GetHashCode() ?? 0;
#region Transaction Creation
/// <summary>Trace an event when a new transaction is created.</summary>
/// <param name="transaction">The transaction that was created.</param>
/// <param name="type">The type of transaction.</param>Method
[NonEvent]
internal void TransactionCreated(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionCreated(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionCreated(string.Empty, type);
}
}
[Event(TRANSACTION_CREATED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.Transaction, Opcode = Opcodes.Create, Message = "Transaction Created. ID is {0}, type is {1}")]
private void TransactionCreated(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_CREATED_EVENTID, transactionIdentifier, type);
}
#endregion
#region Transaction Clone Create
/// <summary>Trace an event when a new transaction is clone created.</summary>
/// <param name="transaction">The transaction that was clone created.</param>
/// <param name="type">The type of transaction.</param>
[NonEvent]
internal void TransactionCloneCreate(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionCloneCreate(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionCloneCreate(string.Empty, type);
}
}
[Event(TRANSACTION_CLONECREATE_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.Transaction, Opcode = Opcodes.CloneCreate, Message = "Transaction Clone Created. ID is {0}, type is {1}")]
private void TransactionCloneCreate(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_CLONECREATE_EVENTID, transactionIdentifier, type);
}
#endregion
#region Transaction Serialized
/// <summary>Trace an event when a transaction is serialized.</summary>
/// <param name="transaction">The transaction that was serialized.</param>
/// <param name="type">The type of transaction.</param>
[NonEvent]
internal void TransactionSerialized(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionSerialized(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionSerialized(string.Empty, type);
}
}
[Event(TRANSACTION_SERIALIZED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.Transaction, Opcode = Opcodes.Serialized, Message = "Transaction Serialized. ID is {0}, type is {1}")]
private void TransactionSerialized(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_SERIALIZED_EVENTID, transactionIdentifier, type);
}
#endregion
#region Transaction Exception
/// <summary>Trace an event when an exception happens.</summary>
/// <param name="traceSource">trace source</param>
/// <param name="type">The type of transaction.</param>
/// <param name="message">The message for the exception.</param>
/// <param name="innerExceptionStr">The inner exception.</param>
[NonEvent]
internal void TransactionExceptionTrace(TraceSourceType traceSource, TransactionExceptionType type, string message, string innerExceptionStr)
{
if (IsEnabled(EventLevel.Error, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceBase)
{
TransactionExceptionBase(type.ToString(), message, innerExceptionStr);
}
else
{
TransactionExceptionLtm(type.ToString(), message, innerExceptionStr);
}
}
}
/// <summary>Trace an event when an exception happens.</summary>
/// <param name="type">The type of transaction.</param>
/// <param name="message">The message for the exception.</param>
/// <param name="innerExceptionStr">The inner exception.</param>
[NonEvent]
internal void TransactionExceptionTrace(TransactionExceptionType type, string message, string innerExceptionStr)
{
if (IsEnabled(EventLevel.Error, ALL_KEYWORDS))
{
TransactionExceptionLtm(type.ToString(), message, innerExceptionStr);
}
}
[Event(TRANSACTION_EXCEPTION_BASE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Error, Task = Tasks.TransactionException, Message = "Transaction Exception. Type is {0}, message is {1}, InnerException is {2}")]
private void TransactionExceptionBase(string type, string message, string innerExceptionStr)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTION_EXCEPTION_BASE_EVENTID, type, message, innerExceptionStr);
}
[Event(TRANSACTION_EXCEPTION_LTM_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Error, Task = Tasks.TransactionException, Message = "Transaction Exception. Type is {0}, message is {1}, InnerException is {2}")]
private void TransactionExceptionLtm(string type, string message, string innerExceptionStr)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTION_EXCEPTION_LTM_EVENTID, type, message, innerExceptionStr);
}
#endregion
#region Transaction Invalid Operation
/// <summary>Trace an event when an invalid operation happened on a transaction.</summary>
/// <param name="type">The type of transaction.</param>
/// <param name="operation">The operationont the transaction.</param>
[NonEvent]
internal void InvalidOperation(string type, string operation)
{
if (IsEnabled(EventLevel.Error, ALL_KEYWORDS))
{
TransactionInvalidOperation(
string.Empty, type, operation);
}
}
[Event(TRANSACTION_INVALID_OPERATION_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Error, Task = Tasks.Transaction, Opcode = Opcodes.InvalidOperation, Message = "Transaction Invalid Operation. ID is {0}, type is {1} and operation is {2}")]
private void TransactionInvalidOperation(string transactionIdentifier, string type, string operation)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTION_INVALID_OPERATION_EVENTID, transactionIdentifier, type, operation);
}
#endregion
#region Transaction Rollback
/// <summary>Trace an event when rollback on a transaction.</summary>
/// <param name="transaction">The transaction to rollback.</param>
/// <param name="type">The type of transaction.</param>
[NonEvent]
internal void TransactionRollback(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionRollback(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionRollback(string.Empty, type);
}
}
[Event(TRANSACTION_ROLLBACK_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Transaction, Opcode = Opcodes.Rollback, Message = "Transaction Rollback. ID is {0}, type is {1}")]
private void TransactionRollback(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_ROLLBACK_EVENTID, transactionIdentifier, type);
}
#endregion
#region Transaction Dependent Clone Complete
/// <summary>Trace an event when transaction dependent clone complete.</summary>
/// <param name="transaction">The transaction that do dependent clone.</param>
/// <param name="type">The type of transaction.</param>
[NonEvent]
internal void TransactionDependentCloneComplete(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionDependentCloneComplete(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionDependentCloneComplete(string.Empty, type);
}
}
[Event(TRANSACTION_DEPENDENT_CLONE_COMPLETE_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.Transaction, Opcode = Opcodes.DependentCloneComplete, Message = "Transaction Dependent Clone Completed. ID is {0}, type is {1}")]
private void TransactionDependentCloneComplete(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_DEPENDENT_CLONE_COMPLETE_EVENTID, transactionIdentifier, type);
}
#endregion
#region Transaction Commit
/// <summary>Trace an event when there is commit on that transaction.</summary>
/// <param name="transaction">The transaction to commit.</param>
/// <param name="type">The type of transaction.</param>
[NonEvent]
internal void TransactionCommit(Transaction transaction, string type)
{
Debug.Assert(transaction != null, "Transaction needed for the ETW event.");
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (transaction != null && transaction.TransactionTraceId.TransactionIdentifier != null)
TransactionCommit(transaction.TransactionTraceId.TransactionIdentifier, type);
else
TransactionCommit(string.Empty, type);
}
}
[Event(TRANSACTION_COMMIT_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Transaction, Opcode = Opcodes.Commit, Message = "Transaction Commit: ID is {0}, type is {1}")]
private void TransactionCommit(string transactionIdentifier, string type)
{
SetActivityId(transactionIdentifier);
WriteEvent(TRANSACTION_COMMIT_EVENTID, transactionIdentifier, type);
}
#endregion
#region Enlistment
/// <summary>Trace an event for enlistment status.</summary>
/// <param name="enlistment">The enlistment to report status.</param>
/// <param name="notificationCall">The notification call on the enlistment.</param>
[NonEvent]
internal void EnlistmentStatus(InternalEnlistment enlistment, NotificationCall notificationCall)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentStatus(enlistment.EnlistmentTraceId.EnlistmentIdentifier, notificationCall.ToString());
else
EnlistmentStatus(0, notificationCall.ToString());
}
}
[Event(ENLISTMENT_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Enlistment, Message = "Enlistment status: ID is {0}, notificationcall is {1}")]
private void EnlistmentStatus(int enlistmentIdentifier, string notificationCall)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_EVENTID, enlistmentIdentifier, notificationCall);
}
#endregion
#region Enlistment Done
/// <summary>Trace an event for enlistment done.</summary>
/// <param name="enlistment">The enlistment done.</param>
[NonEvent]
internal void EnlistmentDone(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentDone(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentDone(0);
}
}
[Event(ENLISTMENT_DONE_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Enlistment, Opcode = Opcodes.Done, Message = "Enlistment.Done: ID is {0}")]
private void EnlistmentDone(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_DONE_EVENTID, enlistmentIdentifier);
}
#endregion
#region Enlistment Prepared
/// <summary>Trace an event for enlistment prepared.</summary>
/// <param name="enlistment">The enlistment prepared.</param>
[NonEvent]
internal void EnlistmentPrepared(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentPrepared(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentPrepared(0);
}
}
[Event(ENLISTMENT_PREPARED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Enlistment, Opcode = Opcodes.Prepared, Message = "PreparingEnlistment.Prepared: ID is {0}")]
private void EnlistmentPrepared(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_PREPARED_EVENTID, enlistmentIdentifier);
}
#endregion
#region Enlistment ForceRollback
/// <summary>Trace an enlistment that will forcerollback.</summary>
/// <param name="enlistment">The enlistment to forcerollback.</param>
[NonEvent]
internal void EnlistmentForceRollback(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentForceRollback(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentForceRollback(0);
}
}
[Event(ENLISTMENT_FORCEROLLBACK_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Enlistment, Opcode = Opcodes.ForceRollback, Message = "Enlistment forceRollback: ID is {0}")]
private void EnlistmentForceRollback(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_FORCEROLLBACK_EVENTID, enlistmentIdentifier);
}
#endregion
#region Enlistment Aborted
/// <summary>Trace an enlistment that aborted.</summary>
/// <param name="enlistment">The enlistment aborted.</param>
[NonEvent]
internal void EnlistmentAborted(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentAborted(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentAborted(0);
}
}
[Event(ENLISTMENT_ABORTED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Enlistment, Opcode = Opcodes.Aborted, Message = "Enlistment SinglePhase Aborted: ID is {0}")]
private void EnlistmentAborted(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_ABORTED_EVENTID, enlistmentIdentifier);
}
#endregion
#region Enlistment Committed
/// <summary>Trace an enlistment that committed.</summary>
/// <param name="enlistment">The enlistment committed.</param>
[NonEvent]
internal void EnlistmentCommitted(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentCommitted(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentCommitted(0);
}
}
[Event(ENLISTMENT_COMMITTED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Enlistment, Opcode = Opcodes.Committed, Message = "Enlistment Committed: ID is {0}")]
private void EnlistmentCommitted(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_COMMITTED_EVENTID, enlistmentIdentifier);
}
#endregion
#region Enlistment InDoubt
/// <summary>Trace an enlistment that InDoubt.</summary>
/// <param name="enlistment">The enlistment Indoubt.</param>
[NonEvent]
internal void EnlistmentInDoubt(InternalEnlistment enlistment)
{
Debug.Assert(enlistment != null, "Enlistment needed for the ETW event.");
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
if (enlistment != null && enlistment.EnlistmentTraceId.EnlistmentIdentifier != 0)
EnlistmentInDoubt(enlistment.EnlistmentTraceId.EnlistmentIdentifier);
else
EnlistmentInDoubt(0);
}
}
[Event(ENLISTMENT_INDOUBT_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Enlistment, Opcode = Opcodes.InDoubt, Message = "Enlistment SinglePhase InDoubt: ID is {0}")]
private void EnlistmentInDoubt(int enlistmentIdentifier)
{
SetActivityId(string.Empty);
WriteEvent(ENLISTMENT_INDOUBT_EVENTID, enlistmentIdentifier);
}
#endregion
#region Method Enter
/// <summary>Trace an event when enter a method.</summary>
/// <param name="traceSource"> trace source</param>
/// <param name="thisOrContextObject">'this', or another object that serves to provide context for the operation.</param>
/// <param name="methodname">The name of method.</param>
[NonEvent]
internal void MethodEnter(TraceSourceType traceSource, object thisOrContextObject, [CallerMemberName] string methodname = null)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceLtm)
{
MethodEnterTraceLtm(IdOf(thisOrContextObject), methodname);
}
else if (traceSource == TraceSourceType.TraceSourceBase)
{
MethodEnterTraceBase(IdOf(thisOrContextObject), methodname);
}
else if (traceSource == TraceSourceType.TraceSourceDistributed)
{
MethodEnterTraceDistributed(IdOf(thisOrContextObject), methodname);
}
}
}
/// <summary>Trace an event when enter a method.</summary>
/// <param name="traceSource"> trace source</param>
/// <param name="methodname">The name of method.</param>
[NonEvent]
internal void MethodEnter(TraceSourceType traceSource, [CallerMemberName] string methodname = null)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceLtm)
{
MethodEnterTraceLtm(string.Empty, methodname);
}
else if (traceSource == TraceSourceType.TraceSourceBase)
{
MethodEnterTraceBase(string.Empty, methodname);
}
else if (traceSource == TraceSourceType.TraceSourceDistributed)
{
MethodEnterTraceDistributed(string.Empty, methodname);
}
}
}
[Event(METHOD_ENTER_LTM_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Enter, Message = "Enter method : {0}.{1}")]
private void MethodEnterTraceLtm(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_ENTER_LTM_EVENTID, thisOrContextObject, methodname);
}
[Event(METHOD_ENTER_BASE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Enter, Message = "Enter method : {0}.{1}")]
private void MethodEnterTraceBase(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_ENTER_BASE_EVENTID, thisOrContextObject, methodname);
}
[Event(METHOD_ENTER_DISTRIBUTED_EVENTID, Keywords = Keywords.TraceDistributed, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Enter, Message = "Enter method : {0}.{1}")]
private void MethodEnterTraceDistributed(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_ENTER_DISTRIBUTED_EVENTID, thisOrContextObject, methodname);
}
#endregion
#region Method Exit
/// <summary>Trace an event when enter a method.</summary>
/// <param name="traceSource"> trace source</param>
/// <param name="thisOrContextObject">'this', or another object that serves to provide context for the operation.</param>
/// <param name="methodname">The name of method.</param>
[NonEvent]
internal void MethodExit(TraceSourceType traceSource, object thisOrContextObject, [CallerMemberName] string methodname = null)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceLtm)
{
MethodExitTraceLtm(IdOf(thisOrContextObject), methodname);
}
else if (traceSource == TraceSourceType.TraceSourceBase)
{
MethodExitTraceBase(IdOf(thisOrContextObject), methodname);
}
else if (traceSource == TraceSourceType.TraceSourceDistributed)
{
MethodExitTraceDistributed(IdOf(thisOrContextObject), methodname);
}
}
}
/// <summary>Trace an event when enter a method.</summary>
/// <param name="traceSource"> trace source</param>
/// <param name="methodname">The name of method.</param>
[NonEvent]
internal void MethodExit(TraceSourceType traceSource, [CallerMemberName] string methodname = null)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceLtm)
{
MethodExitTraceLtm(string.Empty, methodname);
}
else if (traceSource == TraceSourceType.TraceSourceBase)
{
MethodExitTraceBase(string.Empty, methodname);
}
else if (traceSource == TraceSourceType.TraceSourceDistributed)
{
MethodExitTraceDistributed(string.Empty, methodname);
}
}
}
[Event(METHOD_EXIT_LTM_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Exit, Message = "Exit method: {0}.{1}")]
private void MethodExitTraceLtm(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_EXIT_LTM_EVENTID, thisOrContextObject, methodname);
}
[Event(METHOD_EXIT_BASE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Exit, Message = "Exit method: {0}.{1}")]
private void MethodExitTraceBase(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_EXIT_BASE_EVENTID, thisOrContextObject, methodname);
}
[Event(METHOD_EXIT_DISTRIBUTED_EVENTID, Keywords = Keywords.TraceDistributed, Level = EventLevel.Verbose, Task = Tasks.Method, Opcode = Opcodes.Exit, Message = "Exit method: {0}.{1}")]
private void MethodExitTraceDistributed(string thisOrContextObject, string methodname)
{
SetActivityId(string.Empty);
WriteEvent(METHOD_EXIT_DISTRIBUTED_EVENTID, thisOrContextObject, methodname);
}
#endregion
#region Exception Consumed
/// <summary>Trace an event when exception consumed.</summary>
/// <param name="traceSource">trace source</param>
/// <param name="exception">The exception.</param>
[NonEvent]
internal void ExceptionConsumed(TraceSourceType traceSource, Exception exception)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
if (traceSource == TraceSourceType.TraceSourceBase)
{
ExceptionConsumedBase(exception.ToString());
}
else
{
ExceptionConsumedLtm(exception.ToString());
}
}
}
/// <summary>Trace an event when exception consumed.</summary>
/// <param name="exception">The exception.</param>
[NonEvent]
internal void ExceptionConsumed(Exception exception)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
ExceptionConsumedLtm(exception.ToString());
}
}
[Event(EXCEPTION_CONSUMED_BASE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Verbose, Opcode = Opcodes.ExceptionConsumed, Message = "Exception consumed: {0}")]
private void ExceptionConsumedBase(string exceptionStr)
{
SetActivityId(string.Empty);
WriteEvent(EXCEPTION_CONSUMED_BASE_EVENTID, exceptionStr);
}
[Event(EXCEPTION_CONSUMED_LTM_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Opcode = Opcodes.ExceptionConsumed, Message = "Exception consumed: {0}")]
private void ExceptionConsumedLtm(string exceptionStr)
{
SetActivityId(string.Empty);
WriteEvent(EXCEPTION_CONSUMED_LTM_EVENTID, exceptionStr);
}
#endregion
#region TransactionManager Reenlist
/// <summary>Trace an event when reenlist transactionmanager.</summary>
/// <param name="resourceManagerID">The resource manager ID.</param>
[NonEvent]
internal void TransactionManagerReenlist(Guid resourceManagerID)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
TransactionManagerReenlistTrace(resourceManagerID.ToString());
}
}
[Event(TRANSACTIONMANAGER_REENLIST_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Informational, Task = Tasks.TransactionManager, Opcode = Opcodes.Reenlist, Message = "Reenlist in: {0}")]
private void TransactionManagerReenlistTrace(string rmID)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTIONMANAGER_REENLIST_EVENTID, rmID);
}
#endregion
#region TransactionManager Recovery Complete
/// <summary>Trace an event when transactionmanager recovery complete.</summary>
/// <param name="resourceManagerID">The resource manager ID.</param>
[NonEvent]
internal void TransactionManagerRecoveryComplete(Guid resourceManagerID)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
TransactionManagerRecoveryComplete(resourceManagerID.ToString());
}
}
[Event(TRANSACTIONMANAGER_RECOVERY_COMPLETE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Informational, Task = Tasks.TransactionManager, Opcode = Opcodes.RecoveryComplete, Message = "Recovery complete: {0}")]
private void TransactionManagerRecoveryComplete(string rmID)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTIONMANAGER_RECOVERY_COMPLETE_EVENTID, rmID);
}
#endregion
#region Configured Default Timeout Adjusted
/// <summary>Trace an event when configured default timeout adjusted.</summary>
[NonEvent]
internal void ConfiguredDefaultTimeoutAdjusted()
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
ConfiguredDefaultTimeoutAdjustedTrace();
}
}
[Event(CONFIGURED_DEFAULT_TIMEOUT_ADJUSTED_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Warning, Task = Tasks.ConfiguredDefaultTimeout, Opcode = Opcodes.Adjusted, Message = "Configured Default Timeout Adjusted")]
private void ConfiguredDefaultTimeoutAdjustedTrace()
{
SetActivityId(string.Empty);
WriteEvent(CONFIGURED_DEFAULT_TIMEOUT_ADJUSTED_EVENTID);
}
#endregion
#region Transactionscope Created
/// <summary>Trace an event when a transactionscope is created.</summary>
/// <param name="transactionID">The transaction ID.</param>
/// <param name="transactionScopeResult">The transaction scope result.</param>
[NonEvent]
internal void TransactionScopeCreated(TransactionTraceIdentifier transactionID, TransactionScopeResult transactionScopeResult)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
TransactionScopeCreated(transactionID.TransactionIdentifier ?? string.Empty, transactionScopeResult);
}
}
[Event(TRANSACTIONSCOPE_CREATED_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Informational, Task = Tasks.TransactionScope, Opcode = Opcodes.Created, Message = "Transactionscope was created: Transaction ID is {0}, TransactionScope Result is {1}")]
private void TransactionScopeCreated(string transactionID, TransactionScopeResult transactionScopeResult)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTIONSCOPE_CREATED_EVENTID, transactionID, transactionScopeResult);
}
#endregion
#region Transactionscope Current Changed
/// <summary>Trace an event when a transactionscope current transaction changed.</summary>
/// <param name="currenttransactionID">The transaction ID.</param>
/// <param name="newtransactionID">The new transaction ID.</param>
[NonEvent]
internal void TransactionScopeCurrentChanged(TransactionTraceIdentifier currenttransactionID, TransactionTraceIdentifier newtransactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
string currentId = string.Empty;
string newId = string.Empty;
if (currenttransactionID.TransactionIdentifier != null)
{
currentId = currenttransactionID.TransactionIdentifier.ToString();
}
if (newtransactionID.TransactionIdentifier != null)
{
newId = newtransactionID.TransactionIdentifier.ToString();
}
TransactionScopeCurrentChanged(currentId, newId);
}
}
[Event(TRANSACTIONSCOPE_CURRENT_CHANGED_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Warning, Task = Tasks.TransactionScope, Opcode = Opcodes.CurrentChanged, Message = "Transactionscope current transaction ID changed from {0} to {1}")]
private void TransactionScopeCurrentChanged(string currenttransactionID, string newtransactionID)
{
SetActivityId(newtransactionID);
WriteEvent(TRANSACTIONSCOPE_CURRENT_CHANGED_EVENTID, currenttransactionID, newtransactionID);
}
#endregion
#region Transactionscope Nested Incorrectly
/// <summary>Trace an event when a transactionscope is nested incorrectly.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionScopeNestedIncorrectly(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionScopeNestedIncorrectly(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTIONSCOPE_NESTED_INCORRECTLY_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Warning, Task = Tasks.TransactionScope, Opcode = Opcodes.NestedIncorrectly, Message = "Transactionscope nested incorrectly: transaction ID is {0}")]
private void TransactionScopeNestedIncorrectly(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTIONSCOPE_NESTED_INCORRECTLY_EVENTID, transactionID);
}
#endregion
#region Transactionscope Disposed
/// <summary>Trace an event when a transactionscope is disposed.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionScopeDisposed(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
TransactionScopeDisposed(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTIONSCOPE_DISPOSED_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Informational, Task = Tasks.TransactionScope, Opcode = Opcodes.Disposed, Message = "Transactionscope disposed: transaction ID is {0}")]
private void TransactionScopeDisposed(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTIONSCOPE_DISPOSED_EVENTID, transactionID);
}
#endregion
#region Transactionscope Incomplete
/// <summary>Trace an event when a transactionscope incomplete.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionScopeIncomplete(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionScopeIncomplete(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTIONSCOPE_INCOMPLETE_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Warning, Task = Tasks.TransactionScope, Opcode = Opcodes.Incomplete, Message = "Transactionscope incomplete: transaction ID is {0}")]
private void TransactionScopeIncomplete(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTIONSCOPE_INCOMPLETE_EVENTID, transactionID);
}
#endregion
#region Transactionscope Internal Error
/// <summary>Trace an event when there is an internal error on transactionscope.</summary>
/// <param name="error">The error information.</param>
[NonEvent]
internal void TransactionScopeInternalError(string error)
{
if (IsEnabled(EventLevel.Critical, ALL_KEYWORDS))
{
TransactionScopeInternalErrorTrace(error);
}
}
[Event(TRANSACTIONSCOPE_INTERNAL_ERROR_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Critical, Task = Tasks.TransactionScope, Opcode = Opcodes.InternalError, Message = "Transactionscope internal error: {0}")]
private void TransactionScopeInternalErrorTrace(string error)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTIONSCOPE_INTERNAL_ERROR_EVENTID, error);
}
#endregion
#region Transactionscope Timeout
/// <summary>Trace an event when there is timeout on transactionscope.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionScopeTimeout(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionScopeTimeout(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTIONSCOPE_TIMEOUT_EVENTID, Keywords = Keywords.TraceBase, Level = EventLevel.Warning, Task = Tasks.TransactionScope, Opcode = Opcodes.Timeout, Message = "Transactionscope timeout: transaction ID is {0}")]
private void TransactionScopeTimeout(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTIONSCOPE_TIMEOUT_EVENTID, transactionID);
}
#endregion
#region Transaction Timeout
/// <summary>Trace an event when there is timeout on transaction.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionTimeout(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionTimeout(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTION_TIMEOUT_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Transaction, Opcode = Opcodes.Timeout, Message = "Transaction timeout: transaction ID is {0}")]
private void TransactionTimeout(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTION_TIMEOUT_EVENTID, transactionID);
}
#endregion
#region Transactionstate Enlist
/// <summary>Trace an event when there is enlist.</summary>
/// <param name="enlistmentID">The enlistment ID.</param>
/// <param name="enlistmentType">The enlistment type.</param>
/// <param name="enlistmentOption">The enlistment option.</param>
[NonEvent]
internal void TransactionstateEnlist(EnlistmentTraceIdentifier enlistmentID, EnlistmentType enlistmentType, EnlistmentOptions enlistmentOption)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
if (enlistmentID.EnlistmentIdentifier != 0)
TransactionstateEnlist(enlistmentID.EnlistmentIdentifier.ToString(), enlistmentType.ToString(), enlistmentOption.ToString());
else
TransactionstateEnlist(string.Empty, enlistmentType.ToString(), enlistmentOption.ToString());
}
}
[Event(TRANSACTIONSTATE_ENLIST_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.TransactionState, Opcode = Opcodes.Enlist, Message = "Transactionstate enlist: Enlistment ID is {0}, type is {1} and options is {2}")]
private void TransactionstateEnlist(string enlistmentID, string type, string option)
{
SetActivityId(string.Empty);
WriteEvent(TRANSACTIONSTATE_ENLIST_EVENTID, enlistmentID, type, option);
}
#endregion
#region Transactionstate committed
/// <summary>Trace an event when transaction is committed.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionCommitted(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Verbose, ALL_KEYWORDS))
{
TransactionCommitted(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTION_COMMITTED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Verbose, Task = Tasks.Transaction, Opcode = Opcodes.Committed, Message = "Transaction committed: transaction ID is {0}")]
private void TransactionCommitted(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTION_COMMITTED_EVENTID, transactionID);
}
#endregion
#region Transactionstate indoubt
/// <summary>Trace an event when transaction is indoubt.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionInDoubt(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionInDoubt(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTION_INDOUBT_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Transaction, Opcode = Opcodes.InDoubt, Message = "Transaction indoubt: transaction ID is {0}")]
private void TransactionInDoubt(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTION_INDOUBT_EVENTID, transactionID);
}
#endregion
#region Transactionstate promoted
/// <summary>Trace an event when transaction is promoted.</summary>
/// <param name="transactionID">The transaction ID.</param>
/// <param name="distributedTxID">The distributed transaction ID.</param>
[NonEvent]
internal void TransactionPromoted(TransactionTraceIdentifier transactionID, TransactionTraceIdentifier distributedTxID)
{
if (IsEnabled(EventLevel.Informational, ALL_KEYWORDS))
{
TransactionPromoted(transactionID.TransactionIdentifier ?? string.Empty, distributedTxID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTION_PROMOTED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Informational, Task = Tasks.Transaction, Opcode = Opcodes.Promoted, Message = "Transaction promoted: transaction ID is {0} and distributed transaction ID is {1}")]
private void TransactionPromoted(string transactionID, string distributedTxID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTION_PROMOTED_EVENTID, transactionID, distributedTxID);
}
#endregion
#region Transactionstate aborted
/// <summary>Trace an event when transaction is aborted.</summary>
/// <param name="transactionID">The transaction ID.</param>
[NonEvent]
internal void TransactionAborted(TransactionTraceIdentifier transactionID)
{
if (IsEnabled(EventLevel.Warning, ALL_KEYWORDS))
{
TransactionAborted(transactionID.TransactionIdentifier ?? string.Empty);
}
}
[Event(TRANSACTION_ABORTED_EVENTID, Keywords = Keywords.TraceLtm, Level = EventLevel.Warning, Task = Tasks.Transaction, Opcode = Opcodes.Aborted, Message = "Transaction aborted: transaction ID is {0}")]
private void TransactionAborted(string transactionID)
{
SetActivityId(transactionID);
WriteEvent(TRANSACTION_ABORTED_EVENTID, transactionID);
}
#endregion
public class Opcodes
{
public const EventOpcode Aborted = (EventOpcode)100;
public const EventOpcode Activity = (EventOpcode)101;
public const EventOpcode Adjusted = (EventOpcode)102;
public const EventOpcode CloneCreate = (EventOpcode)103;
public const EventOpcode Commit = (EventOpcode)104;
public const EventOpcode Committed = (EventOpcode)105;
public const EventOpcode Create = (EventOpcode)106;
public const EventOpcode Created = (EventOpcode)107;
public const EventOpcode CurrentChanged = (EventOpcode)108;
public const EventOpcode DependentCloneComplete = (EventOpcode)109;
public const EventOpcode Disposed = (EventOpcode)110;
public const EventOpcode Done = (EventOpcode)111;
public const EventOpcode Enlist = (EventOpcode)112;
public const EventOpcode Enter = (EventOpcode)113;
public const EventOpcode ExceptionConsumed = (EventOpcode)114;
public const EventOpcode Exit = (EventOpcode)115;
public const EventOpcode ForceRollback = (EventOpcode)116;
public const EventOpcode Incomplete = (EventOpcode)117;
public const EventOpcode InDoubt = (EventOpcode)118;
public const EventOpcode InternalError = (EventOpcode)119;
public const EventOpcode InvalidOperation = (EventOpcode)120;
public const EventOpcode NestedIncorrectly = (EventOpcode)121;
public const EventOpcode Prepared = (EventOpcode)122;
public const EventOpcode Promoted = (EventOpcode)123;
public const EventOpcode RecoveryComplete = (EventOpcode)124;
public const EventOpcode Reenlist = (EventOpcode)125;
public const EventOpcode Rollback = (EventOpcode)126;
public const EventOpcode Serialized = (EventOpcode)127;
public const EventOpcode Timeout = (EventOpcode)128;
}
public class Tasks
{
public const EventTask ConfiguredDefaultTimeout = (EventTask)1;
public const EventTask Enlistment = (EventTask)2;
public const EventTask ResourceManager = (EventTask)3;
public const EventTask Method = (EventTask)4;
public const EventTask Transaction = (EventTask)5;
public const EventTask TransactionException = (EventTask)6;
public const EventTask TransactionManager = (EventTask)7;
public const EventTask TransactionScope = (EventTask)8;
public const EventTask TransactionState = (EventTask)9;
}
public class Keywords
{
public const EventKeywords TraceBase = (EventKeywords)0x0001;
public const EventKeywords TraceLtm = (EventKeywords)0x0002;
public const EventKeywords TraceDistributed = (EventKeywords)0x0004;
}
private void SetActivityId(string str)
{
Guid guid = Guid.Empty;
if (str.Contains('-'))
{ // GUID with dash
if (str.Length >= 36)
{
string str_part1 = str.Substring(0, 36);
Guid.TryParse(str_part1, out guid);
}
}
else
{
if (str.Length >= 32)
{
string str_part1 = str.Substring(0, 32);
Guid.TryParse(str_part1, out guid);
}
}
SetCurrentThreadActivityId(guid);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DecimalStorage.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="false" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.Xml;
using System.Data.SqlTypes;
using System.Collections;
internal sealed class DecimalStorage : DataStorage {
private static readonly Decimal defaultValue = Decimal.Zero;
private Decimal[] values;
internal DecimalStorage(DataColumn column)
: base(column, typeof(Decimal), defaultValue, StorageType.Decimal) {
}
override public Object Aggregate(int[] records, AggregateType kind) {
bool hasData = false;
try {
switch (kind) {
case AggregateType.Sum:
Decimal sum = defaultValue;
foreach (int record in records) {
if (HasValue(record)) {
checked { sum += values[record];}
hasData = true;
}
}
if (hasData) {
return sum;
}
return NullValue;
case AggregateType.Mean:
Decimal meanSum = (Decimal)defaultValue;
int meanCount = 0;
foreach (int record in records) {
if (HasValue(record)) {
checked { meanSum += (Decimal)values[record];}
meanCount++;
hasData = true;
}
}
if (hasData) {
Decimal mean;
checked {mean = (meanSum /(Decimal) meanCount);}
return mean;
}
return NullValue;
case AggregateType.Var:
case AggregateType.StDev:
int count = 0;
double var = (double)defaultValue;
double prec = (double)defaultValue;
double dsum = (double)defaultValue;
double sqrsum = (double)defaultValue;
foreach (int record in records) {
if (HasValue(record)) {
dsum += (double)values[record];
sqrsum += (double)values[record]*(double)values[record];
count++;
}
}
if (count > 1) {
var = ((double)count * sqrsum - (dsum * dsum));
prec = var / (dsum * dsum);
// we are dealing with the risk of a cancellation error
// double is guaranteed only for 15 digits so a difference
// with a result less than 1e-15 should be considered as zero
if ((prec < 1e-15) || (var <0))
var = 0;
else
var = var / (count * (count -1));
if (kind == AggregateType.StDev) {
return Math.Sqrt(var);
}
return var;
}
return NullValue;
case AggregateType.Min:
Decimal min = Decimal.MaxValue;
for (int i = 0; i < records.Length; i++) {
int record = records[i];
if (HasValue(record)) {
min=Math.Min(values[record], min);
hasData = true;
}
}
if (hasData) {
return min;
}
return NullValue;
case AggregateType.Max:
Decimal max = Decimal.MinValue;
for (int i = 0; i < records.Length; i++) {
int record = records[i];
if (HasValue(record)) {
max=Math.Max(values[record], max);
hasData = true;
}
}
if (hasData) {
return max;
}
return NullValue;
case AggregateType.First:
if (records.Length > 0) {
return values[records[0]];
}
return null;
case AggregateType.Count:
return base.Aggregate(records, kind);
}
}
catch (OverflowException) {
throw ExprException.Overflow(typeof(Decimal));
}
throw ExceptionBuilder.AggregateException(kind, DataType);
}
override public int Compare(int recordNo1, int recordNo2) {
Decimal valueNo1 = values[recordNo1];
Decimal valueNo2 = values[recordNo2];
if (valueNo1 == defaultValue || valueNo2 == defaultValue) {
int bitCheck = CompareBits(recordNo1, recordNo2);
if (0 != bitCheck)
return bitCheck;
}
return Decimal.Compare(valueNo1, valueNo2); // InternalCall
}
public override int CompareValueTo(int recordNo, object value) {
System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record");
System.Diagnostics.Debug.Assert(null != value, "null value");
if (NullValue == value) {
return (HasValue(recordNo) ? 1 : 0);
}
Decimal valueNo1 = values[recordNo];
if ((defaultValue == valueNo1) && !HasValue(recordNo)) {
return -1;
}
return Decimal.Compare(valueNo1, (Decimal)value);
}
public override object ConvertValue(object value) {
if (NullValue != value) {
if (null != value) {
value = ((IConvertible)value).ToDecimal(FormatProvider);
}
else {
value = NullValue;
}
}
return value;
}
override public void Copy(int recordNo1, int recordNo2) {
CopyBits(recordNo1, recordNo2);
values[recordNo2] = values[recordNo1];
}
override public Object Get(int record) {
return (HasValue(record) ? values[record] : NullValue);
}
override public void Set(int record, Object value) {
System.Diagnostics.Debug.Assert(null != value, "null value");
if (NullValue == value) {
values[record] = defaultValue;
SetNullBit(record, true);
}
else {
values[record] = ((IConvertible)value).ToDecimal(FormatProvider);
SetNullBit(record, false);
}
}
override public void SetCapacity(int capacity) {
Decimal[] newValues = new Decimal[capacity];
if (null != values) {
Array.Copy(values, 0, newValues, 0, Math.Min(capacity, values.Length));
}
values = newValues;
base.SetCapacity(capacity);
}
override public object ConvertXmlToObject(string s) {
return XmlConvert.ToDecimal(s);
}
override public string ConvertObjectToXml(object value) {
return XmlConvert.ToString((Decimal)value);
}
override protected object GetEmptyStorage(int recordCount) {
return new Decimal[recordCount];
}
override protected void CopyValue(int record, object store, BitArray nullbits, int storeIndex) {
Decimal[] typedStore = (Decimal[]) store;
typedStore[storeIndex] = values[record];
nullbits.Set(storeIndex, !HasValue(record));
}
override protected void SetStorage(object store, BitArray nullbits) {
values = (Decimal[]) store;
SetNullStorage(nullbits);
}
}
}
| |
using Discord.Commands;
using NadekoBot.Extensions;
using System.Linq;
using NadekoBot.Services;
using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using Discord;
using System;
using NadekoBot.Common.Attributes;
using NadekoBot.Modules.Pokemon.Common;
using NadekoBot.Modules.Pokemon.Services;
namespace NadekoBot.Modules.Pokemon
{
public class Pokemon : NadekoTopLevelModule<PokemonService>
{
private readonly DbService _db;
private readonly IBotConfigProvider _bc;
private readonly CurrencyService _cs;
public Pokemon(DbService db, IBotConfigProvider bc, CurrencyService cs)
{
_db = db;
_bc = bc;
_cs = cs;
}
private int GetDamage(PokemonType usertype, PokemonType targetType)
{
var rng = new Random();
var damage = rng.Next(40, 60);
foreach (var multiplierObj in usertype.Multipliers)
{
if (multiplierObj.Type != targetType.Name) continue;
damage = (int)(damage * multiplierObj.Multiplication);
}
return damage;
}
private PokemonType GetPokeType(ulong id)
{
Dictionary<ulong, string> setTypes;
using (var uow = _db.UnitOfWork)
{
setTypes = uow.PokeGame.GetAll().ToDictionary(x => x.UserId, y => y.type);
}
if (setTypes.ContainsKey(id))
{
return StringToPokemonType(setTypes[id]);
}
var count = _service.PokemonTypes.Count;
var remainder = Math.Abs((int)(id % (ulong)count));
return _service.PokemonTypes[remainder];
}
private PokemonType StringToPokemonType(string v)
{
var str = v?.ToUpperInvariant();
var list = _service.PokemonTypes;
foreach (var p in list)
{
if (str == p.Name)
{
return p;
}
}
return null;
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Attack(string move, IGuildUser targetUser = null)
{
IGuildUser user = (IGuildUser)Context.User;
if (string.IsNullOrWhiteSpace(move)) {
return;
}
if (targetUser == null)
{
await ReplyErrorLocalized("user_not_found").ConfigureAwait(false);
return;
}
if (targetUser == user)
{
await ReplyErrorLocalized("cant_attack_yourself").ConfigureAwait(false);
return;
}
// Checking stats first, then move
//Set up the userstats
var userStats = _service.Stats.GetOrAdd(user.Id, new PokeStats());
//Check if able to move
//User not able if HP < 0, has made more than 4 attacks
if (userStats.Hp < 0)
{
await ReplyErrorLocalized("you_fainted").ConfigureAwait(false);
return;
}
if (userStats.MovesMade >= 5)
{
await ReplyErrorLocalized("too_many_moves").ConfigureAwait(false);
return;
}
if (userStats.LastAttacked.Contains(targetUser.Id))
{
await ReplyErrorLocalized("cant_attack_again").ConfigureAwait(false);
return;
}
//get target stats
var targetStats = _service.Stats.GetOrAdd(targetUser.Id, new PokeStats());
//If target's HP is below 0, no use attacking
if (targetStats.Hp <= 0)
{
await ReplyErrorLocalized("too_many_moves", targetUser).ConfigureAwait(false);
return;
}
//Check whether move can be used
PokemonType userType = GetPokeType(user.Id);
var enabledMoves = userType.Moves;
if (!enabledMoves.Contains(move.ToLowerInvariant()))
{
await ReplyErrorLocalized("invalid_move", Format.Bold(move), Prefix).ConfigureAwait(false);
return;
}
//get target type
PokemonType targetType = GetPokeType(targetUser.Id);
//generate damage
int damage = GetDamage(userType, targetType);
//apply damage to target
targetStats.Hp -= damage;
var response = GetText("attack", Format.Bold(move), userType.Icon, Format.Bold(targetUser.ToString()), targetType.Icon, Format.Bold(damage.ToString()));
//Damage type
if (damage < 40)
{
response += "\n" + GetText("not_effective");
}
else if (damage > 60)
{
response += "\n" + GetText("super_effective");
}
else
{
response += "\n" + GetText("somewhat_effective");
}
//check fainted
if (targetStats.Hp <= 0)
{
response += "\n" + GetText("fainted", Format.Bold(targetUser.ToString()));
}
else
{
response += "\n" + GetText("hp_remaining", Format.Bold(targetUser.ToString()), targetStats.Hp);
}
//update other stats
userStats.LastAttacked.Add(targetUser.Id);
userStats.MovesMade++;
targetStats.MovesMade = 0;
if (targetStats.LastAttacked.Contains(user.Id))
{
targetStats.LastAttacked.Remove(user.Id);
}
//update dictionary
//This can stay the same right?
_service.Stats[user.Id] = userStats;
_service.Stats[targetUser.Id] = targetStats;
await Context.Channel.SendConfirmAsync(Context.User.Mention + " " + response).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Movelist()
{
IGuildUser user = (IGuildUser)Context.User;
var userType = GetPokeType(user.Id);
var movesList = userType.Moves;
var embed = new EmbedBuilder().WithOkColor()
.WithTitle(GetText("moves", userType))
.WithDescription(string.Join("\n", movesList.Select(m => userType.Icon + " " + m)));
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Heal(IGuildUser targetUser = null)
{
IGuildUser user = (IGuildUser)Context.User;
if (targetUser == null)
{
await ReplyErrorLocalized("user_not_found").ConfigureAwait(false);
return;
}
if (_service.Stats.ContainsKey(targetUser.Id))
{
var targetStats = _service.Stats[targetUser.Id];
if (targetStats.Hp == targetStats.MaxHp)
{
await ReplyErrorLocalized("already_full", Format.Bold(targetUser.ToString())).ConfigureAwait(false);
return;
}
//Payment~
var amount = 1;
var target = (targetUser.Id == user.Id) ? "yourself" : targetUser.Mention;
if (amount > 0)
{
if (!await _cs.RemoveAsync(user, $"Poke-Heal {target}", amount, true).ConfigureAwait(false))
{
await ReplyErrorLocalized("no_currency", _bc.BotConfig.CurrencySign).ConfigureAwait(false);
return;
}
}
//healing
targetStats.Hp = targetStats.MaxHp;
if (targetStats.Hp < 0)
{
//Could heal only for half HP?
_service.Stats[targetUser.Id].Hp = (targetStats.MaxHp / 2);
if (target == "yourself")
{
await ReplyConfirmLocalized("revive_yourself", _bc.BotConfig.CurrencySign).ConfigureAwait(false);
return;
}
await ReplyConfirmLocalized("revive_other", Format.Bold(targetUser.ToString()), _bc.BotConfig.CurrencySign).ConfigureAwait(false);
}
await ReplyConfirmLocalized("healed", Format.Bold(targetUser.ToString()), _bc.BotConfig.CurrencySign).ConfigureAwait(false);
}
else
{
await ErrorLocalized("already_full", Format.Bold(targetUser.ToString()));
}
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Type(IGuildUser targetUser = null)
{
targetUser = targetUser ?? (IGuildUser)Context.User;
var pType = GetPokeType(targetUser.Id);
await ReplyConfirmLocalized("type_of_user", Format.Bold(targetUser.ToString()), pType).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Settype([Remainder] string typeTargeted = null)
{
IGuildUser user = (IGuildUser)Context.User;
var targetType = StringToPokemonType(typeTargeted);
if (targetType == null)
{
await Context.Channel.EmbedAsync(_service.PokemonTypes.Aggregate(new EmbedBuilder().WithDescription("List of the available types:"),
(eb, pt) => eb.AddField(efb => efb.WithName(pt.Name)
.WithValue(pt.Icon)
.WithIsInline(true)))
.WithColor(NadekoBot.OkColor)).ConfigureAwait(false);
return;
}
if (targetType == GetPokeType(user.Id))
{
await ReplyErrorLocalized("already_that_type", targetType).ConfigureAwait(false);
return;
}
//Payment~
var amount = 1;
if (amount > 0)
{
if (!await _cs.RemoveAsync(user, $"{user} change type to {typeTargeted}", amount, true).ConfigureAwait(false))
{
await ReplyErrorLocalized("no_currency", _bc.BotConfig.CurrencySign).ConfigureAwait(false);
return;
}
}
//Actually changing the type here
using (var uow = _db.UnitOfWork)
{
var pokeUsers = uow.PokeGame.GetAll().ToArray();
var setTypes = pokeUsers.ToDictionary(x => x.UserId, y => y.type);
var pt = new UserPokeTypes
{
UserId = user.Id,
type = targetType.Name,
};
if (!setTypes.ContainsKey(user.Id))
{
//create user in db
uow.PokeGame.Add(pt);
}
else
{
//update user in db
var pokeUserCmd = pokeUsers.FirstOrDefault(p => p.UserId == user.Id);
pokeUserCmd.type = targetType.Name;
uow.PokeGame.Update(pokeUserCmd);
}
await uow.CompleteAsync();
}
//Now for the response
await ReplyConfirmLocalized("settype_success",
targetType,
_bc.BotConfig.CurrencySign).ConfigureAwait(false);
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// TollFreeResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Api.V2010.Account.IncomingPhoneNumber
{
public class TollFreeResource : Resource
{
public sealed class AddressRequirementEnum : StringEnum
{
private AddressRequirementEnum(string value) : base(value) {}
public AddressRequirementEnum() {}
public static implicit operator AddressRequirementEnum(string value)
{
return new AddressRequirementEnum(value);
}
public static readonly AddressRequirementEnum None = new AddressRequirementEnum("none");
public static readonly AddressRequirementEnum Any = new AddressRequirementEnum("any");
public static readonly AddressRequirementEnum Local = new AddressRequirementEnum("local");
public static readonly AddressRequirementEnum Foreign = new AddressRequirementEnum("foreign");
}
public sealed class EmergencyStatusEnum : StringEnum
{
private EmergencyStatusEnum(string value) : base(value) {}
public EmergencyStatusEnum() {}
public static implicit operator EmergencyStatusEnum(string value)
{
return new EmergencyStatusEnum(value);
}
public static readonly EmergencyStatusEnum Active = new EmergencyStatusEnum("Active");
public static readonly EmergencyStatusEnum Inactive = new EmergencyStatusEnum("Inactive");
}
public sealed class EmergencyAddressStatusEnum : StringEnum
{
private EmergencyAddressStatusEnum(string value) : base(value) {}
public EmergencyAddressStatusEnum() {}
public static implicit operator EmergencyAddressStatusEnum(string value)
{
return new EmergencyAddressStatusEnum(value);
}
public static readonly EmergencyAddressStatusEnum Registered = new EmergencyAddressStatusEnum("registered");
public static readonly EmergencyAddressStatusEnum Unregistered = new EmergencyAddressStatusEnum("unregistered");
public static readonly EmergencyAddressStatusEnum PendingRegistration = new EmergencyAddressStatusEnum("pending-registration");
public static readonly EmergencyAddressStatusEnum RegistrationFailure = new EmergencyAddressStatusEnum("registration-failure");
public static readonly EmergencyAddressStatusEnum PendingUnregistration = new EmergencyAddressStatusEnum("pending-unregistration");
public static readonly EmergencyAddressStatusEnum UnregistrationFailure = new EmergencyAddressStatusEnum("unregistration-failure");
}
public sealed class VoiceReceiveModeEnum : StringEnum
{
private VoiceReceiveModeEnum(string value) : base(value) {}
public VoiceReceiveModeEnum() {}
public static implicit operator VoiceReceiveModeEnum(string value)
{
return new VoiceReceiveModeEnum(value);
}
public static readonly VoiceReceiveModeEnum Voice = new VoiceReceiveModeEnum("voice");
public static readonly VoiceReceiveModeEnum Fax = new VoiceReceiveModeEnum("fax");
}
private static Request BuildReadRequest(ReadTollFreeOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/IncomingPhoneNumbers/TollFree.json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read TollFree parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of TollFree </returns>
public static ResourceSet<TollFreeResource> Read(ReadTollFreeOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<TollFreeResource>.FromJson("incoming_phone_numbers", response.Content);
return new ResourceSet<TollFreeResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read TollFree parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of TollFree </returns>
public static async System.Threading.Tasks.Task<ResourceSet<TollFreeResource>> ReadAsync(ReadTollFreeOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<TollFreeResource>.FromJson("incoming_phone_numbers", response.Content);
return new ResourceSet<TollFreeResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param>
/// <param name="beta"> Whether to include new phone numbers </param>
/// <param name="friendlyName"> A string that identifies the resources to read </param>
/// <param name="phoneNumber"> The phone numbers of the resources to read </param>
/// <param name="origin"> Include phone numbers based on their origin. By default, phone numbers of all origin are
/// included. </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of TollFree </returns>
public static ResourceSet<TollFreeResource> Read(string pathAccountSid = null,
bool? beta = null,
string friendlyName = null,
Types.PhoneNumber phoneNumber = null,
string origin = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadTollFreeOptions(){PathAccountSid = pathAccountSid, Beta = beta, FriendlyName = friendlyName, PhoneNumber = phoneNumber, Origin = origin, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param>
/// <param name="beta"> Whether to include new phone numbers </param>
/// <param name="friendlyName"> A string that identifies the resources to read </param>
/// <param name="phoneNumber"> The phone numbers of the resources to read </param>
/// <param name="origin"> Include phone numbers based on their origin. By default, phone numbers of all origin are
/// included. </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of TollFree </returns>
public static async System.Threading.Tasks.Task<ResourceSet<TollFreeResource>> ReadAsync(string pathAccountSid = null,
bool? beta = null,
string friendlyName = null,
Types.PhoneNumber phoneNumber = null,
string origin = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadTollFreeOptions(){PathAccountSid = pathAccountSid, Beta = beta, FriendlyName = friendlyName, PhoneNumber = phoneNumber, Origin = origin, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<TollFreeResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<TollFreeResource>.FromJson("incoming_phone_numbers", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<TollFreeResource> NextPage(Page<TollFreeResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<TollFreeResource>.FromJson("incoming_phone_numbers", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<TollFreeResource> PreviousPage(Page<TollFreeResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<TollFreeResource>.FromJson("incoming_phone_numbers", response.Content);
}
private static Request BuildCreateRequest(CreateTollFreeOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/IncomingPhoneNumbers/TollFree.json",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create TollFree parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of TollFree </returns>
public static TollFreeResource Create(CreateTollFreeOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create TollFree parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of TollFree </returns>
public static async System.Threading.Tasks.Task<TollFreeResource> CreateAsync(CreateTollFreeOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="phoneNumber"> The phone number to purchase in E.164 format </param>
/// <param name="pathAccountSid"> The SID of the Account that will create the resource </param>
/// <param name="apiVersion"> The API version to use for incoming calls made to the new phone number </param>
/// <param name="friendlyName"> A string to describe the new phone number </param>
/// <param name="smsApplicationSid"> The SID of the application to handle SMS messages </param>
/// <param name="smsFallbackMethod"> HTTP method used with sms_fallback_url </param>
/// <param name="smsFallbackUrl"> The URL we call when an error occurs while executing TwiML </param>
/// <param name="smsMethod"> The HTTP method to use with sms_url </param>
/// <param name="smsUrl"> The URL we should call when the new phone number receives an incoming SMS message </param>
/// <param name="statusCallback"> The URL to send status information to your application </param>
/// <param name="statusCallbackMethod"> The HTTP method we should use to call status_callback </param>
/// <param name="voiceApplicationSid"> The SID of the application to handle the new phone number </param>
/// <param name="voiceCallerIdLookup"> Whether to lookup the caller's name </param>
/// <param name="voiceFallbackMethod"> The HTTP method used with voice_fallback_url </param>
/// <param name="voiceFallbackUrl"> The URL we will call when an error occurs in TwiML </param>
/// <param name="voiceMethod"> The HTTP method used with the voice_url </param>
/// <param name="voiceUrl"> The URL we should call when the phone number receives a call </param>
/// <param name="identitySid"> The SID of the Identity resource to associate with the new phone number </param>
/// <param name="addressSid"> The SID of the Address resource associated with the phone number </param>
/// <param name="emergencyStatus"> Displays if emergency calling is enabled for this number. </param>
/// <param name="emergencyAddressSid"> The emergency address configuration to use for emergency calling </param>
/// <param name="trunkSid"> SID of the trunk to handle calls to the new phone number </param>
/// <param name="voiceReceiveMode"> Incoming call type: fax or voice </param>
/// <param name="bundleSid"> The SID of the Bundle resource associated with number </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of TollFree </returns>
public static TollFreeResource Create(Types.PhoneNumber phoneNumber,
string pathAccountSid = null,
string apiVersion = null,
string friendlyName = null,
string smsApplicationSid = null,
Twilio.Http.HttpMethod smsFallbackMethod = null,
Uri smsFallbackUrl = null,
Twilio.Http.HttpMethod smsMethod = null,
Uri smsUrl = null,
Uri statusCallback = null,
Twilio.Http.HttpMethod statusCallbackMethod = null,
string voiceApplicationSid = null,
bool? voiceCallerIdLookup = null,
Twilio.Http.HttpMethod voiceFallbackMethod = null,
Uri voiceFallbackUrl = null,
Twilio.Http.HttpMethod voiceMethod = null,
Uri voiceUrl = null,
string identitySid = null,
string addressSid = null,
TollFreeResource.EmergencyStatusEnum emergencyStatus = null,
string emergencyAddressSid = null,
string trunkSid = null,
TollFreeResource.VoiceReceiveModeEnum voiceReceiveMode = null,
string bundleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateTollFreeOptions(phoneNumber){PathAccountSid = pathAccountSid, ApiVersion = apiVersion, FriendlyName = friendlyName, SmsApplicationSid = smsApplicationSid, SmsFallbackMethod = smsFallbackMethod, SmsFallbackUrl = smsFallbackUrl, SmsMethod = smsMethod, SmsUrl = smsUrl, StatusCallback = statusCallback, StatusCallbackMethod = statusCallbackMethod, VoiceApplicationSid = voiceApplicationSid, VoiceCallerIdLookup = voiceCallerIdLookup, VoiceFallbackMethod = voiceFallbackMethod, VoiceFallbackUrl = voiceFallbackUrl, VoiceMethod = voiceMethod, VoiceUrl = voiceUrl, IdentitySid = identitySid, AddressSid = addressSid, EmergencyStatus = emergencyStatus, EmergencyAddressSid = emergencyAddressSid, TrunkSid = trunkSid, VoiceReceiveMode = voiceReceiveMode, BundleSid = bundleSid};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="phoneNumber"> The phone number to purchase in E.164 format </param>
/// <param name="pathAccountSid"> The SID of the Account that will create the resource </param>
/// <param name="apiVersion"> The API version to use for incoming calls made to the new phone number </param>
/// <param name="friendlyName"> A string to describe the new phone number </param>
/// <param name="smsApplicationSid"> The SID of the application to handle SMS messages </param>
/// <param name="smsFallbackMethod"> HTTP method used with sms_fallback_url </param>
/// <param name="smsFallbackUrl"> The URL we call when an error occurs while executing TwiML </param>
/// <param name="smsMethod"> The HTTP method to use with sms_url </param>
/// <param name="smsUrl"> The URL we should call when the new phone number receives an incoming SMS message </param>
/// <param name="statusCallback"> The URL to send status information to your application </param>
/// <param name="statusCallbackMethod"> The HTTP method we should use to call status_callback </param>
/// <param name="voiceApplicationSid"> The SID of the application to handle the new phone number </param>
/// <param name="voiceCallerIdLookup"> Whether to lookup the caller's name </param>
/// <param name="voiceFallbackMethod"> The HTTP method used with voice_fallback_url </param>
/// <param name="voiceFallbackUrl"> The URL we will call when an error occurs in TwiML </param>
/// <param name="voiceMethod"> The HTTP method used with the voice_url </param>
/// <param name="voiceUrl"> The URL we should call when the phone number receives a call </param>
/// <param name="identitySid"> The SID of the Identity resource to associate with the new phone number </param>
/// <param name="addressSid"> The SID of the Address resource associated with the phone number </param>
/// <param name="emergencyStatus"> Displays if emergency calling is enabled for this number. </param>
/// <param name="emergencyAddressSid"> The emergency address configuration to use for emergency calling </param>
/// <param name="trunkSid"> SID of the trunk to handle calls to the new phone number </param>
/// <param name="voiceReceiveMode"> Incoming call type: fax or voice </param>
/// <param name="bundleSid"> The SID of the Bundle resource associated with number </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of TollFree </returns>
public static async System.Threading.Tasks.Task<TollFreeResource> CreateAsync(Types.PhoneNumber phoneNumber,
string pathAccountSid = null,
string apiVersion = null,
string friendlyName = null,
string smsApplicationSid = null,
Twilio.Http.HttpMethod smsFallbackMethod = null,
Uri smsFallbackUrl = null,
Twilio.Http.HttpMethod smsMethod = null,
Uri smsUrl = null,
Uri statusCallback = null,
Twilio.Http.HttpMethod statusCallbackMethod = null,
string voiceApplicationSid = null,
bool? voiceCallerIdLookup = null,
Twilio.Http.HttpMethod voiceFallbackMethod = null,
Uri voiceFallbackUrl = null,
Twilio.Http.HttpMethod voiceMethod = null,
Uri voiceUrl = null,
string identitySid = null,
string addressSid = null,
TollFreeResource.EmergencyStatusEnum emergencyStatus = null,
string emergencyAddressSid = null,
string trunkSid = null,
TollFreeResource.VoiceReceiveModeEnum voiceReceiveMode = null,
string bundleSid = null,
ITwilioRestClient client = null)
{
var options = new CreateTollFreeOptions(phoneNumber){PathAccountSid = pathAccountSid, ApiVersion = apiVersion, FriendlyName = friendlyName, SmsApplicationSid = smsApplicationSid, SmsFallbackMethod = smsFallbackMethod, SmsFallbackUrl = smsFallbackUrl, SmsMethod = smsMethod, SmsUrl = smsUrl, StatusCallback = statusCallback, StatusCallbackMethod = statusCallbackMethod, VoiceApplicationSid = voiceApplicationSid, VoiceCallerIdLookup = voiceCallerIdLookup, VoiceFallbackMethod = voiceFallbackMethod, VoiceFallbackUrl = voiceFallbackUrl, VoiceMethod = voiceMethod, VoiceUrl = voiceUrl, IdentitySid = identitySid, AddressSid = addressSid, EmergencyStatus = emergencyStatus, EmergencyAddressSid = emergencyAddressSid, TrunkSid = trunkSid, VoiceReceiveMode = voiceReceiveMode, BundleSid = bundleSid};
return await CreateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a TollFreeResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> TollFreeResource object represented by the provided JSON </returns>
public static TollFreeResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<TollFreeResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Address resource associated with the phone number
/// </summary>
[JsonProperty("address_sid")]
public string AddressSid { get; private set; }
/// <summary>
/// Whether the phone number requires an Address registered with Twilio.
/// </summary>
[JsonProperty("address_requirements")]
[JsonConverter(typeof(StringEnumConverter))]
public TollFreeResource.AddressRequirementEnum AddressRequirements { get; private set; }
/// <summary>
/// The API version used to start a new TwiML session
/// </summary>
[JsonProperty("api_version")]
public string ApiVersion { get; private set; }
/// <summary>
/// Whether the phone number is new to the Twilio platform
/// </summary>
[JsonProperty("beta")]
public bool? Beta { get; private set; }
/// <summary>
/// Indicate if a phone can receive calls or messages
/// </summary>
[JsonProperty("capabilities")]
public PhoneNumberCapabilities Capabilities { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT that the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT that the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The string that you assigned to describe the resource
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// The SID of the Identity resource associated with number
/// </summary>
[JsonProperty("identity_sid")]
public string IdentitySid { get; private set; }
/// <summary>
/// The phone number in E.164 format
/// </summary>
[JsonProperty("phone_number")]
[JsonConverter(typeof(PhoneNumberConverter))]
public Types.PhoneNumber PhoneNumber { get; private set; }
/// <summary>
/// The phone number's origin. Can be twilio or hosted.
/// </summary>
[JsonProperty("origin")]
public string Origin { get; private set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the application that handles SMS messages sent to the phone number
/// </summary>
[JsonProperty("sms_application_sid")]
public string SmsApplicationSid { get; private set; }
/// <summary>
/// The HTTP method used with sms_fallback_url
/// </summary>
[JsonProperty("sms_fallback_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod SmsFallbackMethod { get; private set; }
/// <summary>
/// The URL that we call when an error occurs while retrieving or executing the TwiML
/// </summary>
[JsonProperty("sms_fallback_url")]
public Uri SmsFallbackUrl { get; private set; }
/// <summary>
/// The HTTP method to use with sms_url
/// </summary>
[JsonProperty("sms_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod SmsMethod { get; private set; }
/// <summary>
/// The URL we call when the phone number receives an incoming SMS message
/// </summary>
[JsonProperty("sms_url")]
public Uri SmsUrl { get; private set; }
/// <summary>
/// The URL to send status information to your application
/// </summary>
[JsonProperty("status_callback")]
public Uri StatusCallback { get; private set; }
/// <summary>
/// The HTTP method we use to call status_callback
/// </summary>
[JsonProperty("status_callback_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod StatusCallbackMethod { get; private set; }
/// <summary>
/// The SID of the Trunk that handles calls to the phone number
/// </summary>
[JsonProperty("trunk_sid")]
public string TrunkSid { get; private set; }
/// <summary>
/// The URI of the resource, relative to `https://api.twilio.com`
/// </summary>
[JsonProperty("uri")]
public string Uri { get; private set; }
/// <summary>
/// The voice_receive_mode
/// </summary>
[JsonProperty("voice_receive_mode")]
[JsonConverter(typeof(StringEnumConverter))]
public TollFreeResource.VoiceReceiveModeEnum VoiceReceiveMode { get; private set; }
/// <summary>
/// The SID of the application that handles calls to the phone number
/// </summary>
[JsonProperty("voice_application_sid")]
public string VoiceApplicationSid { get; private set; }
/// <summary>
/// Whether to lookup the caller's name
/// </summary>
[JsonProperty("voice_caller_id_lookup")]
public bool? VoiceCallerIdLookup { get; private set; }
/// <summary>
/// The HTTP method used with voice_fallback_url
/// </summary>
[JsonProperty("voice_fallback_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod VoiceFallbackMethod { get; private set; }
/// <summary>
/// The URL we call when an error occurs in TwiML
/// </summary>
[JsonProperty("voice_fallback_url")]
public Uri VoiceFallbackUrl { get; private set; }
/// <summary>
/// The HTTP method used with the voice_url
/// </summary>
[JsonProperty("voice_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod VoiceMethod { get; private set; }
/// <summary>
/// The URL we call when the phone number receives a call
/// </summary>
[JsonProperty("voice_url")]
public Uri VoiceUrl { get; private set; }
/// <summary>
/// Displays if emergency calling is enabled for this number.
/// </summary>
[JsonProperty("emergency_status")]
[JsonConverter(typeof(StringEnumConverter))]
public TollFreeResource.EmergencyStatusEnum EmergencyStatus { get; private set; }
/// <summary>
/// The emergency address configuration to use for emergency calling
/// </summary>
[JsonProperty("emergency_address_sid")]
public string EmergencyAddressSid { get; private set; }
/// <summary>
/// State of the emergency address configuration for the phone number
/// </summary>
[JsonProperty("emergency_address_status")]
[JsonConverter(typeof(StringEnumConverter))]
public TollFreeResource.EmergencyAddressStatusEnum EmergencyAddressStatus { get; private set; }
/// <summary>
/// The SID of the Bundle resource associated with number
/// </summary>
[JsonProperty("bundle_sid")]
public string BundleSid { get; private set; }
/// <summary>
/// The status
/// </summary>
[JsonProperty("status")]
public string Status { get; private set; }
private TollFreeResource()
{
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.ComponentModel;
using NLog.Internal;
using JetBrains.Annotations;
#if ASYNC_SUPPORTED
using System.Threading.Tasks;
#endif
/// <summary>
/// Provides logging interface and utility functions.
/// </summary>
[CLSCompliant(true)]
public partial class Logger : ILogger
{
private readonly Type loggerType = typeof(Logger);
private volatile LoggerConfiguration configuration;
private volatile bool isTraceEnabled;
private volatile bool isDebugEnabled;
private volatile bool isInfoEnabled;
private volatile bool isWarnEnabled;
private volatile bool isErrorEnabled;
private volatile bool isFatalEnabled;
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class.
/// </summary>
protected internal Logger()
{
}
/// <summary>
/// Occurs when logger configuration changes.
/// </summary>
public event EventHandler<EventArgs> LoggerReconfigured;
/// <summary>
/// Gets the name of the logger.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets the factory that created this logger.
/// </summary>
public LogFactory Factory { get; private set; }
/// <summary>
/// Gets a value indicating whether logging is enabled for the specified level.
/// </summary>
/// <param name="level">Log level to be checked.</param>
/// <returns>A value of <see langword="true" /> if logging is enabled for the specified level, otherwise it returns <see langword="false" />.</returns>
public bool IsEnabled(LogLevel level)
{
if (level == null)
{
throw new InvalidOperationException("Log level must be defined");
}
return this.GetTargetsForLevel(level) != null;
}
/// <summary>
/// Writes the specified diagnostic message.
/// </summary>
/// <param name="logEvent">Log event.</param>
public void Log(LogEventInfo logEvent)
{
if (this.IsEnabled(logEvent.Level))
{
this.WriteToTargets(logEvent);
}
}
/// <summary>
/// Writes the specified diagnostic message.
/// </summary>
/// <param name="wrapperType">The name of the type that wraps Logger.</param>
/// <param name="logEvent">Log event.</param>
public void Log(Type wrapperType, LogEventInfo logEvent)
{
if (this.IsEnabled(logEvent.Level))
{
this.WriteToTargets(wrapperType, logEvent);
}
}
#region Log() overloads
/// <overloads>
/// Writes the diagnostic message at the specified level using the specified format provider and format parameters.
/// </overloads>
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <typeparam name="T">Type of the value.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="value">The value to be written.</param>
public void Log<T>(LogLevel level, T value)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, null, value);
}
}
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <typeparam name="T">Type of the value.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="value">The value to be written.</param>
public void Log<T>(LogLevel level, IFormatProvider formatProvider, T value)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, formatProvider, value);
}
}
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param>
public void Log(LogLevel level, LogMessageGenerator messageFunc)
{
if (this.IsEnabled(level))
{
if (messageFunc == null)
{
throw new ArgumentNullException("messageFunc");
}
this.WriteToTargets(level, null, messageFunc());
}
}
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="exception">An exception to be logged.</param>
[Obsolete("Use Log(LogLevel, String, Exception) method instead.")]
public void LogException(LogLevel level, [Localizable(false)] string message, Exception exception)
{
this.Log(level, message, exception);
}
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters and formatting them with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing format items.</param>
/// <param name="args">Arguments to format.</param>
[StringFormatMethod("message")]
public void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, params object[] args)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, formatProvider, message, args);
}
}
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">Log message.</param>
public void Log(LogLevel level, [Localizable(false)] string message)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, null, message);
}
}
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing format items.</param>
/// <param name="args">Arguments to format.</param>
public void Log(LogLevel level, [Localizable(false)] string message, params object[] args)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, message, args);
}
}
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="exception">An exception to be logged.</param>
[Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args)")]
public void Log(LogLevel level, [Localizable(false)] string message, Exception exception)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, message, exception);
}
}
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="args">Arguments to format.</param>
/// <param name="exception">An exception to be logged.</param>
public void Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, exception, message, args);
}
}
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="args">Arguments to format.</param>
/// <param name="exception">An exception to be logged.</param>
public void Log(LogLevel level, Exception exception, IFormatProvider formatProvider, [Localizable(false)] string message, params object[] args)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, exception, formatProvider, message, args);
}
}
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameter and formatting it with the supplied format provider.
/// </summary>
/// <typeparam name="TArgument">The type of the argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[StringFormatMethod("message")]
public void Log<TArgument>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument argument)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, formatProvider, message, new object[] { argument });
}
}
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameter.
/// </summary>
/// <typeparam name="TArgument">The type of the argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[StringFormatMethod("message")]
public void Log<TArgument>(LogLevel level, [Localizable(false)] string message, TArgument argument)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, message, new object[] { argument });
}
}
/// <summary>
/// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
public void Log<TArgument1, TArgument2>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, formatProvider, message, new object[] { argument1, argument2 });
}
}
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
[StringFormatMethod("message")]
public void Log<TArgument1, TArgument2>(LogLevel level, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, message, new object[] { argument1, argument2 });
}
}
/// <summary>
/// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <typeparam name="TArgument3">The type of the third argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
/// <param name="argument3">The third argument to format.</param>
public void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, formatProvider, message, new object[] { argument1, argument2, argument3 });
}
}
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <typeparam name="TArgument3">The type of the third argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
/// <param name="argument3">The third argument to format.</param>
[StringFormatMethod("message")]
public void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, [Localizable(false)] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3)
{
if (this.IsEnabled(level))
{
this.WriteToTargets(level, message, new object[] { argument1, argument2, argument3 });
}
}
internal void WriteToTargets(LogLevel level, Exception ex, [Localizable(false)] string message, object[] args)
{
LoggerImpl.Write(this.loggerType, this.GetTargetsForLevel(level), PrepareLogEventInfo(LogEventInfo.Create(level, this.Name, ex, this.Factory.DefaultCultureInfo, message, args)), this.Factory);
}
internal void WriteToTargets(LogLevel level, Exception ex, IFormatProvider formatProvider, [Localizable(false)] string message, object[] args)
{
LoggerImpl.Write(this.loggerType, this.GetTargetsForLevel(level), PrepareLogEventInfo(LogEventInfo.Create(level, this.Name, ex, formatProvider, message, args)), this.Factory);
}
private LogEventInfo PrepareLogEventInfo(LogEventInfo logEvent)
{
if (logEvent.FormatProvider == null)
{
logEvent.FormatProvider = this.Factory.DefaultCultureInfo;
}
return logEvent;
}
#endregion
/// <summary>
/// Runs the provided action. If the action throws, the exception is logged at <c>Error</c> level. The exception is not propagated outside of this method.
/// </summary>
/// <param name="action">Action to execute.</param>
public void Swallow(Action action)
{
try
{
action();
}
catch (Exception e)
{
Error(e);
}
}
/// <summary>
/// Runs the provided function and returns its result. If an exception is thrown, it is logged at <c>Error</c> level.
/// The exception is not propagated outside of this method; a default value is returned instead.
/// </summary>
/// <typeparam name="T">Return type of the provided function.</typeparam>
/// <param name="func">Function to run.</param>
/// <returns>Result returned by the provided function or the default value of type <typeparamref name="T"/> in case of exception.</returns>
public T Swallow<T>(Func<T> func)
{
return Swallow(func, default(T));
}
/// <summary>
/// Runs the provided function and returns its result. If an exception is thrown, it is logged at <c>Error</c> level.
/// The exception is not propagated outside of this method; a fallback value is returned instead.
/// </summary>
/// <typeparam name="T">Return type of the provided function.</typeparam>
/// <param name="func">Function to run.</param>
/// <param name="fallback">Fallback value to return in case of exception.</param>
/// <returns>Result returned by the provided function or fallback value in case of exception.</returns>
public T Swallow<T>(Func<T> func, T fallback)
{
try
{
return func();
}
catch (Exception e)
{
Error(e);
return fallback;
}
}
#if ASYNC_SUPPORTED
/// <summary>
/// Logs an exception is logged at <c>Error</c> level if the provided task does not run to completion.
/// </summary>
/// <param name="task">The task for which to log an error if it does not run to completion.</param>
/// <remarks>This method is useful in fire-and-forget situations, where application logic does not depend on completion of task. This method is avoids C# warning CS4014 in such situations.</remarks>
public async void Swallow(Task task)
{
try
{
await task;
}
catch (Exception e)
{
Error(e);
}
}
/// <summary>
/// Returns a task that completes when a specified task to completes. If the task does not run to completion, an exception is logged at <c>Error</c> level. The returned task always runs to completion.
/// </summary>
/// <param name="task">The task for which to log an error if it does not run to completion.</param>
/// <returns>A task that completes in the <see cref="TaskStatus.RanToCompletion"/> state when <paramref name="task"/> completes.</returns>
public async Task SwallowAsync(Task task)
{
try
{
await task;
}
catch (Exception e)
{
Error(e);
}
}
/// <summary>
/// Runs async action. If the action throws, the exception is logged at <c>Error</c> level. The exception is not propagated outside of this method.
/// </summary>
/// <param name="asyncAction">Async action to execute.</param>
public async Task SwallowAsync(Func<Task> asyncAction)
{
try
{
await asyncAction();
}
catch (Exception e)
{
Error(e);
}
}
/// <summary>
/// Runs the provided async function and returns its result. If the task does not run to completion, an exception is logged at <c>Error</c> level.
/// The exception is not propagated outside of this method; a default value is returned instead.
/// </summary>
/// <typeparam name="TResult">Return type of the provided function.</typeparam>
/// <param name="asyncFunc">Async function to run.</param>
/// <returns>A task that represents the completion of the supplied task. If the supplied task ends in the <see cref="TaskStatus.RanToCompletion"/> state, the result of the new task will be the result of the supplied task; otherwise, the result of the new task will be the default value of type <typeparamref name="TResult"/>.</returns>
public async Task<TResult> SwallowAsync<TResult>(Func<Task<TResult>> asyncFunc)
{
return await SwallowAsync(asyncFunc, default(TResult));
}
/// <summary>
/// Runs the provided async function and returns its result. If the task does not run to completion, an exception is logged at <c>Error</c> level.
/// The exception is not propagated outside of this method; a fallback value is returned instead.
/// </summary>
/// <typeparam name="TResult">Return type of the provided function.</typeparam>
/// <param name="asyncFunc">Async function to run.</param>
/// <param name="fallback">Fallback value to return if the task does not end in the <see cref="TaskStatus.RanToCompletion"/> state.</param>
/// <returns>A task that represents the completion of the supplied task. If the supplied task ends in the <see cref="TaskStatus.RanToCompletion"/> state, the result of the new task will be the result of the supplied task; otherwise, the result of the new task will be the fallback value.</returns>
public async Task<TResult> SwallowAsync<TResult>(Func<Task<TResult>> asyncFunc, TResult fallback)
{
try
{
return await asyncFunc();
}
catch (Exception e)
{
Error(e);
return fallback;
}
}
#endif
internal void Initialize(string name, LoggerConfiguration loggerConfiguration, LogFactory factory)
{
this.Name = name;
this.Factory = factory;
this.SetConfiguration(loggerConfiguration);
}
internal void WriteToTargets(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message, object[] args)
{
LoggerImpl.Write(this.loggerType, this.GetTargetsForLevel(level), PrepareLogEventInfo(LogEventInfo.Create(level, this.Name, formatProvider, message, args)), this.Factory);
}
internal void WriteToTargets(LogLevel level, IFormatProvider formatProvider, [Localizable(false)] string message)
{
// please note that this overload calls the overload of LogEventInfo.Create with object[] parameter on purpose -
// to avoid unnecessary string.Format (in case of calling Create(LogLevel, string, IFormatProvider, object))
var logEvent = LogEventInfo.Create(level, this.Name, formatProvider, message, (object[])null);
LoggerImpl.Write(this.loggerType, this.GetTargetsForLevel(level), PrepareLogEventInfo(logEvent), this.Factory);
}
internal void WriteToTargets<T>(LogLevel level, IFormatProvider formatProvider, T value)
{
var logEvent = PrepareLogEventInfo(LogEventInfo.Create(level, this.Name, formatProvider, value));
var ex = value as Exception;
if (ex != null)
{
//also record exception
logEvent.Exception = ex;
}
LoggerImpl.Write(this.loggerType, this.GetTargetsForLevel(level), logEvent, this.Factory);
}
[Obsolete("Use WriteToTargets(Exception ex, LogLevel level, IFormatProvider formatProvider, string message, object[] args) method instead.")]
internal void WriteToTargets(LogLevel level, [Localizable(false)] string message, Exception ex)
{
LoggerImpl.Write(this.loggerType, this.GetTargetsForLevel(level), PrepareLogEventInfo(LogEventInfo.Create(level, this.Name, message, ex)), this.Factory);
}
internal void WriteToTargets(LogLevel level, [Localizable(false)] string message, object[] args)
{
this.WriteToTargets(level, this.Factory.DefaultCultureInfo, message, args);
}
internal void WriteToTargets(LogEventInfo logEvent)
{
LoggerImpl.Write(this.loggerType, this.GetTargetsForLevel(logEvent.Level), PrepareLogEventInfo(logEvent), this.Factory);
}
internal void WriteToTargets(Type wrapperType, LogEventInfo logEvent)
{
LoggerImpl.Write(wrapperType ?? this.loggerType, this.GetTargetsForLevel(logEvent.Level), PrepareLogEventInfo(logEvent), this.Factory);
}
internal void SetConfiguration(LoggerConfiguration newConfiguration)
{
this.configuration = newConfiguration;
// pre-calculate 'enabled' flags
this.isTraceEnabled = newConfiguration.IsEnabled(LogLevel.Trace);
this.isDebugEnabled = newConfiguration.IsEnabled(LogLevel.Debug);
this.isInfoEnabled = newConfiguration.IsEnabled(LogLevel.Info);
this.isWarnEnabled = newConfiguration.IsEnabled(LogLevel.Warn);
this.isErrorEnabled = newConfiguration.IsEnabled(LogLevel.Error);
this.isFatalEnabled = newConfiguration.IsEnabled(LogLevel.Fatal);
var loggerReconfiguredDelegate = this.LoggerReconfigured;
if (loggerReconfiguredDelegate != null)
{
loggerReconfiguredDelegate(this, new EventArgs());
}
}
private TargetWithFilterChain GetTargetsForLevel(LogLevel level)
{
return this.configuration.GetTargetsForLevel(level);
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class RoundRobinGroupTargetTests : NLogTestBase
{
[Fact]
public void RoundRobinGroupTargetSyncTest1()
{
var myTarget1 = new MyTarget();
var myTarget2 = new MyTarget();
var myTarget3 = new MyTarget();
var wrapper = new RoundRobinGroupTarget()
{
Targets = { myTarget1, myTarget2, myTarget3 },
};
myTarget1.Initialize(null);
myTarget2.Initialize(null);
myTarget3.Initialize(null);
wrapper.Initialize(null);
List<Exception> exceptions = new List<Exception>();
// no exceptions
for (int i = 0; i < 10; ++i)
{
wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
}
Assert.Equal(10, exceptions.Count);
foreach (var e in exceptions)
{
Assert.Null(e);
}
Assert.Equal(4, myTarget1.WriteCount);
Assert.Equal(3, myTarget2.WriteCount);
Assert.Equal(3, myTarget3.WriteCount);
Exception flushException = null;
var flushHit = new ManualResetEvent(false);
wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });
flushHit.WaitOne();
if (flushException != null)
{
Assert.True(false, flushException.ToString());
}
Assert.Equal(1, myTarget1.FlushCount);
Assert.Equal(1, myTarget2.FlushCount);
Assert.Equal(1, myTarget3.FlushCount);
}
[Fact]
public void RoundRobinGroupTargetSyncTest2()
{
var wrapper = new RoundRobinGroupTarget()
{
// empty target list
};
wrapper.Initialize(null);
List<Exception> exceptions = new List<Exception>();
// no exceptions
for (int i = 0; i < 10; ++i)
{
wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
}
Assert.Equal(10, exceptions.Count);
foreach (var e in exceptions)
{
Assert.Null(e);
}
Exception flushException = null;
var flushHit = new ManualResetEvent(false);
wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });
flushHit.WaitOne();
if (flushException != null)
{
Assert.True(false, flushException.ToString());
}
}
public class MyAsyncTarget : Target
{
public int FlushCount { get; private set; }
public int WriteCount { get; private set; }
public MyAsyncTarget() : base()
{
}
public MyAsyncTarget(string name) : this()
{
Name = name;
}
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Assert.True(FlushCount <= WriteCount);
WriteCount++;
ThreadPool.QueueUserWorkItem(
s =>
{
if (ThrowExceptions)
{
logEvent.Continuation(new InvalidOperationException("Some problem!"));
logEvent.Continuation(new InvalidOperationException("Some problem!"));
}
else
{
logEvent.Continuation(null);
logEvent.Continuation(null);
}
});
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
FlushCount++;
ThreadPool.QueueUserWorkItem(
s => asyncContinuation(null));
}
public bool ThrowExceptions { get; set; }
}
class MyTarget : Target
{
public int FlushCount { get; set; }
public int WriteCount { get; set; }
public int FailCounter { get; set; }
public MyTarget() : base()
{
}
public MyTarget(string name) : this()
{
Name = name;
}
protected override void Write(LogEventInfo logEvent)
{
Assert.True(FlushCount <= WriteCount);
WriteCount++;
if (FailCounter > 0)
{
FailCounter--;
throw new InvalidOperationException("Some failure.");
}
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
FlushCount++;
asyncContinuation(null);
}
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEngine.Serialization;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus
{
/// <summary>
/// Execution state of a Block.
/// </summary>
public enum ExecutionState
{
/// <summary> No command executing </summary>
Idle,
/// <summary> Executing a command </summary>
Executing,
}
/// <summary>
/// A container for a sequence of Fungus comands.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(Flowchart))]
[AddComponentMenu("")]
public class Block : Node
{
[SerializeField] protected int itemId = -1; // Invalid flowchart item id
[FormerlySerializedAs("sequenceName")]
[Tooltip("The name of the block node as displayed in the Flowchart window")]
[SerializeField] protected string blockName = "New Block";
[TextArea(2, 5)]
[Tooltip("Description text to display under the block node")]
[SerializeField] protected string description = "";
[Tooltip("An optional Event Handler which can execute the block when an event occurs")]
[SerializeField] protected EventHandler eventHandler;
[SerializeField] protected List<Command> commandList = new List<Command>();
protected ExecutionState executionState;
protected Command activeCommand;
protected Action lastOnCompleteAction;
/// <summary>
// Index of last command executed before the current one.
// -1 indicates no previous command.
/// </summary>
protected int previousActiveCommandIndex = -1;
protected int jumpToCommandIndex = -1;
protected int executionCount;
protected bool executionInfoSet = false;
protected virtual void Awake()
{
SetExecutionInfo();
}
/// <summary>
/// Populate the command metadata used to control execution.
/// </summary>
protected virtual void SetExecutionInfo()
{
// Give each child command a reference back to its parent block
// and tell each command its index in the list.
int index = 0;
for (int i = 0; i < commandList.Count; i++)
{
var command = commandList[i];
if (command == null)
{
continue;
}
command.ParentBlock = this;
command.CommandIndex = index++;
}
// Ensure all commands are at their correct indent level
// This should have already happened in the editor, but may be necessary
// if commands are added to the Block at runtime.
UpdateIndentLevels();
executionInfoSet = true;
}
#if UNITY_EDITOR
// The user can modify the command list order while playing in the editor,
// so we keep the command indices updated every frame. There's no need to
// do this in player builds so we compile this bit out for those builds.
protected virtual void Update()
{
int index = 0;
for (int i = 0; i < commandList.Count; i++)
{
var command = commandList[i];
if (command == null)// Null entry will be deleted automatically later
{
continue;
}
command.CommandIndex = index++;
}
}
#endif
//editor only state for speeding up flowchart window drawing
public bool IsSelected { get; set; } //local cache of selectedness
public bool IsFiltered { get; set; } //local cache of filteredness
public bool IsControlSelected { get; set; } //local cache of being part of the control exclusion group
#region Public members
/// <summary>
/// The execution state of the Block.
/// </summary>
public virtual ExecutionState State { get { return executionState; } }
/// <summary>
/// Unique identifier for the Block.
/// </summary>
public virtual int ItemId { get { return itemId; } set { itemId = value; } }
/// <summary>
/// The name of the block node as displayed in the Flowchart window.
/// </summary>
public virtual string BlockName { get { return blockName; } set { blockName = value; } }
/// <summary>
/// Description text to display under the block node
/// </summary>
public virtual string Description { get { return description; } }
/// <summary>
/// An optional Event Handler which can execute the block when an event occurs.
/// Note: Using the concrete class instead of the interface here because of weird editor behaviour.
/// </summary>
public virtual EventHandler _EventHandler { get { return eventHandler; } set { eventHandler = value; } }
/// <summary>
/// The currently executing command.
/// </summary>
public virtual Command ActiveCommand { get { return activeCommand; } }
/// <summary>
/// Timer for fading Block execution icon.
/// </summary>
public virtual float ExecutingIconTimer { get; set; }
/// <summary>
/// The list of commands in the sequence.
/// </summary>
public virtual List<Command> CommandList { get { return commandList; } }
/// <summary>
/// Controls the next command to execute in the block execution coroutine.
/// </summary>
public virtual int JumpToCommandIndex { set { jumpToCommandIndex = value; } }
/// <summary>
/// Returns the parent Flowchart for this Block.
/// </summary>
public virtual Flowchart GetFlowchart()
{
return GetComponent<Flowchart>();
}
/// <summary>
/// Returns true if the Block is executing a command.
/// </summary>
public virtual bool IsExecuting()
{
return (executionState == ExecutionState.Executing);
}
/// <summary>
/// Returns the number of times this Block has executed.
/// </summary>
public virtual int GetExecutionCount()
{
return executionCount;
}
/// <summary>
/// Start a coroutine which executes all commands in the Block. Only one running instance of each Block is permitted.
/// </summary>
public virtual void StartExecution()
{
StartCoroutine(Execute());
}
/// <summary>
/// A coroutine method that executes all commands in the Block. Only one running instance of each Block is permitted.
/// </summary>
/// <param name="commandIndex">Index of command to start execution at</param>
/// <param name="onComplete">Delegate function to call when execution completes</param>
public virtual IEnumerator Execute(int commandIndex = 0, Action onComplete = null)
{
if (executionState != ExecutionState.Idle)
{
Debug.LogWarning(BlockName + " cannot be executed, it is already running.");
yield break;
}
lastOnCompleteAction = onComplete;
if (!executionInfoSet)
{
SetExecutionInfo();
}
executionCount++;
var executionCountAtStart = executionCount;
var flowchart = GetFlowchart();
executionState = ExecutionState.Executing;
BlockSignals.DoBlockStart(this);
#if UNITY_EDITOR
// Select the executing block & the first command
flowchart.SelectedBlock = this;
if (commandList.Count > 0)
{
flowchart.ClearSelectedCommands();
flowchart.AddSelectedCommand(commandList[0]);
}
#endif
jumpToCommandIndex = commandIndex;
int i = 0;
while (true)
{
// Executing commands specify the next command to skip to by setting jumpToCommandIndex using Command.Continue()
if (jumpToCommandIndex > -1)
{
i = jumpToCommandIndex;
jumpToCommandIndex = -1;
}
// Skip disabled commands, comments and labels
while (i < commandList.Count &&
(!commandList[i].enabled ||
commandList[i].GetType() == typeof(Comment) ||
commandList[i].GetType() == typeof(Label)))
{
i = commandList[i].CommandIndex + 1;
}
if (i >= commandList.Count)
{
break;
}
// The previous active command is needed for if / else / else if commands
if (activeCommand == null)
{
previousActiveCommandIndex = -1;
}
else
{
previousActiveCommandIndex = activeCommand.CommandIndex;
}
var command = commandList[i];
activeCommand = command;
if (flowchart.IsActive())
{
// Auto select a command in some situations
if ((flowchart.SelectedCommands.Count == 0 && i == 0) ||
(flowchart.SelectedCommands.Count == 1 && flowchart.SelectedCommands[0].CommandIndex == previousActiveCommandIndex))
{
flowchart.ClearSelectedCommands();
flowchart.AddSelectedCommand(commandList[i]);
}
}
command.IsExecuting = true;
// This icon timer is managed by the FlowchartWindow class, but we also need to
// set it here in case a command starts and finishes execution before the next window update.
command.ExecutingIconTimer = Time.realtimeSinceStartup + FungusConstants.ExecutingIconFadeTime;
BlockSignals.DoCommandExecute(this, command, i, commandList.Count);
command.Execute();
// Wait until the executing command sets another command to jump to via Command.Continue()
while (jumpToCommandIndex == -1)
{
yield return null;
}
#if UNITY_EDITOR
if (flowchart.StepPause > 0f)
{
yield return new WaitForSeconds(flowchart.StepPause);
}
#endif
command.IsExecuting = false;
}
if(State == ExecutionState.Executing &&
//ensure we aren't dangling from a previous stopage and stopping a future run
executionCountAtStart == executionCount)
{
ReturnToIdle();
}
}
private void ReturnToIdle()
{
executionState = ExecutionState.Idle;
activeCommand = null;
BlockSignals.DoBlockEnd(this);
if (lastOnCompleteAction != null)
{
lastOnCompleteAction();
}
lastOnCompleteAction = null;
}
/// <summary>
/// Stop executing commands in this Block.
/// </summary>
public virtual void Stop()
{
// Tell the executing command to stop immediately
if (activeCommand != null)
{
activeCommand.IsExecuting = false;
activeCommand.OnStopExecuting();
}
// This will cause the execution loop to break on the next iteration
jumpToCommandIndex = int.MaxValue;
//force idle here so other commands that rely on block not executing are informed this frame rather than next
ReturnToIdle();
}
/// <summary>
/// Returns a list of all Blocks connected to this one.
/// </summary>
public virtual List<Block> GetConnectedBlocks()
{
var connectedBlocks = new List<Block>();
for (int i = 0; i < commandList.Count; i++)
{
var command = commandList[i];
if (command != null)
{
command.GetConnectedBlocks(ref connectedBlocks);
}
}
return connectedBlocks;
}
/// <summary>
/// Returns the type of the previously executing command.
/// </summary>
/// <returns>The previous active command type.</returns>
public virtual System.Type GetPreviousActiveCommandType()
{
if (previousActiveCommandIndex >= 0 &&
previousActiveCommandIndex < commandList.Count)
{
return commandList[previousActiveCommandIndex].GetType();
}
return null;
}
public virtual int GetPreviousActiveCommandIndent()
{
if (previousActiveCommandIndex >= 0 &&
previousActiveCommandIndex < commandList.Count)
{
return commandList[previousActiveCommandIndex].IndentLevel;
}
return -1;
}
/// <summary>
/// Recalculate the indent levels for all commands in the list.
/// </summary>
public virtual void UpdateIndentLevels()
{
int indentLevel = 0;
for (int i = 0; i < commandList.Count; i++)
{
var command = commandList[i];
if (command == null)
{
continue;
}
if (command.CloseBlock())
{
indentLevel--;
}
// Negative indent level is not permitted
indentLevel = Math.Max(indentLevel, 0);
command.IndentLevel = indentLevel;
if (command.OpenBlock())
{
indentLevel++;
}
}
}
/// <summary>
/// Returns the index of the Label command with matching key, or -1 if not found.
/// </summary>
public virtual int GetLabelIndex(string labelKey)
{
if (labelKey.Length == 0)
{
return -1;
}
for (int i = 0; i < commandList.Count; i++)
{
var command = commandList[i];
var labelCommand = command as Label;
if (labelCommand != null && String.Compare(labelCommand.Key, labelKey, true) == 0)
{
return i;
}
}
return -1;
}
#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.Diagnostics;
using System.Runtime.InteropServices;
using CryptographicException = System.Security.Cryptography.CryptographicException;
using SafeBCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeBCryptKeyHandle;
using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle;
using X509KeyUsageFlags = System.Security.Cryptography.X509Certificates.X509KeyUsageFlags;
using SafeNCryptKeyHandle = Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
public static partial class crypt32
{
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
out CertEncodingType pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
out FormatType pdwFormatType,
out SafeCertStoreHandle phCertStore,
out SafeCryptMsgHandle phMsg,
out SafeCertContextHandle ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
IntPtr phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
out SafeCertStoreHandle phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] byte[] pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] out CRYPTOAPI_BLOB pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertGetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, [Out] out IntPtr pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetCertificateContextProperty")]
public static extern unsafe bool CertGetCertificateContextPropertyString(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, byte* pvData, ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPTOAPI_BLOB* pvData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] CRYPT_KEY_PROV_INFO* pvData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertSetCertificateContextProperty(SafeCertContextHandle pCertContext, CertContextPropId dwPropId, CertSetPropertyFlags dwFlags, [In] SafeNCryptKeyHandle keyHandle);
public static unsafe string CertGetNameString(
SafeCertContextHandle certContext,
CertNameType certNameType,
CertNameFlags certNameFlags,
CertNameStringType strType)
{
int cchCount = CertGetNameString(certContext, certNameType, certNameFlags, strType, null, 0);
if (cchCount == 0)
{
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
Span<char> buffer = cchCount <= 256 ? stackalloc char[cchCount] : new char[cchCount];
fixed (char* ptr = &MemoryMarshal.GetReference(buffer))
{
if (CertGetNameString(certContext, certNameType, certNameFlags, strType, ptr, cchCount) == 0)
{
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
Debug.Assert(buffer[cchCount - 1] == '\0');
return new string(buffer.Slice(0, cchCount - 1));
}
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertGetNameStringW")]
private static extern unsafe int CertGetNameString(SafeCertContextHandle pCertContext, CertNameType dwType, CertNameFlags dwFlags, in CertNameStringType pvTypePara, char* pszNameString, int cchNameString);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeCertContextHandle CertDuplicateCertificateContext(IntPtr pCertContext);
[DllImport(Libraries.Crypt32, SetLastError = true)]
public static extern SafeX509ChainHandle CertDuplicateCertificateChain(IntPtr pChainContext);
[DllImport(Libraries.Crypt32, SetLastError = true)]
internal static extern SafeCertStoreHandle CertDuplicateStore(IntPtr hCertStore);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertDuplicateCertificateContext")]
public static extern SafeCertContextHandleWithKeyContainerDeletion CertDuplicateCertificateContextWithKeyContainerDeletion(IntPtr pCertContext);
public static SafeCertStoreHandle CertOpenStore(CertStoreProvider lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, string pvPara)
{
return CertOpenStore((IntPtr)lpszStoreProvider, dwMsgAndCertEncodingType, hCryptProv, dwFlags, pvPara);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeCertStoreHandle CertOpenStore(IntPtr lpszStoreProvider, CertEncodingType dwMsgAndCertEncodingType, IntPtr hCryptProv, CertStoreFlags dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pvPara);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertAddCertificateContextToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertAddCertificateLinkToStore(SafeCertStoreHandle hCertStore, SafeCertContextHandle pCertContext, CertStoreAddDisposition dwAddDisposition, IntPtr ppStoreContext);
/// <summary>
/// A less error-prone wrapper for CertEnumCertificatesInStore().
///
/// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with
/// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle
/// and returns "false" to indicate the end of the store has been reached.
/// </summary>
public static bool CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, ref SafeCertContextHandle pCertContext)
{
unsafe
{
CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect();
pCertContext = CertEnumCertificatesInStore(hCertStore, pPrevCertContext);
return !pCertContext.IsInvalid;
}
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe SafeCertContextHandle CertEnumCertificatesInStore(SafeCertStoreHandle hCertStore, CERT_CONTEXT* pPrevCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeCertStoreHandle PFXImportCertStore([In] ref CRYPTOAPI_BLOB pPFX, SafePasswordHandle password, PfxCertStoreFlags dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, byte* pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptMsgGetParam(SafeCryptMsgHandle hCryptMsg, CryptMessageParameterType dwParamType, int dwIndex, out int pvData, [In, Out] ref int pcbData);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertSerializeCertificateStoreElement(SafeCertContextHandle pCertContext, int dwFlags, [Out] byte[] pbElement, [In, Out] ref int pcbElement);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool PFXExportCertStore(SafeCertStoreHandle hStore, [In, Out] ref CRYPTOAPI_BLOB pPFX, SafePasswordHandle szPassword, PFXExportFlags dwFlags);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CertStrToNameW")]
public static extern bool CertStrToName(CertEncodingType dwCertEncodingType, string pszX500, CertNameStrTypeAndFlags dwStrType, IntPtr pvReserved, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded, IntPtr ppszError);
public static bool CryptDecodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, byte[] pvStructInfo, ref int pcbStructInfo)
{
return CryptDecodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CryptDecodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] byte[] pvStructInfo, [In, Out] ref int pcbStructInfo);
public static unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, void* pvStructInfo, ref int pcbStructInfo)
{
return CryptDecodeObjectPointer(dwCertEncodingType, (IntPtr)lpszStructType, pbEncoded, cbEncoded, dwFlags, pvStructInfo, ref pcbStructInfo);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")]
private static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CryptDecodeObject")]
public static extern unsafe bool CryptDecodeObjectPointer(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] string lpszStructType, [In] byte[] pbEncoded, int cbEncoded, CryptDecodeObjectFlags dwFlags, [Out] void* pvStructInfo, [In, Out] ref int pcbStructInfo);
public static unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, CryptDecodeObjectStructType lpszStructType, void* pvStructInfo, byte[] pbEncoded, ref int pcbEncoded)
{
return CryptEncodeObject(dwCertEncodingType, (IntPtr)lpszStructType, pvStructInfo, pbEncoded, ref pcbEncoded);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, IntPtr lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptEncodeObject(CertEncodingType dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)] string lpszStructType, void* pvStructInfo, [Out] byte[] pbEncoded, [In, Out] ref int pcbEncoded);
public static unsafe byte[] EncodeObject(CryptDecodeObjectStructType lpszStructType, void* decoded)
{
int cb = 0;
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
byte[] encoded = new byte[cb];
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
return encoded;
}
public static unsafe byte[] EncodeObject(string lpszStructType, void* decoded)
{
int cb = 0;
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, null, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
byte[] encoded = new byte[cb];
if (!Interop.crypt32.CryptEncodeObject(CertEncodingType.All, lpszStructType, decoded, encoded, ref cb))
throw Marshal.GetLastWin32Error().ToCryptographicException();
return encoded;
}
internal static SafeChainEngineHandle CertCreateCertificateChainEngine(ref CERT_CHAIN_ENGINE_CONFIG config)
{
if (!CertCreateCertificateChainEngine(ref config, out SafeChainEngineHandle chainEngineHandle))
{
int errorCode = Marshal.GetLastWin32Error();
throw errorCode.ToCryptographicException();
}
return chainEngineHandle;
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CertCreateCertificateChainEngine(ref CERT_CHAIN_ENGINE_CONFIG pConfig, out SafeChainEngineHandle hChainEngineHandle);
[DllImport(Libraries.Crypt32)]
public static extern void CertFreeCertificateChainEngine(IntPtr hChainEngine);
[DllImport(Libraries.Crypt32, SetLastError = true)]
public static extern unsafe bool CertGetCertificateChain(IntPtr hChainEngine, SafeCertContextHandle pCertContext, FILETIME* pTime, SafeCertStoreHandle hStore, [In] ref CERT_CHAIN_PARA pChainPara, CertChainFlags dwFlags, IntPtr pvReserved, out SafeX509ChainHandle ppChainContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptHashPublicKeyInfo(IntPtr hCryptProv, int algId, int dwFlags, CertEncodingType dwCertEncodingType, [In] ref CERT_PUBLIC_KEY_INFO pInfo, [Out] byte[] pbComputedHash, [In, Out] ref int pcbComputedHash);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertSaveStore(SafeCertStoreHandle hCertStore, CertEncodingType dwMsgAndCertEncodingType, CertStoreSaveAs dwSaveAs, CertStoreSaveTo dwSaveTo, ref CRYPTOAPI_BLOB pvSaveToPara, int dwFlags);
/// <summary>
/// A less error-prone wrapper for CertEnumCertificatesInStore().
///
/// To begin the enumeration, set pCertContext to null. Each iteration replaces pCertContext with
/// the next certificate in the iteration. The final call sets pCertContext to an invalid SafeCertStoreHandle
/// and returns "false" to indicate the end of the store has been reached.
/// </summary>
public static unsafe bool CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertFindType dwFindType, void* pvFindPara, ref SafeCertContextHandle pCertContext)
{
CERT_CONTEXT* pPrevCertContext = pCertContext == null ? null : pCertContext.Disconnect();
pCertContext = CertFindCertificateInStore(hCertStore, CertEncodingType.All, CertFindFlags.None, dwFindType, pvFindPara, pPrevCertContext);
return !pCertContext.IsInvalid;
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern unsafe SafeCertContextHandle CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertEncodingType dwCertEncodingType, CertFindFlags dwFindFlags, CertFindType dwFindType, void* pvFindPara, CERT_CONTEXT* pPrevCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe int CertVerifyTimeValidity([In] ref FILETIME pTimeToVerify, [In] CERT_INFO* pCertInfo);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe CERT_EXTENSION* CertFindExtension([MarshalAs(UnmanagedType.LPStr)] string pszObjId, int cExtensions, CERT_EXTENSION* rgExtensions);
// Note: It's somewhat unusual to use an API enum as a parameter type to a P/Invoke but in this case, X509KeyUsageFlags was intentionally designed as bit-wise
// identical to the wincrypt CERT_*_USAGE values.
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertGetIntendedKeyUsage(CertEncodingType dwCertEncodingType, CERT_INFO* pCertInfo, out X509KeyUsageFlags pbKeyUsage, int cbKeyUsage);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertGetValidUsages(int cCerts, [In] ref SafeCertContextHandle rghCerts, out int cNumOIDs, [Out] void* rghOIDs, [In, Out] ref int pcbOIDs);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CertControlStore(SafeCertStoreHandle hCertStore, CertControlStoreFlags dwFlags, CertControlStoreType dwControlType, IntPtr pvCtrlPara);
// Note: CertDeleteCertificateFromStore always calls CertFreeCertificateContext on pCertContext, even if an error is encountered.
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CertDeleteCertificateFromStore(CERT_CONTEXT* pCertContext);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern void CertFreeCertificateChain(IntPtr pChainContext);
public static bool CertVerifyCertificateChainPolicy(ChainPolicy pszPolicyOID, SafeX509ChainHandle pChainContext, ref CERT_CHAIN_POLICY_PARA pPolicyPara, ref CERT_CHAIN_POLICY_STATUS pPolicyStatus)
{
return CertVerifyCertificateChainPolicy((IntPtr)pszPolicyOID, pChainContext, ref pPolicyPara, ref pPolicyStatus);
}
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CertVerifyCertificateChainPolicy(IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, [In] ref CERT_CHAIN_POLICY_PARA pPolicyPara, [In, Out] ref CERT_CHAIN_POLICY_STATUS pPolicyStatus);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptImportPublicKeyInfoEx2(CertEncodingType dwCertEncodingType, CERT_PUBLIC_KEY_INFO* pInfo, int dwFlags, void* pvAuxInfo, out SafeBCryptKeyHandle phKey);
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptAcquireCertificatePrivateKey(SafeCertContextHandle pCert, CryptAcquireFlags dwFlags, IntPtr pvParameters, out SafeNCryptKeyHandle phCryptProvOrNCryptKey, out int pdwKeySpec, out bool pfCallerFreeProvOrNCryptKey);
}
}
| |
//! \file ImagePT1.cs
//! \date Wed Apr 15 15:17:24 2015
//! \brief FFA System image format implementation.
//
// 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 System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Utility;
namespace GameRes.Formats.Ffa
{
internal class Pt1MetaData : ImageMetaData
{
public int Type;
public uint PackedSize;
public uint UnpackedSize;
}
[Export(typeof(ImageFormat))]
public class Pt1Format : ImageFormat
{
public override string Tag { get { return "PT1"; } }
public override string Description { get { return "FFA System RGB image format"; } }
public override uint Signature { get { return 2u; } }
public Pt1Format ()
{
Signatures = new uint[] { 3, 2, 1, 0 };
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("Pt1Format.Write not implemented");
}
public override ImageMetaData ReadMetaData (Stream stream)
{
using (var input = new ArcView.Reader (stream))
{
int type = input.ReadInt32();
if (type < 0 || type > 3)
return null;
if (-1 != input.ReadInt32())
return null;
int x = input.ReadInt32();
int y = input.ReadInt32();
uint width = input.ReadUInt32();
uint height = input.ReadUInt32();
uint comp_size = input.ReadUInt32();
uint uncomp_size = input.ReadUInt32();
if (uncomp_size != width*height*3u)
return null;
return new Pt1MetaData {
Width = width,
Height = height,
OffsetX = x,
OffsetY = y,
BPP = 3 == type ? 32 : 24,
Type = type,
PackedSize = comp_size,
UnpackedSize = uncomp_size
};
}
}
public override ImageData Read (Stream stream, ImageMetaData info)
{
var meta = (Pt1MetaData)info;
var reader = new Reader (stream, meta);
reader.Unpack();
return ImageData.Create (meta, reader.Format, null, reader.Data);
}
internal class Reader
{
byte[] m_input;
byte[] m_output;
byte[] m_alpha_packed;
int m_type;
int m_width;
int m_height;
int m_stride;
public PixelFormat Format { get; private set; }
public byte[] Data { get { return m_output; } }
public Reader (Stream input, Pt1MetaData info)
{
m_type = info.Type;
m_input = new byte[info.PackedSize+8];
input.Position = 0x20;
if ((int)info.PackedSize != input.Read (m_input, 0, (int)info.PackedSize))
throw new InvalidFormatException ("Unexpected end of file");
m_width = (int)info.Width;
m_height = (int)info.Height;
m_output = new byte[info.UnpackedSize];
m_stride = m_width*3;
if (3 == m_type)
{
Format = PixelFormats.Bgra32;
using (var reader = new ArcView.Reader (input))
{
int packed_size = reader.ReadInt32();
m_alpha_packed = new byte[packed_size];
if (packed_size != input.Read (m_alpha_packed, 0, packed_size))
throw new EndOfStreamException();
}
}
else
{
Format = PixelFormats.Bgr24;
}
}
public byte[] Unpack ()
{
switch (m_type)
{
case 3: UnpackV3(); break;
case 2: UnpackV2(); break;
case 1: UnpackV1(); break;
case 0: UnpackV0 (m_input, m_output); break;
}
return m_output;
}
void UnpackV3 ()
{
UnpackV2();
int total = m_width * m_height;
var alpha = new byte[total];
UnpackV0 (m_alpha_packed, alpha);
var pixels = new byte[total * 4];
int src = 0;
int dst = 0;
for (int i = 0; i < total; ++i)
{
pixels[dst++] = m_output[src++];
pixels[dst++] = m_output[src++];
pixels[dst++] = m_output[src++];
pixels[dst++] = alpha[i];
}
m_output = pixels;
}
uint edx;
byte ch;
int src;
void ReadNext ()
{
byte cl = (byte)(32 - ch);
edx &= 0xFFFFFFFFu >> cl;
edx += LittleEndian.ToUInt32 (m_input, src) << ch;
src += cl >> 3;
ch += (byte)(cl & 0xf8);
}
void UnpackV2 ()
{
src = 0;
int dst = 0;
Buffer.BlockCopy (m_input, src, m_output, dst, 3);
src += 3;
dst += 3;
edx = LittleEndian.ToUInt32 (m_input, src);
src += 3;
ch = 0x18;
uint _CF;
uint ebx;
sbyte ah;
byte al;
// [ebp+var_8] = i
for (int i = 1; i < m_width; ++i)
{
ReadNext();
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
--ch;
Buffer.BlockCopy (m_output, dst-3, m_output, dst, 3);
dst += 3;
}
else
{
ch -= 2;
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
}
else
{
ReadNext();
LittleEndian.Pack ((ushort)edx, m_output, dst);
edx >>= 16;
m_output[dst+2] = (byte)edx;
dst += 3;
edx >>= 8;
ch -= 24;
}
}
}
for (int i = 1; i < m_height; ++i)
{
ReadNext();
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
--ch;
Buffer.BlockCopy (m_output, dst-m_stride, m_output, dst, 3);
dst += 3;
}
else // loc_42207F
{
ch -= 2;
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-m_stride]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-m_stride]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-m_stride]);
m_output[dst++] = al;
}
else // loc_4220FC
{
ReadNext();
LittleEndian.Pack ((ushort)edx, m_output, dst);
edx >>= 16;
m_output[dst+2] = (byte)edx;
dst += 3;
edx >>= 8;
ch -= 24;
}
}
for (int j = 1; j < m_width; ++j)
{
ReadNext();
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
--ch;
ebx = (uint)(dst - m_stride);
ah = sub_4225EA();
al = (byte)(m_output[dst-3] - m_output[ebx-3] + m_output[ebx] + ah);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(m_output[dst-3] - m_output[ebx-2] + m_output[ebx+1] + ah);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(m_output[dst-3] - m_output[ebx-1] + m_output[ebx+2] + ah);
m_output[dst++] = al;
}
else
{
_CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
ch -= 2;
ebx = (uint)(dst - m_stride);
al = (byte)(m_output[dst-3] - m_output[ebx-3] + m_output[ebx]);
m_output[dst++] = al;
al = (byte)(m_output[dst-3] - m_output[ebx-2] + m_output[ebx+1]);
m_output[dst++] = al;
al = (byte)(m_output[dst-3] - m_output[ebx-1] + m_output[ebx+2]);
m_output[dst++] = al;
}
else
{
ebx = edx & 3;
if (3 == ebx)
{
edx >>= 2;
ch -= 4;
Buffer.BlockCopy (m_output, dst-3, m_output, dst, 3);
dst += 3;
}
else if (2 == ebx)
{
edx >>= 2;
ch -= 4;
ReadNext();
LittleEndian.Pack ((ushort)edx, m_output, dst);
edx >>= 16;
m_output[dst+2] = (byte)edx;
dst += 3;
edx >>= 8;
ch -= 24;
}
else if (1 == ebx)
{
edx >>= 2;
ch -= 4;
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
ReadNext();
ah = sub_4225EA();
al = (byte)(ah + m_output[dst-3]);
m_output[dst++] = al;
}
else
{
ebx = edx & 0xf;
edx >>= 4;
ch -= 6;
if (0 == ebx)
{
Buffer.BlockCopy (m_output, dst - m_stride - 3, m_output, dst, 3);
dst += 3;
}
else if (8 == ebx)
{
Buffer.BlockCopy (m_output, dst - m_stride, m_output, dst, 3);
dst += 3;
}
else
{
int off = dst - m_stride;
if (4 == ebx) off -= 3;
ah = sub_4225EA();
m_output[dst++] = (byte)(ah + m_output[off++]);
ReadNext();
ah = sub_4225EA();
m_output[dst++] = (byte)(ah + m_output[off++]);
ReadNext();
ah = sub_4225EA();
m_output[dst++] = (byte)(ah + m_output[off++]);
}
}
}
}
}
}
}
sbyte sub_4225EA ()
{
uint _CF = edx & 1;
edx >>= 1;
if (0 != _CF)
{
--ch;
return 0;
}
uint bits = edx & 3;
if (2 == bits)
{
edx >>= 2;
ch -= 3;
return -1;
}
if (1 == bits)
{
edx >>= 2;
ch -= 3;
return 1;
}
switch (edx & 7)
{
case 7:
edx >>= 3;
ch -= 4;
return -2;
case 3:
edx >>= 3;
ch -= 4;
return 2;
case 4:
edx >>= 3;
ch -= 4;
return -3;
default:
switch (edx & 0x3f)
{
case 0x38:
edx >>= 6;
ch -= 7;
return 3;
case 0x18:
edx >>= 6;
ch -= 7;
return -4;
case 0x28:
edx >>= 6;
ch -= 7;
return 4;
case 0x08:
edx >>= 6;
ch -= 7;
return -5;
case 0x30:
edx >>= 6;
ch -= 7;
return 5;
case 0x10:
edx >>= 6;
ch -= 7;
return -6;
case 0x20:
edx >>= 6;
ch -= 7;
return 6;
default:
switch (edx & 0xff)
{
case 0xc0:
edx >>= 8;
ch -= 9;
return -7;
case 0x40:
edx >>= 8;
ch -= 9;
return 7;
case 0x80:
edx >>= 8;
ch -= 9;
return -8;
default:
switch (edx & 0x3ff)
{
case 0x300:
edx >>= 10;
ch -= 11;
return 8;
case 0x100:
edx >>= 10;
ch -= 11;
return -9;
case 0x200:
edx >>= 10;
ch -= 11;
return 9;
default:
switch (edx & 0xfff)
{
case 0xc00:
edx >>= 12;
ch -= 13;
return -10;
case 0x400:
edx >>= 12;
ch -= 13;
return 10;
case 0x800:
edx >>= 12;
ch -= 13;
return -11;
default:
switch (edx & 0x3fff)
{
case 0x3000:
edx >>= 14;
ch -= 15;
return 0x0b;
case 0x1000:
edx >>= 14;
ch -= 15;
return -12;
case 0x2000:
edx >>= 14;
ch -= 15;
return 0x0c;
default:
edx >>= 14;
ch -= 15;
return -13;
}
}
}
}
}
}
}
void UnpackV1 ()
{
int src = 0; // dword_462E74
int dst = 0; // dword_462E78
byte[] frame = new byte[0x1000]; // word_461A28
PopulateLzssFrame (frame);
int ebp = 0xfee;
while (src < m_input.Length)
{
byte ah = m_input[src++];
for (int mask = 1; mask != 0x100; mask <<= 1)
{
if (0 != (ah & mask))
{
byte al = m_input[src++];
frame[ebp++] = al;
ebp &= 0xfff;
m_output[dst++] = al;
m_output[dst++] = al;
m_output[dst++] = al;
}
else
{
int offset = m_input[src++];
int count = m_input[src++];
offset |= (count & 0xf0) << 4;
count = (count & 0x0f) + 3;
for (; count != 0; --count)
{
byte al = frame[offset++];
frame[ebp++] = al;
offset &= 0xfff;
ebp &= 0xfff;
m_output[dst++] = al;
m_output[dst++] = al;
m_output[dst++] = al;
}
}
if (dst >= m_output.Length)
return;
}
}
}
void UnpackV0 (byte[] input, byte[] output)
{
int src = 0;
int dst = 0;
byte[] frame = new byte[0x1000]; // word_461A28
PopulateLzssFrame (frame);
int ebp = 0xfee;
while (src < input.Length)
{
byte ah = input[src++];
for (int mask = 1; mask != 0x100; mask <<= 1)
{
if (0 != (ah & mask))
{
byte al = input[src++];
frame[ebp++] = al;
ebp &= 0xfff;
output[dst++] = al;
}
else
{
int offset = input[src++];
int count = input[src++];
offset |= (count & 0xf0) << 4;
count = (count & 0x0f) + 3;
for (int i = 0; i < count; ++i)
{
byte al = frame[offset++];
frame[ebp++] = al;
offset &= 0xfff;
ebp &= 0xfff;
output[dst++] = al;
}
}
if (dst >= output.Length)
return;
}
}
}
void PopulateLzssFrame (byte[] frame)
{
int fill = 0;
int ecx;
for (int al = 0; al < 0x100; ++al)
for (ecx = 0x0d; ecx > 0; --ecx)
frame[fill++] = (byte)al;
for (int al = 0; al < 0x100; ++al)
frame[fill++] = (byte)al;
for (int al = 0xff; al >= 0; --al)
frame[fill++] = (byte)al;
for (ecx = 0x80; ecx > 0; --ecx)
frame[fill++] = 0;
for (ecx = 0x6e; ecx > 0; --ecx)
frame[fill++] = 0x20;
for (ecx = 0x12; ecx > 0; --ecx)
frame[fill++] = 0;
}
}
}
}
| |
//Matt Schoen
//9-12-2015
//
// This software is the copyrighted material of its author, Matt Schoen, and his company Defective Studios.
// It is available for sale on the Unity Asset store and is subject to their restrictions and limitations, as well as
// the following: You shall not reproduce or re-distribute this software without the express written (e-mail is fine)
// permission of the author. If permission is granted, the code (this file and related files) must bear this license
// in its entirety. Anyone who purchases the script is welcome to modify and re-use the code at their personal risk
// and under the condition that it not be included in any distribution builds. The software is provided as-is without
// warranty and the author bears no responsibility for damages or losses caused by the software.
// This Agreement becomes effective from the day you have installed, copied, accessed, downloaded and/or otherwise used
// the software.
//UniMerge 1.7.4
//SceneMerge Window
#define DEV //Comment this out to not auto-populate scene merge
using System.Collections;
using UniMerge;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
#if UNITY_5_3 || UNITY_5_3_OR_NEWER
using UnityEngine.SceneManagement;
using UnityEditor.SceneManagement;
#endif
public class SceneMerge : EditorWindow {
const string messagePath = "Assets/merges.txt";
public static Object mine, theirs;
public static string mineName = "Mine", theirName = "Theirs";
private static bool merged;
//If these names end up conflicting with names within your scene, change them here
public static string mineContainerName = "mine", theirsContainerName = "theirs";
public static GameObject mineContainer, theirsContainer;
public static float colWidth;
static SceneData mySceneData, theirSceneData;
Vector2 scroll;
private bool renderSettingsFoldout, lightmapsFoldout;
private static bool loading;
[MenuItem("Window/UniMerge/Scene Merge %&m")]
static void Init() {
GetWindow(typeof(SceneMerge));
}
#if DEV
//If these names end up conflicting with names within your project, change them here
public const string mineSceneName = "Mine", theirsSceneName = "Theirs";
void OnEnable() {
//Get path
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
//Unity 3 path stuff?
#else
string scriptPath = AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this));
UniMergeConfig.DEFAULT_PATH = scriptPath.Substring(0, scriptPath.IndexOf("Editor") - 1);
#endif
if(Directory.Exists(UniMergeConfig.DEFAULT_PATH + "/Demo/Scene Merge")) {
string[] assets = Directory.GetFiles(UniMergeConfig.DEFAULT_PATH + "/Demo/Scene Merge");
foreach(var asset in assets) {
if(asset.EndsWith(".unity")) {
if(asset.Contains(mineSceneName)) {
mine = AssetDatabase.LoadAssetAtPath(asset.Replace('\\', '/'), typeof(Object));
}
if(asset.Contains(theirsSceneName)) {
theirs = AssetDatabase.LoadAssetAtPath(asset.Replace('\\', '/'), typeof(Object));
}
}
}
}
if(EditorPrefs.HasKey(ObjectMerge.RowHeightKey)) {
ObjectMerge.selectedRowHeight = EditorPrefs.GetInt(ObjectMerge.RowHeightKey);
}
loading = false;
}
#endif
void OnDestroy() {
EditorPrefs.SetInt("RowHeight", ObjectMerge.selectedRowHeight);
}
private void OnGUI() {
if(loading) {
GUILayout.Label("Loading...");
return;
}
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
//Layout fix for older versions?
#else
EditorGUIUtility.labelWidth = 100;
#endif
//Ctrl + w to close
if(Event.current.Equals(Event.KeyboardEvent("^w"))) {
Close();
GUIUtility.ExitGUI();
}
/*
* SETUP
*/
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
EditorGUIUtility.LookLikeControls();
#endif
ObjectMerge.alt = false;
//Adjust colWidth as the window resizes
colWidth = (position.width - UniMergeConfig.midWidth * 2 - UniMergeConfig.margin) / 2;
#if UNITY_5
if(mine == null || theirs == null) //TODO: check if valid scene object
#else
if (mine == null || theirs == null
|| mine.GetType() != typeof (Object) || mine.GetType() != typeof (Object)
) //|| !AssetDatabase.GetAssetPath(mine).Contains(".unity") || !AssetDatabase.GetAssetPath(theirs).Contains(".unity"))
#endif
merged = GUI.enabled = false;
if(GUILayout.Button("Merge")) {
loading = true;
Merge(mine, theirs);
GUIUtility.ExitGUI();
}
GUI.enabled = merged;
GUILayout.BeginHorizontal();
{
GUI.enabled = mineContainer;
if(!GUI.enabled)
merged = false;
if(GUILayout.Button("Unpack Mine")) {
DestroyImmediate(theirsContainer);
List<Transform> tmp = new List<Transform>();
foreach(Transform t in mineContainer.transform)
tmp.Add(t);
foreach(Transform t in tmp)
t.parent = null;
DestroyImmediate(mineContainer);
mySceneData.ApplySettings();
}
GUI.enabled = theirsContainer;
if(!GUI.enabled)
merged = false;
if(GUILayout.Button("Unpack Theirs")) {
DestroyImmediate(mineContainer);
List<Transform> tmp = new List<Transform>();
foreach(Transform t in theirsContainer.transform)
tmp.Add(t);
foreach(Transform t in tmp)
t.parent = null;
DestroyImmediate(theirsContainer);
theirSceneData.ApplySettings();
}
}
GUILayout.EndHorizontal();
GUI.enabled = true;
ObjectMerge.DrawRowHeight();
GUILayout.BeginHorizontal();
{
GUILayout.BeginVertical(GUILayout.Width(colWidth));
{
#if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2)
GUILayout.BeginHorizontal();
mineName = GUILayout.TextField(mineName, GUILayout.Width(EditorGUIUtility.labelWidth));
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
mine = (Object)EditorGUILayout.ObjectField(mine, typeof(Object));
#else
mine = (Object)EditorGUILayout.ObjectField(mine, typeof(Object), true);
#endif
GUILayout.EndHorizontal();
#else
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
mine = (Object)EditorGUILayout.ObjectField("Mine", mine, typeof(Object));
#else
mine = (Object)EditorGUILayout.ObjectField("Mine", mine, typeof(Object), true);
#endif
#endif
}
GUILayout.EndVertical();
GUILayout.Space(UniMergeConfig.midWidth * 2);
GUILayout.BeginVertical(GUILayout.Width(colWidth));
{
#if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2)
GUILayout.BeginHorizontal();
theirName = GUILayout.TextField(theirName, GUILayout.Width(EditorGUIUtility.labelWidth));
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
theirs = (Object)EditorGUILayout.ObjectField(theirs, typeof(Object));
#else
theirs = (Object)EditorGUILayout.ObjectField(theirs, typeof(Object), true);
#endif
GUILayout.EndHorizontal();
#else
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
theirs = (Object)EditorGUILayout.ObjectField("Theirs", theirs, typeof(Object));
#else
theirs = (Object)EditorGUILayout.ObjectField("Theirs", theirs, typeof(Object), true);
#endif
#endif
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
if(mine == null || theirs == null)
merged = false;
if(merged) {
scroll = GUILayout.BeginScrollView(scroll);
ObjectMerge.StartRow(RenderSettingsCompare(mySceneData, theirSceneData));
#if UNITY_5
renderSettingsFoldout = EditorGUILayout.Foldout(renderSettingsFoldout, "Lighting");
#else
renderSettingsFoldout = EditorGUILayout.Foldout(renderSettingsFoldout, "Render Settings");
#endif
ObjectMerge.EndRow();
if(renderSettingsFoldout) {
//Fog
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.fog == theirSceneData.fog,
left = delegate { mySceneData.fog = EditorGUILayout.Toggle("Fog", mySceneData.fog); },
leftButton = delegate { mySceneData.fog = theirSceneData.fog; },
rightButton = delegate { theirSceneData.fog = mySceneData.fog; },
right = delegate { theirSceneData.fog = EditorGUILayout.Toggle("Fog", theirSceneData.fog); },
drawButtons = true
});
//Fog Color
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.fogColor == theirSceneData.fogColor,
left = delegate { mySceneData.fogColor = EditorGUILayout.ColorField("Fog Color", mySceneData.fogColor); },
leftButton = delegate { mySceneData.fogColor = theirSceneData.fogColor; },
rightButton = delegate { theirSceneData.fogColor = mySceneData.fogColor; },
right = delegate { theirSceneData.fogColor = EditorGUILayout.ColorField("Fog Color", theirSceneData.fogColor); },
drawButtons = true
});
//Fog Mode
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.fogMode == theirSceneData.fogMode,
left = delegate { mySceneData.fogMode = (FogMode)EditorGUILayout.EnumPopup("Fog Mode", mySceneData.fogMode); },
leftButton = delegate { mySceneData.fogMode = theirSceneData.fogMode; },
rightButton = delegate { theirSceneData.fogMode = mySceneData.fogMode; },
right = delegate { theirSceneData.fogMode = (FogMode)EditorGUILayout.EnumPopup("Fog Mode", theirSceneData.fogMode); },
drawButtons = true
});
//Fog Density
#if UNITY_5
string label = "Density";
#else
string label = "Linear Density";
#endif
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.fogDensity == theirSceneData.fogDensity,
left = delegate { mySceneData.fogDensity = EditorGUILayout.FloatField(label, mySceneData.fogDensity); },
leftButton = delegate { mySceneData.fogDensity = theirSceneData.fogDensity; },
rightButton = delegate { theirSceneData.fogDensity = mySceneData.fogDensity; },
right = delegate { theirSceneData.fogDensity = EditorGUILayout.FloatField(label, theirSceneData.fogDensity); },
drawButtons = true
});
//Linear Fog Start
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.fogStartDistance == theirSceneData.fogStartDistance,
left = delegate { mySceneData.fogStartDistance = EditorGUILayout.FloatField("Linear Fog Start", mySceneData.fogStartDistance); },
leftButton = delegate { mySceneData.fogStartDistance = theirSceneData.fogStartDistance; },
rightButton = delegate { theirSceneData.fogStartDistance = mySceneData.fogStartDistance; },
right = delegate { theirSceneData.fogStartDistance = EditorGUILayout.FloatField("Linear Fog Start", theirSceneData.fogStartDistance); },
drawButtons = true
});
//Linear Fog End
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.fogEndDistance == theirSceneData.fogEndDistance,
left = delegate { mySceneData.fogEndDistance = EditorGUILayout.FloatField("Linear Fog End", mySceneData.fogEndDistance); },
leftButton = delegate { mySceneData.fogEndDistance = theirSceneData.fogEndDistance; },
rightButton = delegate { theirSceneData.fogEndDistance = mySceneData.fogEndDistance; },
right = delegate { theirSceneData.fogEndDistance = EditorGUILayout.FloatField("Linear Fog End", theirSceneData.fogEndDistance); },
drawButtons = true
});
//Ambient Light
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.ambientLight == theirSceneData.ambientLight,
left = delegate { mySceneData.ambientLight = EditorGUILayout.ColorField("Ambient Light", mySceneData.ambientLight); },
leftButton = delegate { mySceneData.ambientLight = theirSceneData.ambientLight; },
rightButton = delegate { theirSceneData.ambientLight = mySceneData.ambientLight; },
right = delegate { theirSceneData.ambientLight = EditorGUILayout.ColorField("Ambient Light", theirSceneData.ambientLight); },
drawButtons = true
});
//Skybox
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.skybox == theirSceneData.skybox,
left = delegate {
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
mySceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", mySceneData.skybox, typeof(Material));
#else
mySceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", mySceneData.skybox, typeof(Material), false);
#endif
},
leftButton = delegate { mySceneData.skybox = theirSceneData.skybox; },
rightButton = delegate { theirSceneData.skybox = mySceneData.skybox; },
right = delegate {
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
theirSceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", theirSceneData.skybox, typeof(Material));
#else
theirSceneData.skybox = (Material)EditorGUILayout.ObjectField("Skybox Material", theirSceneData.skybox, typeof(Material), false);
#endif
},
drawButtons = true
});
//Halo Strength
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.haloStrength == theirSceneData.haloStrength,
left = delegate { mySceneData.haloStrength = EditorGUILayout.FloatField("Halo Strength", mySceneData.haloStrength); },
leftButton = delegate { mySceneData.haloStrength = theirSceneData.haloStrength; },
rightButton = delegate { theirSceneData.haloStrength = mySceneData.haloStrength; },
right = delegate { theirSceneData.haloStrength = EditorGUILayout.FloatField("Halo Strength", theirSceneData.haloStrength); },
drawButtons = true
});
//Flare Strength
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.flareStrength == theirSceneData.flareStrength,
left = delegate { mySceneData.flareStrength = EditorGUILayout.FloatField("Flare Strength", mySceneData.flareStrength); },
leftButton = delegate { mySceneData.flareStrength = theirSceneData.flareStrength; },
rightButton = delegate { theirSceneData.flareStrength = mySceneData.flareStrength; },
right = delegate { theirSceneData.flareStrength = EditorGUILayout.FloatField("Flare Strength", theirSceneData.flareStrength); },
drawButtons = true
});
//Flare Fade Speed
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.flareFadeSpeed == theirSceneData.flareFadeSpeed,
left = delegate { mySceneData.flareFadeSpeed = EditorGUILayout.FloatField("Flare Fade Speed", mySceneData.flareFadeSpeed); },
leftButton = delegate { mySceneData.flareFadeSpeed = theirSceneData.flareFadeSpeed; },
rightButton = delegate { theirSceneData.flareFadeSpeed = mySceneData.flareFadeSpeed; },
right = delegate { theirSceneData.flareFadeSpeed = EditorGUILayout.FloatField("Flare Fade Speed", theirSceneData.flareFadeSpeed); },
drawButtons = true
});
}
ObjectMerge.StartRow(LightmapSettingsCompare(mySceneData, theirSceneData));
lightmapsFoldout = EditorGUILayout.Foldout(lightmapsFoldout, "Lightmap Settings");
ObjectMerge.EndRow();
if(lightmapsFoldout) {
#if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5)
//BakedColorSpace
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.bakedColorSpace == theirSceneData.bakedColorSpace,
left = delegate { mySceneData.bakedColorSpace = (ColorSpace)EditorGUILayout.EnumPopup("Baked Color Space", mySceneData.bakedColorSpace); },
leftButton = delegate { mySceneData.bakedColorSpace = theirSceneData.bakedColorSpace; },
rightButton = delegate { theirSceneData.bakedColorSpace = mySceneData.bakedColorSpace; },
right = delegate { theirSceneData.bakedColorSpace = (ColorSpace)EditorGUILayout.EnumPopup("Baked Color Space", theirSceneData.bakedColorSpace); },
drawButtons = true
});
//LightProbes
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.lightProbes == theirSceneData.lightProbes,
left = delegate { mySceneData.lightProbes = (LightProbes)EditorGUILayout.ObjectField("Light Probes", mySceneData.lightProbes, typeof(LightProbes), false); },
leftButton = delegate { mySceneData.lightProbes = theirSceneData.lightProbes; },
rightButton = delegate { theirSceneData.lightProbes = mySceneData.lightProbes; },
right = delegate { theirSceneData.lightProbes = (LightProbes)EditorGUILayout.ObjectField("Light Probes", theirSceneData.lightProbes, typeof(LightProbes), false); },
drawButtons = true
});
#endif
//Lightmaps--do this later
//Lightmaps mode
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.lightmapsMode == theirSceneData.lightmapsMode,
left = delegate { mySceneData.lightmapsMode = (LightmapsMode)EditorGUILayout.EnumPopup("Lightmaps Mode", mySceneData.lightmapsMode); },
leftButton = delegate { mySceneData.lightmapsMode = theirSceneData.lightmapsMode; },
rightButton = delegate { theirSceneData.lightmapsMode = mySceneData.lightmapsMode; },
right = delegate { theirSceneData.lightmapsMode = (LightmapsMode)EditorGUILayout.EnumPopup("Lightmaps Mode", theirSceneData.lightmapsMode); },
drawButtons = true
});
#if !UNITY_5
//Quality
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.quality == theirSceneData.quality,
left = delegate { mySceneData.quality = (LightmapBakeQuality)EditorGUILayout.EnumPopup("Quality", mySceneData.quality); },
leftButton = delegate { mySceneData.quality = theirSceneData.quality; },
rightButton = delegate { theirSceneData.quality = mySceneData.quality; },
right = delegate { theirSceneData.quality = (LightmapBakeQuality)EditorGUILayout.EnumPopup("Quality", theirSceneData.quality); },
drawButtons = true
});
//Bounces
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.bounces == theirSceneData.bounces,
left = delegate { mySceneData.bounces = EditorGUILayout.IntField("Bounces", mySceneData.bounces); },
leftButton = delegate { mySceneData.bounces = theirSceneData.bounces; },
rightButton = delegate { theirSceneData.bounces = mySceneData.bounces; },
right = delegate { theirSceneData.bounces = EditorGUILayout.IntField("Bounces", theirSceneData.bounces); },
drawButtons = true
});
#endif
//Sky Light Color
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.skyLightColor == theirSceneData.skyLightColor,
left = delegate { mySceneData.skyLightColor = EditorGUILayout.ColorField("Sky Light Color", mySceneData.skyLightColor); },
leftButton = delegate { mySceneData.skyLightColor = theirSceneData.skyLightColor; },
rightButton = delegate { theirSceneData.skyLightColor = mySceneData.skyLightColor; },
right = delegate { theirSceneData.skyLightColor = EditorGUILayout.ColorField("Sky Light Color", theirSceneData.skyLightColor); },
drawButtons = true
});
//Sky Light Intensity
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.skyLightIntensity == theirSceneData.skyLightIntensity,
left = delegate { mySceneData.skyLightIntensity = EditorGUILayout.FloatField("Sky Light Intensity", mySceneData.skyLightIntensity); },
leftButton = delegate { mySceneData.skyLightIntensity = theirSceneData.skyLightIntensity; },
rightButton = delegate { theirSceneData.skyLightIntensity = mySceneData.skyLightIntensity; },
right = delegate { theirSceneData.skyLightIntensity = EditorGUILayout.FloatField("Sky Light Intensity", theirSceneData.skyLightIntensity); },
drawButtons = true
});
#if !UNITY_5
//Bounce Boost
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.bounceBoost == theirSceneData.bounceBoost,
left = delegate { mySceneData.bounceBoost = EditorGUILayout.FloatField("Bounce Boost", mySceneData.bounceBoost); },
leftButton = delegate { mySceneData.bounceBoost = theirSceneData.bounceBoost; },
rightButton = delegate { theirSceneData.bounceBoost = mySceneData.bounceBoost; },
right = delegate { theirSceneData.bounceBoost = EditorGUILayout.FloatField("Bounce Boost", theirSceneData.bounceBoost); },
drawButtons = true
});
//Bounce Intensity
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.bounceIntensity == theirSceneData.bounceIntensity,
left = delegate { mySceneData.bounceIntensity = EditorGUILayout.FloatField("Bounce Boost", mySceneData.bounceIntensity); },
leftButton = delegate { mySceneData.bounceIntensity = theirSceneData.bounceIntensity; },
rightButton = delegate { theirSceneData.bounceIntensity = mySceneData.bounceIntensity; },
right = delegate { theirSceneData.bounceIntensity = EditorGUILayout.FloatField("Bounce Boost", theirSceneData.bounceIntensity); },
drawButtons = true
});
//Final Gather Rays
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.finalGatherRays == theirSceneData.finalGatherRays,
left = delegate { mySceneData.finalGatherRays = EditorGUILayout.IntField("Final Gather Rays", mySceneData.finalGatherRays); },
leftButton = delegate { mySceneData.finalGatherRays = theirSceneData.finalGatherRays; },
rightButton = delegate { theirSceneData.finalGatherRays = mySceneData.finalGatherRays; },
right = delegate { theirSceneData.finalGatherRays = EditorGUILayout.IntField("Final Gather Rays", theirSceneData.finalGatherRays); },
drawButtons = true
});
//Final Gather Contrast Threshold
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.finalGatherContrastThreshold == theirSceneData.finalGatherContrastThreshold,
left = delegate { mySceneData.finalGatherContrastThreshold = EditorGUILayout.FloatField("FG Contrast Threshold", mySceneData.finalGatherContrastThreshold); },
leftButton = delegate { mySceneData.finalGatherContrastThreshold = theirSceneData.finalGatherContrastThreshold; },
rightButton = delegate { theirSceneData.finalGatherContrastThreshold = mySceneData.finalGatherContrastThreshold; },
right = delegate { theirSceneData.finalGatherContrastThreshold = EditorGUILayout.FloatField("FG Contrast Threshold", theirSceneData.finalGatherContrastThreshold); },
drawButtons = true
});
//Final Gather Gradient Threshold
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.finalGatherGradientThreshold == theirSceneData.finalGatherGradientThreshold,
left = delegate { mySceneData.finalGatherGradientThreshold = EditorGUILayout.FloatField("FG Gradient Threshold", mySceneData.finalGatherGradientThreshold); },
leftButton = delegate { mySceneData.finalGatherGradientThreshold = theirSceneData.finalGatherGradientThreshold; },
rightButton = delegate { theirSceneData.finalGatherGradientThreshold = mySceneData.finalGatherGradientThreshold; },
right = delegate { theirSceneData.finalGatherGradientThreshold = EditorGUILayout.FloatField("FG Gradient Threshold", theirSceneData.finalGatherGradientThreshold); },
drawButtons = true
});
//Final Gather Interpolation Points
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.finalGatherInterpolationPoints == theirSceneData.finalGatherInterpolationPoints,
left = delegate { mySceneData.finalGatherInterpolationPoints = EditorGUILayout.IntField("FG Interpolation Points", mySceneData.finalGatherInterpolationPoints); },
leftButton = delegate { mySceneData.finalGatherInterpolationPoints = theirSceneData.finalGatherInterpolationPoints; },
rightButton = delegate { theirSceneData.finalGatherInterpolationPoints = mySceneData.finalGatherInterpolationPoints; },
right = delegate { theirSceneData.finalGatherInterpolationPoints = EditorGUILayout.IntField("FG Interpolation Points", theirSceneData.finalGatherInterpolationPoints); },
drawButtons = true
});
//AO Amount
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.aoAmount == theirSceneData.aoAmount,
left = delegate { mySceneData.aoAmount = EditorGUILayout.FloatField("Ambient Occlusion", mySceneData.aoAmount); },
leftButton = delegate { mySceneData.aoAmount = theirSceneData.aoAmount; },
rightButton = delegate { theirSceneData.aoAmount = mySceneData.aoAmount; },
right = delegate { theirSceneData.aoAmount = EditorGUILayout.FloatField("Ambient Occlusion", theirSceneData.aoAmount); },
drawButtons = true
});
//AO Contrast
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.aoContrast == theirSceneData.aoContrast,
left = delegate { mySceneData.aoContrast = EditorGUILayout.FloatField("AO Contrast", mySceneData.aoContrast); },
leftButton = delegate { mySceneData.aoContrast = theirSceneData.aoContrast; },
rightButton = delegate { theirSceneData.aoContrast = mySceneData.aoContrast; },
right = delegate { theirSceneData.aoContrast = EditorGUILayout.FloatField("AO Contrast", theirSceneData.aoContrast); },
drawButtons = true
});
//AO Max Distance
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.aoMaxDistance == theirSceneData.aoMaxDistance,
left = delegate { mySceneData.aoMaxDistance = EditorGUILayout.FloatField("AO Max Distance", mySceneData.aoMaxDistance); },
leftButton = delegate { mySceneData.aoMaxDistance = theirSceneData.aoMaxDistance; },
rightButton = delegate { theirSceneData.aoMaxDistance = mySceneData.aoMaxDistance; },
right = delegate { theirSceneData.aoMaxDistance = EditorGUILayout.FloatField("AO Contrast", theirSceneData.aoMaxDistance); },
drawButtons = true
});
//Lock Atlas
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.lockAtlas == theirSceneData.lockAtlas,
left = delegate { mySceneData.lockAtlas = EditorGUILayout.Toggle("Lock Atlas", mySceneData.lockAtlas); },
leftButton = delegate { mySceneData.lockAtlas = theirSceneData.lockAtlas; },
rightButton = delegate { theirSceneData.lockAtlas = mySceneData.lockAtlas; },
right = delegate { theirSceneData.lockAtlas = EditorGUILayout.Toggle("Lock Atlas", theirSceneData.lockAtlas); },
drawButtons = true
});
//Last Used Resolution
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.lastUsedResolution == theirSceneData.lastUsedResolution,
left = delegate { mySceneData.lastUsedResolution = EditorGUILayout.FloatField("Last Used Resolution", mySceneData.lastUsedResolution); },
leftButton = delegate { mySceneData.lastUsedResolution = theirSceneData.lastUsedResolution; },
rightButton = delegate { theirSceneData.lastUsedResolution = mySceneData.lastUsedResolution; },
right = delegate { theirSceneData.lastUsedResolution = EditorGUILayout.FloatField("Last Used Resolution", theirSceneData.lastUsedResolution); },
drawButtons = true
});
#endif
//Resolution
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.resolution == theirSceneData.resolution,
left = delegate { mySceneData.resolution = EditorGUILayout.FloatField("Resolution", mySceneData.resolution); },
leftButton = delegate { mySceneData.resolution = theirSceneData.resolution; },
rightButton = delegate { theirSceneData.resolution = mySceneData.resolution; },
right = delegate { theirSceneData.resolution = EditorGUILayout.FloatField("Resolution", theirSceneData.resolution); },
drawButtons = true
});
#if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5)
//Padding
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.padding == theirSceneData.padding,
left = delegate { mySceneData.padding = EditorGUILayout.IntField("Padding", mySceneData.padding); },
leftButton = delegate { mySceneData.padding = theirSceneData.padding; },
rightButton = delegate { theirSceneData.padding = mySceneData.padding; },
right = delegate { theirSceneData.padding = EditorGUILayout.IntField("Padding", theirSceneData.padding); },
drawButtons = true
});
#endif
//Max Atlas Height
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.maxAtlasHeight == theirSceneData.maxAtlasHeight,
left = delegate { mySceneData.maxAtlasHeight = EditorGUILayout.IntField("Max Atlas Height", mySceneData.maxAtlasHeight); },
leftButton = delegate { mySceneData.maxAtlasHeight = theirSceneData.maxAtlasHeight; },
rightButton = delegate { theirSceneData.maxAtlasHeight = mySceneData.maxAtlasHeight; },
right = delegate { theirSceneData.maxAtlasHeight = EditorGUILayout.IntField("Max Atlas Height", theirSceneData.maxAtlasHeight); },
drawButtons = true
});
//Max Atlas Width
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.maxAtlasWidth == theirSceneData.maxAtlasWidth,
left = delegate { mySceneData.maxAtlasWidth = EditorGUILayout.IntField("Max Atlas Width", mySceneData.maxAtlasWidth); },
leftButton = delegate { mySceneData.maxAtlasWidth = theirSceneData.maxAtlasWidth; },
rightButton = delegate { theirSceneData.maxAtlasWidth = mySceneData.maxAtlasWidth; },
right = delegate { theirSceneData.maxAtlasWidth = EditorGUILayout.IntField("Max Atlas Width", theirSceneData.maxAtlasWidth); },
drawButtons = true
});
//Texture Compression
ObjectMerge.DrawGenericRow(new ObjectMerge.GenericRowArguments {
indent = UniMerge.Util.TAB_SIZE,
colWidth = colWidth,
compare = () => mySceneData.textureCompression == theirSceneData.textureCompression,
left = delegate { mySceneData.textureCompression = EditorGUILayout.Toggle("Tex Compression", mySceneData.textureCompression); },
leftButton = delegate { mySceneData.fog = theirSceneData.textureCompression; },
rightButton = delegate { theirSceneData.textureCompression = mySceneData.textureCompression; },
right = delegate { theirSceneData.fog = EditorGUILayout.Toggle("Tex Compression", theirSceneData.textureCompression); },
drawButtons = true
});
}
GUILayout.EndScrollView();
}
}
static bool RenderSettingsCompare(SceneData mySceneData, SceneData theirSceneData) {
if(mySceneData.fog != theirSceneData.fog)
return false;
if(mySceneData.fogColor != theirSceneData.fogColor)
return false;
if(mySceneData.fogMode != theirSceneData.fogMode)
return false;
if(mySceneData.fogDensity != theirSceneData.fogDensity)
return false;
if(mySceneData.fogStartDistance != theirSceneData.fogStartDistance)
return false;
if(mySceneData.fogEndDistance != theirSceneData.fogEndDistance)
return false;
if(mySceneData.ambientLight != theirSceneData.ambientLight)
return false;
if(mySceneData.skybox != theirSceneData.skybox)
return false;
if(mySceneData.haloStrength != theirSceneData.haloStrength)
return false;
if(mySceneData.flareStrength != theirSceneData.flareStrength)
return false;
if(mySceneData.flareFadeSpeed != theirSceneData.flareFadeSpeed)
return false;
return true;
}
static bool LightmapSettingsCompare(SceneData mySceneData, SceneData theirSceneData) {
#if !UNITY_5
if (mySceneData.aoAmount != theirSceneData.aoAmount)
return false;
if (mySceneData.aoContrast != theirSceneData.aoContrast)
return false;
if (mySceneData.bounceBoost != theirSceneData.bounceBoost)
return false;
if (mySceneData.bounceIntensity != theirSceneData.bounceIntensity)
return false;
if (mySceneData.finalGatherContrastThreshold != theirSceneData.finalGatherContrastThreshold)
return false;
if (mySceneData.lastUsedResolution != theirSceneData.lastUsedResolution)
return false;
if (mySceneData.bounces != theirSceneData.bounces)
return false;
if (mySceneData.finalGatherInterpolationPoints != theirSceneData.finalGatherInterpolationPoints)
return false;
if (mySceneData.finalGatherRays != theirSceneData.finalGatherRays)
return false;
if (mySceneData.lockAtlas != theirSceneData.lockAtlas)
return false;
#if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5)
if (mySceneData.padding != theirSceneData.padding)
return false;
#endif
#endif
#if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5)
if(mySceneData.bakedColorSpace != theirSceneData.bakedColorSpace)
return false;
if(mySceneData.lightProbes != theirSceneData.lightProbes)
return false;
#endif
//if (mySceneData.lightmaps != theirSceneData.lightmaps)
// return false;
if(mySceneData.lightmapsMode != theirSceneData.lightmapsMode)
return false;
if(mySceneData.aoMaxDistance != theirSceneData.aoMaxDistance)
return false;
if(mySceneData.resolution != theirSceneData.resolution)
return false;
if(mySceneData.skyLightIntensity != theirSceneData.skyLightIntensity)
return false;
if(mySceneData.maxAtlasHeight != theirSceneData.maxAtlasHeight)
return false;
if(mySceneData.maxAtlasWidth != theirSceneData.maxAtlasWidth)
return false;
if(mySceneData.textureCompression != theirSceneData.textureCompression)
return false;
if(mySceneData.skyLightColor != theirSceneData.skyLightColor)
return false;
return true;
}
public static void CLIIn() {
string[] args = System.Environment.GetCommandLineArgs();
foreach(string arg in args)
Debug.Log(arg);
Merge(
args[args.Length - 2].Substring(args[args.Length - 2].IndexOf("Assets")).Replace("\\", "/").Trim(),
args[args.Length - 1].Substring(args[args.Length - 1].IndexOf("Assets")).Replace("\\", "/").Trim());
}
void Update() {
if(cancelRefresh) {
refresh = null;
}
if(refresh != null) {
if(!refresh.MoveNext())
refresh = null;
Repaint();
}
cancelRefresh = false;
TextAsset mergeFile = (TextAsset)AssetDatabase.LoadAssetAtPath(messagePath, typeof(TextAsset));
if(mergeFile) {
string[] files = mergeFile.text.Split('\n');
AssetDatabase.DeleteAsset(messagePath);
for(int i = 0; i < files.Length; i++) {
if(!files[i].StartsWith("Assets")) {
if(files[i].IndexOf("Assets") > -1)
files[i] = files[i].Substring(files[i].IndexOf("Assets")).Replace("\\", "/").Trim();
}
}
DoMerge(files);
}
}
public static void PrefabMerge(string myPath, string theirPath) {
GetWindow(typeof(ObjectMerge));
ObjectMerge.mine = (GameObject)AssetDatabase.LoadAssetAtPath(myPath, typeof(GameObject));
ObjectMerge.theirs = (GameObject)AssetDatabase.LoadAssetAtPath(theirPath, typeof(GameObject));
}
public static IEnumerator refresh;
public static bool cancelRefresh = false;
public static void DoMerge(string[] paths) {
if(paths.Length > 2) {
Merge(paths[0], paths[1]);
} else Debug.LogError("need at least 2 paths, " + paths.Length + " given");
}
public static void Merge(Object myScene, Object theirScene) {
if(myScene == null || theirScene == null)
return;
Merge(AssetDatabase.GetAssetPath(myScene), AssetDatabase.GetAssetPath(theirScene));
}
public static void Merge(string myPath, string theirPath) {
refresh = MergeAsync(myPath, theirPath);
}
public static IEnumerator MergeAsync(string myPath, string theirPath) {
if(string.IsNullOrEmpty(myPath) || string.IsNullOrEmpty(theirPath))
yield break;
if(myPath.EndsWith("prefab") || theirPath.EndsWith("prefab")) {
PrefabMerge(myPath, theirPath);
yield break;
}
if(AssetDatabase.LoadAssetAtPath(myPath, typeof(Object)) && AssetDatabase.LoadAssetAtPath(theirPath, typeof(Object))) {
#if UNITY_5_3 || UNITY_5_3_OR_NEWER
if(EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) {
/*
* Get scene data (render settings, lightmaps)
*/
//Load "theirs" to get RenderSettings, etc.
yield return null;
EditorSceneManager.OpenScene(theirPath);
theirSceneData.CaptureSettings();
//Load "mine" to start the merge
yield return null;
Scene mine = EditorSceneManager.OpenScene(myPath);
mySceneData.CaptureSettings();
#else
if(EditorApplication.SaveCurrentSceneIfUserWantsTo()) {
/*
* Get scene data (render settings, lightmaps)
*/
//Load "theirs" to get RenderSettings, etc.
yield return null;
EditorApplication.OpenScene(theirPath);
theirSceneData.CaptureSettings();
//Load "mine" to start the merge
yield return null;
EditorApplication.OpenScene(myPath);
mySceneData.CaptureSettings();
#endif
/*
* Start Merge
*/
string[] split = myPath.Split('/');
mineContainerName = split[split.Length - 1].Replace(".unity", "");
//split = split[split.Length - 1].Split('.');
//mineContainerName = split[0];
mineContainer = new GameObject { name = mineContainerName };
GameObject[] allObjects = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject));
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
foreach(GameObject obj in allObjects) {
if(obj.transform.parent == null
&& EditorUtility.GetPrefabType(obj) != PrefabType.Prefab
&& EditorUtility.GetPrefabType(obj) != PrefabType.ModelPrefab
&& obj.hideFlags == 0) //Want a better way to filter out "internal" objects
obj.transform.parent = mineContainer.transform;
}
#else
foreach(GameObject obj in allObjects) {
if(obj.transform.parent == null
&& PrefabUtility.GetPrefabType(obj) != PrefabType.Prefab
&& PrefabUtility.GetPrefabType(obj) != PrefabType.ModelPrefab
&& obj.hideFlags == 0) //Want a better way to filter out "internal" objects
obj.transform.parent = mineContainer.transform;
}
#endif
split = theirPath.Split('/');
//split = split[split.Length - 1].Split('.');
//theirsContainerName = split[0];
theirsContainerName = split[split.Length - 1].Replace(".unity", "");
#if UNITY_5_3 || UNITY_5_3_OR_NEWER
Scene theirs = EditorSceneManager.OpenScene(theirPath, OpenSceneMode.Additive);
SceneManager.MergeScenes(mine, theirs);
#else
EditorApplication.OpenSceneAdditive(theirPath);
#endif
theirsContainer = new GameObject { name = theirsContainerName };
allObjects = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject));
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
foreach(GameObject obj in allObjects) {
if(obj.transform.parent == null && obj.name != mineContainerName
&& EditorUtility.GetPrefabType(obj) != PrefabType.Prefab
&& EditorUtility.GetPrefabType(obj) != PrefabType.ModelPrefab
&& obj.hideFlags == 0) //Want a better way to filter out "internal" objects
obj.transform.parent = theirsContainer.transform;
}
#else
foreach(GameObject obj in allObjects) {
if(obj.transform.parent == null && obj.name != mineContainerName
&& PrefabUtility.GetPrefabType(obj) != PrefabType.Prefab
&& PrefabUtility.GetPrefabType(obj) != PrefabType.ModelPrefab
&& obj.hideFlags == 0) //Want a better way to filter out "internal" objects
obj.transform.parent = theirsContainer.transform;
}
#endif
yield return null;
ObjectMerge.root = null;
GetWindow(typeof(ObjectMerge));
ObjectMerge.mine = mineContainer;
ObjectMerge.theirs = theirsContainer;
yield return null;
merged = true;
}
}
loading = false;
yield break;
}
}
public struct SceneData {
/*
* Render Settings
*/
public Color ambientLight,
fogColor;
public float flareFadeSpeed,
flareStrength,
fogDensity,
fogEndDistance,
fogStartDistance,
haloStrength;
public bool fog;
public FogMode fogMode;
public Material skybox;
//Hmm... can't get at haloTexture or spotCookie
//public Texture haloTexture, spotCookie;
/*
* Lightmap Settings
*/
#if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5)
public ColorSpace bakedColorSpace;
public LightProbes lightProbes;
#endif
public LightmapData[] lightmaps;
public LightmapsMode lightmapsMode;
/*
* Lightmap Editor Settings
*/
//Where is "use in forward rendering?"
//TODO: Use serialized object representation
#if UNITY_5
#else
public float aoAmount,
aoContrast,
bounceBoost,
bounceIntensity,
finalGatherContrastThreshold,
finalGatherGradientThreshold,
lastUsedResolution;
public int bounces,
finalGatherInterpolationPoints,
finalGatherRays;
public bool lockAtlas;
#endif
#if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5)
public int padding;
#endif
public float aoMaxDistance,
resolution,
skyLightIntensity;
public int maxAtlasHeight,
maxAtlasWidth;
public bool textureCompression;
public Color skyLightColor;
#if UNITY_5
#else
public LightmapBakeQuality quality;
#endif
//Nav mesh settings can't be accessed via script :(
//Lightmapping is VERY version-specific. You may have to modify the settings that are compared
public void CaptureSettings() {
#if UNITY_5
#else
aoAmount = LightmapEditorSettings.aoAmount;
aoContrast = LightmapEditorSettings.aoContrast;
bounceBoost = LightmapEditorSettings.bounceBoost;
bounceIntensity = LightmapEditorSettings.bounceIntensity;
bounces = LightmapEditorSettings.bounces;
quality = LightmapEditorSettings.quality;
skyLightColor = LightmapEditorSettings.skyLightColor;
skyLightIntensity = LightmapEditorSettings.skyLightIntensity;
finalGatherContrastThreshold = LightmapEditorSettings.finalGatherContrastThreshold;
finalGatherGradientThreshold = LightmapEditorSettings.finalGatherGradientThreshold;
finalGatherInterpolationPoints = LightmapEditorSettings.finalGatherInterpolationPoints;
finalGatherRays = LightmapEditorSettings.finalGatherRays;
lastUsedResolution = LightmapEditorSettings.lastUsedResolution;
lockAtlas = LightmapEditorSettings.lockAtlas;
#if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5)
bakedColorSpace = LightmapSettings.bakedColorSpace;
#endif
#endif
ambientLight = RenderSettings.ambientLight;
#if UNITY_4_3 || UNITY_4_5 || UNITY_5 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3
flareFadeSpeed = RenderSettings.flareFadeSpeed;
#endif
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
#else
lightProbes = LightmapSettings.lightProbes;
padding = LightmapEditorSettings.padding;
#endif
flareStrength = RenderSettings.flareStrength;
fog = RenderSettings.fog;
fogColor = RenderSettings.fogColor;
fogDensity = RenderSettings.fogDensity;
fogEndDistance = RenderSettings.fogEndDistance;
fogMode = RenderSettings.fogMode;
fogStartDistance = RenderSettings.fogStartDistance;
haloStrength = RenderSettings.haloStrength;
skybox = RenderSettings.skybox;
lightmaps = LightmapSettings.lightmaps;
lightmapsMode = LightmapSettings.lightmapsMode;
aoMaxDistance = LightmapEditorSettings.aoMaxDistance;
maxAtlasHeight = LightmapEditorSettings.maxAtlasHeight;
maxAtlasWidth = LightmapEditorSettings.maxAtlasWidth;
resolution = LightmapEditorSettings.realtimeResolution;
textureCompression = LightmapEditorSettings.textureCompression;
}
public void ApplySettings() {
#if UNITY_5
#else
LightmapEditorSettings.aoAmount = aoAmount;
LightmapEditorSettings.aoContrast = aoContrast;
LightmapEditorSettings.bounceBoost = bounceBoost;
LightmapEditorSettings.bounceIntensity = bounceIntensity;
LightmapEditorSettings.bounces = bounces;
LightmapEditorSettings.finalGatherContrastThreshold = finalGatherContrastThreshold;
LightmapEditorSettings.finalGatherGradientThreshold = finalGatherGradientThreshold;
LightmapEditorSettings.finalGatherInterpolationPoints = finalGatherInterpolationPoints;
LightmapEditorSettings.finalGatherRays = finalGatherRays;
LightmapEditorSettings.lastUsedResolution = lastUsedResolution;
LightmapEditorSettings.lockAtlas = lockAtlas;
LightmapEditorSettings.quality = quality;
LightmapEditorSettings.skyLightColor = skyLightColor;
LightmapEditorSettings.skyLightIntensity = skyLightIntensity;
#if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5)
LightmapSettings.bakedColorSpace = bakedColorSpace;
#endif
#endif
RenderSettings.ambientLight = ambientLight;
RenderSettings.fogColor = fogColor;
#if UNITY_4_3 || UNITY_4_5 || UNITY_5 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3
flareFadeSpeed = RenderSettings.flareFadeSpeed;
#endif
#if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5
#else
LightmapSettings.lightProbes = lightProbes;
LightmapEditorSettings.padding = padding;
#endif
RenderSettings.flareStrength = flareStrength;
RenderSettings.fogDensity = fogDensity;
RenderSettings.fogEndDistance = fogEndDistance;
RenderSettings.fogStartDistance = fogStartDistance;
RenderSettings.haloStrength = haloStrength;
RenderSettings.fog = fog;
RenderSettings.fogMode = fogMode;
RenderSettings.skybox = skybox;
LightmapSettings.lightmaps = lightmaps;
LightmapSettings.lightmapsMode = lightmapsMode;
LightmapEditorSettings.aoMaxDistance = aoMaxDistance;
LightmapEditorSettings.maxAtlasHeight = maxAtlasHeight;
LightmapEditorSettings.maxAtlasWidth = maxAtlasWidth;
LightmapEditorSettings.realtimeResolution = resolution;
LightmapEditorSettings.textureCompression = textureCompression;
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Joints
{
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
/// <summary>
/// Friction joint. This is used for top-down friction.
/// It provides 2D translational friction and angular friction.
/// </summary>
public class FrictionJoint : Joint
{
public Vector2 LocalAnchorA;
public Vector2 LocalAnchorB;
private float _angularImpulse;
private float _angularMass;
private Vector2 _linearImpulse;
private Mat22 _linearMass;
internal FrictionJoint()
{
JointType = JointType.Friction;
}
public FrictionJoint(Body bodyA, Body bodyB, Vector2 localAnchorA, Vector2 localAnchorB)
: base(bodyA, bodyB)
{
JointType = JointType.Friction;
LocalAnchorA = localAnchorA;
LocalAnchorB = localAnchorB;
}
public override Vector2 WorldAnchorA
{
get { return BodyA.GetWorldPoint(LocalAnchorA); }
}
public override Vector2 WorldAnchorB
{
get { return BodyB.GetWorldPoint(LocalAnchorB); }
set { Debug.Assert(false, "You can't set the world anchor on this joint type."); }
}
/// <summary>
/// The maximum friction force in N.
/// </summary>
public float MaxForce { get; set; }
/// <summary>
/// The maximum friction torque in N-m.
/// </summary>
public float MaxTorque { get; set; }
public override Vector2 GetReactionForce(float inv_dt)
{
return inv_dt * _linearImpulse;
}
public override float GetReactionTorque(float inv_dt)
{
return inv_dt * _angularImpulse;
}
internal override void InitVelocityConstraints(ref TimeStep step)
{
Body bA = BodyA;
Body bB = BodyB;
Transform xfA, xfB;
bA.GetTransform(out xfA);
bB.GetTransform(out xfB);
// Compute the effective mass matrix.
Vector2 rA = MathUtils.Multiply(ref xfA.R, LocalAnchorA - bA.LocalCenter);
Vector2 rB = MathUtils.Multiply(ref xfB.R, LocalAnchorB - bB.LocalCenter);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float mA = bA.InvMass, mB = bB.InvMass;
float iA = bA.InvI, iB = bB.InvI;
Mat22 K1 = new Mat22();
K1.Col1.X = mA + mB;
K1.Col2.X = 0.0f;
K1.Col1.Y = 0.0f;
K1.Col2.Y = mA + mB;
Mat22 K2 = new Mat22();
K2.Col1.X = iA * rA.Y * rA.Y;
K2.Col2.X = -iA * rA.X * rA.Y;
K2.Col1.Y = -iA * rA.X * rA.Y;
K2.Col2.Y = iA * rA.X * rA.X;
Mat22 K3 = new Mat22();
K3.Col1.X = iB * rB.Y * rB.Y;
K3.Col2.X = -iB * rB.X * rB.Y;
K3.Col1.Y = -iB * rB.X * rB.Y;
K3.Col2.Y = iB * rB.X * rB.X;
Mat22 K12;
Mat22.Add(ref K1, ref K2, out K12);
Mat22 K;
Mat22.Add(ref K12, ref K3, out K);
_linearMass = K.Inverse;
_angularMass = iA + iB;
if (_angularMass > 0.0f)
{
_angularMass = 1.0f / _angularMass;
}
if (Settings.EnableWarmstarting)
{
// Scale impulses to support a variable time step.
_linearImpulse *= step.dtRatio;
_angularImpulse *= step.dtRatio;
Vector2 P = new Vector2(_linearImpulse.X, _linearImpulse.Y);
bA.LinearVelocityInternal -= mA * P;
bA.AngularVelocityInternal -= iA * (MathUtils.Cross(rA, P) + _angularImpulse);
bB.LinearVelocityInternal += mB * P;
bB.AngularVelocityInternal += iB * (MathUtils.Cross(rB, P) + _angularImpulse);
}
else
{
_linearImpulse = Vector2.Zero;
_angularImpulse = 0.0f;
}
}
internal override void SolveVelocityConstraints(ref TimeStep step)
{
Body bA = BodyA;
Body bB = BodyB;
Vector2 vA = bA.LinearVelocityInternal;
float wA = bA.AngularVelocityInternal;
Vector2 vB = bB.LinearVelocityInternal;
float wB = bB.AngularVelocityInternal;
float mA = bA.InvMass, mB = bB.InvMass;
float iA = bA.InvI, iB = bB.InvI;
Transform xfA, xfB;
bA.GetTransform(out xfA);
bB.GetTransform(out xfB);
Vector2 rA = MathUtils.Multiply(ref xfA.R, LocalAnchorA - bA.LocalCenter);
Vector2 rB = MathUtils.Multiply(ref xfB.R, LocalAnchorB - bB.LocalCenter);
// Solve angular friction
{
float Cdot = wB - wA;
float impulse = -_angularMass * Cdot;
float oldImpulse = _angularImpulse;
float maxImpulse = step.dt * MaxTorque;
_angularImpulse = MathHelper.Clamp(_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = _angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
Vector2 Cdot = vB + MathUtils.Cross(wB, rB) - vA - MathUtils.Cross(wA, rA);
Vector2 impulse = -MathUtils.Multiply(ref _linearMass, Cdot);
Vector2 oldImpulse = _linearImpulse;
_linearImpulse += impulse;
float maxImpulse = step.dt * MaxForce;
if (_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
_linearImpulse.Normalize();
_linearImpulse *= maxImpulse;
}
impulse = _linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * MathUtils.Cross(rA, impulse);
vB += mB * impulse;
wB += iB * MathUtils.Cross(rB, impulse);
}
bA.LinearVelocityInternal = vA;
bA.AngularVelocityInternal = wA;
bB.LinearVelocityInternal = vB;
bB.AngularVelocityInternal = wB;
}
internal override bool SolvePositionConstraints()
{
return true;
}
}
}
| |
// Copyright (c) 2017 Trevor Redfern
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
namespace SilverNeedle.Serialization
{
using System;
using System.Collections.Generic;
using System.Linq;
public class MemoryStore : IObjectStore
{
public string Key { get; private set; }
public string Value { get; private set; }
public IEnumerable<string> Keys {
get {
return dataStore.Keys;
}
}
public IEnumerable<IObjectStore> Children {
get { return childList; }
}
public bool HasChildren {
get {
return childList.Count > 0;
}
}
public MemoryStore()
{
dataStore = new Dictionary<string, MemoryStore>();
childList = new List<MemoryStore>();
}
public MemoryStore(string key, string value) : this()
{
Key = key;
Value = value;
dataStore[key] = this;
}
public MemoryStore(string key, IEnumerable<string> list) : this()
{
Key = key;
dataStore[key] = this;
foreach(var s in list)
{
AddListItem(new MemoryStore("list-item", s));
}
}
public IDictionary<string, string> ChildrenToDictionary()
{
throw new NotImplementedException();
}
public bool GetBool(string key)
{
return Boolean.Parse(this.GetString(key));
}
public bool GetBoolOptional(string key, bool defaultValue = false)
{
if(HasKey(key))
return GetBool(key);
return defaultValue;
}
public T GetEnum<T>(string key)
{
return (T)Enum.Parse(typeof(T), GetString(key), true);
}
public float GetFloat(string key)
{
return float.Parse(GetString(key));
}
public float GetFloatOptional(string key, float defaultValue = 0)
{
throw new NotImplementedException();
}
public int GetInteger(string key)
{
return int.Parse(GetString(key));
}
public int GetIntegerOptional(string key, int defaultValue = 0)
{
throw new NotImplementedException();
}
public string[] GetList(string key)
{
var items = GetObjectList(key);
return items.OfType<MemoryStore>().Select(x => x.Value).ToArray();
}
public string[] GetListOptional(string key)
{
if(HasKey(key))
return GetList(key);
return new string[] { };
}
public IObjectStore GetObject(string key)
{
return dataStore[key];
}
public IObjectStore GetObjectOptional(string key)
{
if(HasKey(key))
return GetObject(key);
return null;
}
public string GetString(string key)
{
if(key == Key)
return Value;
return dataStore[key].Value;
}
public string GetStringOptional(string key, string defaultValue = null)
{
if(HasKey(key))
return GetString(key);
return defaultValue;
}
public bool HasKey(string key)
{
return dataStore.ContainsKey(key) || string.Equals(this.Key, key);
}
public void SetValue(string key, string value)
{
SetValue(key, new MemoryStore(key, value));
}
public void SetValue(string key, int value)
{
SetValue(key, value.ToString());
}
public void SetValue(string key, IObjectStore data) {
dataStore.Add(key, data as MemoryStore);
}
public void SetValue(string key, float value)
{
SetValue(key, value.ToString());
}
public void SetValue(string key, bool boolean)
{
SetValue(key, boolean.ToString());
}
public void AddListItem(IObjectStore childItem)
{
childList.Add(childItem as MemoryStore);
}
public void SetValue(string key, IEnumerable<string> values)
{
var obj = new MemoryStore();
obj.Key = key;
foreach(var v in values)
{
obj.AddListItem(new MemoryStore("list-item", v));
}
SetValue(key, obj);
}
public IEnumerable<IObjectStore> GetObjectList(string key)
{
return ((MemoryStore)GetObject(key)).Children;
}
public IEnumerable<IObjectStore> GetObjectListOptional(string key)
{
if(HasKey(key))
return GetObjectList(key);
return new List<IObjectStore>();
}
private Dictionary<string, MemoryStore> dataStore;
private IList<MemoryStore> childList;
}
}
| |
#region License
// Copyright 2014 MorseCode Software
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MorseCode.RxMvvm.Observable.Property.Internal
{
using System;
using System.Diagnostics.Contracts;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using MorseCode.RxMvvm.Common;
using MorseCode.RxMvvm.Common.DiscriminatedUnion;
[Serializable]
internal class AsyncCalculatedPropertyWithContext<TContext, TFirst, TSecond, TThird, T> : CalculatedPropertyBase<T>, ISerializable
{
private readonly TContext context;
private readonly IObservable<TFirst> firstProperty;
private readonly IObservable<TSecond> secondProperty;
private readonly IObservable<TThird> thirdProperty;
private readonly TimeSpan throttleTime;
private readonly Func<TContext, TFirst, TSecond, TThird, T> calculateValue;
private readonly bool isLongRunningCalculation;
private IDisposable scheduledTask;
internal AsyncCalculatedPropertyWithContext(
TContext context,
IObservable<TFirst> firstProperty,
IObservable<TSecond> secondProperty,
IObservable<TThird> thirdProperty,
TimeSpan throttleTime,
Func<TContext, TFirst, TSecond, TThird, T> calculateValue,
bool isLongRunningCalculation)
{
Contract.Requires<ArgumentNullException>(firstProperty != null, "firstProperty");
Contract.Requires<ArgumentNullException>(secondProperty != null, "secondProperty");
Contract.Requires<ArgumentNullException>(thirdProperty != null, "thirdProperty");
Contract.Requires<ArgumentNullException>(calculateValue != null, "calculateValue");
Contract.Ensures(this.firstProperty != null);
Contract.Ensures(this.secondProperty != null);
Contract.Ensures(this.thirdProperty != null);
Contract.Ensures(this.calculateValue != null);
RxMvvmConfiguration.EnsureSerializableDelegateIfUsingSerialization(calculateValue);
this.context = context;
this.firstProperty = firstProperty;
this.secondProperty = secondProperty;
this.thirdProperty = thirdProperty;
this.throttleTime = throttleTime;
this.calculateValue = calculateValue;
this.isLongRunningCalculation = isLongRunningCalculation;
Func<TFirst, TSecond, TThird, IDiscriminatedUnion<object, T, Exception>> calculate =
(first, second, third) =>
{
IDiscriminatedUnion<object, T, Exception> discriminatedUnion;
try
{
discriminatedUnion =
DiscriminatedUnion.First<object, T, Exception>(calculateValue(context, first, second, third));
}
catch (Exception e)
{
discriminatedUnion = DiscriminatedUnion.Second<object, T, Exception>(e);
}
return discriminatedUnion;
};
this.SetHelper(new CalculatedPropertyHelper(
(resultSubject, isCalculatingSubject) =>
{
CompositeDisposable d = new CompositeDisposable();
IScheduler scheduler = isLongRunningCalculation
? RxMvvmConfiguration.GetLongRunningCalculationScheduler()
: RxMvvmConfiguration.GetCalculationScheduler();
IObservable<Tuple<TFirst, TSecond, TThird>> o = firstProperty.CombineLatest(
secondProperty, thirdProperty, Tuple.Create);
o = throttleTime > TimeSpan.Zero ? o.Throttle(throttleTime, scheduler) : o.ObserveOn(scheduler);
d.Add(
o.Subscribe(
v =>
{
using (this.scheduledTask)
{
}
isCalculatingSubject.OnNext(true);
this.scheduledTask = scheduler.ScheduleAsync(
async (s, t) =>
{
try
{
await s.Yield(t).ConfigureAwait(true);
IDiscriminatedUnion<object, T, Exception> result = calculate(v.Item1, v.Item2, v.Item3);
await s.Yield(t).ConfigureAwait(true);
resultSubject.OnNext(result);
}
catch (OperationCanceledException)
{
}
catch (Exception e)
{
resultSubject.OnNext(
DiscriminatedUnion.Second<object, T, Exception>(e));
}
isCalculatingSubject.OnNext(false);
});
}));
return d;
}));
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncCalculatedPropertyWithContext{TContext,TFirst,TSecond,TThird,T}"/> class.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="context">
/// The serialization context.
/// </param>
[ContractVerification(false)]
// ReSharper disable UnusedParameter.Local
protected AsyncCalculatedPropertyWithContext(SerializationInfo info, StreamingContext context)
// ReSharper restore UnusedParameter.Local
: this(
(TContext)(info.GetValue("c", typeof(TContext)) ?? default(TContext)),
(IObservable<TFirst>)info.GetValue("p1", typeof(IObservable<TFirst>)),
(IObservable<TSecond>)info.GetValue("p2", typeof(IObservable<TSecond>)),
(IObservable<TThird>)info.GetValue("p3", typeof(IObservable<TThird>)),
(TimeSpan)(info.GetValue("t", typeof(TimeSpan)) ?? default(TimeSpan)),
(Func<TContext, TFirst, TSecond, TThird, T>)info.GetValue("f", typeof(Func<TContext, TFirst, TSecond, TThird, T>)),
(bool)info.GetValue("l", typeof(bool)))
{
}
/// <summary>
/// Gets the object data to serialize.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="streamingContext">
/// The serialization context.
/// </param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext streamingContext)
{
info.AddValue("c", this.context);
info.AddValue("p1", this.firstProperty);
info.AddValue("p2", this.secondProperty);
info.AddValue("p3", this.thirdProperty);
info.AddValue("t", this.throttleTime);
info.AddValue("f", this.calculateValue);
info.AddValue("l", this.isLongRunningCalculation);
}
/// <summary>
/// Disposes of the property.
/// </summary>
protected override void Dispose()
{
base.Dispose();
using (this.scheduledTask)
{
}
}
[ContractInvariantMethod]
private void CodeContractsInvariants()
{
Contract.Invariant(this.firstProperty != null);
Contract.Invariant(this.secondProperty != null);
Contract.Invariant(this.thirdProperty != null);
Contract.Invariant(this.calculateValue != null);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* 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 NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using Term = Lucene.Net.Index.Term;
using Directory = Lucene.Net.Store.Directory;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Search
{
/// <summary> Test of the DisjunctionMaxQuery.
///
/// </summary>
[TestFixture]
public class TestDisjunctionMaxQuery:LuceneTestCase
{
public TestDisjunctionMaxQuery()
{
InitBlock();
}
private void InitBlock()
{
sim = new TestSimilarity();
}
/// <summary>threshold for comparing floats </summary>
public const float SCORE_COMP_THRESH = 0.000001f;
/// <summary> Similarity to eliminate tf, idf and lengthNorm effects to
/// isolate test case.
///
/// <p/>
/// same as TestRankingSimilarity in TestRanking.zip from
/// http://issues.apache.org/jira/browse/LUCENE-323
/// </summary>
[Serializable]
private class TestSimilarity:DefaultSimilarity
{
public TestSimilarity()
{
}
public override float Tf(float freq)
{
if (freq > 0.0f)
return 1.0f;
else
return 0.0f;
}
public override float LengthNorm(System.String fieldName, int numTerms)
{
return 1.0f;
}
public override float Idf(int docFreq, int numDocs)
{
return 1.0f;
}
}
public Similarity sim;
public Directory index;
public IndexReader r;
public IndexSearcher s;
[SetUp]
public override void SetUp()
{
base.SetUp();
index = new RAMDirectory();
IndexWriter writer = new IndexWriter(index, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
writer.SetSimilarity(sim);
// hed is the most important field, dek is secondary
// d1 is an "ok" match for: albino elephant
{
Document d1 = new Document();
d1.Add(new Field("id", "d1", Field.Store.YES, Field.Index.NOT_ANALYZED)); //Field.Keyword("id", "d1"));
d1.Add(new Field("hed", "elephant", Field.Store.YES, Field.Index.ANALYZED)); //Field.Text("hed", "elephant"));
d1.Add(new Field("dek", "elephant", Field.Store.YES, Field.Index.ANALYZED)); //Field.Text("dek", "elephant"));
writer.AddDocument(d1);
}
// d2 is a "good" match for: albino elephant
{
Document d2 = new Document();
d2.Add(new Field("id", "d2", Field.Store.YES, Field.Index.NOT_ANALYZED)); //Field.Keyword("id", "d2"));
d2.Add(new Field("hed", "elephant", Field.Store.YES, Field.Index.ANALYZED)); //Field.Text("hed", "elephant"));
d2.Add(new Field("dek", "albino", Field.Store.YES, Field.Index.ANALYZED)); //Field.Text("dek", "albino"));
d2.Add(new Field("dek", "elephant", Field.Store.YES, Field.Index.ANALYZED)); //Field.Text("dek", "elephant"));
writer.AddDocument(d2);
}
// d3 is a "better" match for: albino elephant
{
Document d3 = new Document();
d3.Add(new Field("id", "d3", Field.Store.YES, Field.Index.NOT_ANALYZED)); //Field.Keyword("id", "d3"));
d3.Add(new Field("hed", "albino", Field.Store.YES, Field.Index.ANALYZED)); //Field.Text("hed", "albino"));
d3.Add(new Field("hed", "elephant", Field.Store.YES, Field.Index.ANALYZED)); //Field.Text("hed", "elephant"));
writer.AddDocument(d3);
}
// d4 is the "best" match for: albino elephant
{
Document d4 = new Document();
d4.Add(new Field("id", "d4", Field.Store.YES, Field.Index.NOT_ANALYZED)); //Field.Keyword("id", "d4"));
d4.Add(new Field("hed", "albino", Field.Store.YES, Field.Index.ANALYZED)); //Field.Text("hed", "albino"));
d4.Add(new Field("hed", "elephant", Field.Store.YES, Field.Index.ANALYZED)); //Field.Text("hed", "elephant"));
d4.Add(new Field("dek", "albino", Field.Store.YES, Field.Index.ANALYZED)); //Field.Text("dek", "albino"));
writer.AddDocument(d4);
}
writer.Close();
r = IndexReader.Open(index, true);
s = new IndexSearcher(r);
s.Similarity = sim;
}
[Test]
public virtual void TestSkipToFirsttimeMiss()
{
DisjunctionMaxQuery dq = new DisjunctionMaxQuery(0.0f);
dq.Add(Tq("id", "d1"));
dq.Add(Tq("dek", "DOES_NOT_EXIST"));
QueryUtils.Check(dq, s);
Weight dw = dq.Weight(s);
Scorer ds = dw.Scorer(r, true, false);
bool skipOk = ds.Advance(3) != DocIdSetIterator.NO_MORE_DOCS;
if (skipOk)
{
Assert.Fail("firsttime skipTo found a match? ... " + r.Document(ds.DocID()).Get("id"));
}
}
[Test]
public virtual void TestSkipToFirsttimeHit()
{
DisjunctionMaxQuery dq = new DisjunctionMaxQuery(0.0f);
dq.Add(Tq("dek", "albino"));
dq.Add(Tq("dek", "DOES_NOT_EXIST"));
QueryUtils.Check(dq, s);
Weight dw = dq.Weight(s);
Scorer ds = dw.Scorer(r, true, false);
Assert.IsTrue(ds.Advance(3) != DocIdSetIterator.NO_MORE_DOCS, "firsttime skipTo found no match");
Assert.AreEqual("d4", r.Document(ds.DocID()).Get("id"), "found wrong docid");
}
[Test]
public virtual void TestSimpleEqualScores1()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.0f);
q.Add(Tq("hed", "albino"));
q.Add(Tq("hed", "elephant"));
QueryUtils.Check(q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(4, h.Length, "all docs should match " + q.ToString());
float score = h[0].Score;
for (int i = 1; i < h.Length; i++)
{
Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same");
}
}
catch (System.ApplicationException e)
{
PrintHits("testSimpleEqualScores1", h, s);
throw e;
}
}
[Test]
public virtual void TestSimpleEqualScores2()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.0f);
q.Add(Tq("dek", "albino"));
q.Add(Tq("dek", "elephant"));
QueryUtils.Check(q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(3, h.Length, "3 docs should match " + q.ToString());
float score = h[0].Score;
for (int i = 1; i < h.Length; i++)
{
Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same");
}
}
catch (System.ApplicationException e)
{
PrintHits("testSimpleEqualScores2", h, s);
throw e;
}
}
[Test]
public virtual void TestSimpleEqualScores3()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.0f);
q.Add(Tq("hed", "albino"));
q.Add(Tq("hed", "elephant"));
q.Add(Tq("dek", "albino"));
q.Add(Tq("dek", "elephant"));
QueryUtils.Check(q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(4, h.Length, "all docs should match " + q.ToString());
float score = h[0].Score;
for (int i = 1; i < h.Length; i++)
{
Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same");
}
}
catch (System.ApplicationException e)
{
PrintHits("testSimpleEqualScores3", h, s);
throw e;
}
}
[Test]
public virtual void TestSimpleTiebreaker()
{
DisjunctionMaxQuery q = new DisjunctionMaxQuery(0.01f);
q.Add(Tq("dek", "albino"));
q.Add(Tq("dek", "elephant"));
QueryUtils.Check(q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(3, h.Length, "3 docs should match " + q.ToString());
Assert.AreEqual(s.Doc(h[0].Doc).Get("id"), "d2", "wrong first");
float score0 = h[0].Score;
float score1 = h[1].Score;
float score2 = h[2].Score;
Assert.IsTrue(score0 > score1, "d2 does not have better score then others: " + score0 + " >? " + score1);
Assert.AreEqual(score1, score2, SCORE_COMP_THRESH, "d4 and d1 don't have equal scores");
}
catch (System.ApplicationException e)
{
PrintHits("testSimpleTiebreaker", h, s);
throw e;
}
}
[Test]
public virtual void TestBooleanRequiredEqualScores()
{
BooleanQuery q = new BooleanQuery();
{
DisjunctionMaxQuery q1 = new DisjunctionMaxQuery(0.0f);
q1.Add(Tq("hed", "albino"));
q1.Add(Tq("dek", "albino"));
q.Add(q1, Occur.MUST); //true,false);
QueryUtils.Check(q1, s);
}
{
DisjunctionMaxQuery q2 = new DisjunctionMaxQuery(0.0f);
q2.Add(Tq("hed", "elephant"));
q2.Add(Tq("dek", "elephant"));
q.Add(q2, Occur.MUST); //true,false);
QueryUtils.Check(q2, s);
}
QueryUtils.Check(q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(3, h.Length, "3 docs should match " + q.ToString());
float score = h[0].Score;
for (int i = 1; i < h.Length; i++)
{
Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same");
}
}
catch (System.ApplicationException e)
{
PrintHits("testBooleanRequiredEqualScores1", h, s);
throw e;
}
}
[Test]
public virtual void TestBooleanOptionalNoTiebreaker()
{
BooleanQuery q = new BooleanQuery();
{
DisjunctionMaxQuery q1 = new DisjunctionMaxQuery(0.0f);
q1.Add(Tq("hed", "albino"));
q1.Add(Tq("dek", "albino"));
q.Add(q1, Occur.SHOULD); //false,false);
}
{
DisjunctionMaxQuery q2 = new DisjunctionMaxQuery(0.0f);
q2.Add(Tq("hed", "elephant"));
q2.Add(Tq("dek", "elephant"));
q.Add(q2, Occur.SHOULD); //false,false);
}
QueryUtils.Check(q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(4, h.Length, "4 docs should match " + q.ToString());
float score = h[0].Score;
for (int i = 1; i < h.Length - 1; i++)
{
/* note: -1 */
Assert.AreEqual(score, h[i].Score, SCORE_COMP_THRESH, "score #" + i + " is not the same");
}
Assert.AreEqual("d1", s.Doc(h[h.Length - 1].Doc).Get("id"), "wrong last");
float score1 = h[h.Length - 1].Score;
Assert.IsTrue(score > score1, "d1 does not have worse score then others: " + score + " >? " + score1);
}
catch (System.ApplicationException e)
{
PrintHits("testBooleanOptionalNoTiebreaker", h, s);
throw e;
}
}
[Test]
public virtual void TestBooleanOptionalWithTiebreaker()
{
BooleanQuery q = new BooleanQuery();
{
DisjunctionMaxQuery q1 = new DisjunctionMaxQuery(0.01f);
q1.Add(Tq("hed", "albino"));
q1.Add(Tq("dek", "albino"));
q.Add(q1, Occur.SHOULD); //false,false);
}
{
DisjunctionMaxQuery q2 = new DisjunctionMaxQuery(0.01f);
q2.Add(Tq("hed", "elephant"));
q2.Add(Tq("dek", "elephant"));
q.Add(q2, Occur.SHOULD); //false,false);
}
QueryUtils.Check(q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(4, h.Length, "4 docs should match " + q.ToString());
float score0 = h[0].Score;
float score1 = h[1].Score;
float score2 = h[2].Score;
float score3 = h[3].Score;
System.String doc0 = s.Doc(h[0].Doc).Get("id");
System.String doc1 = s.Doc(h[1].Doc).Get("id");
System.String doc2 = s.Doc(h[2].Doc).Get("id");
System.String doc3 = s.Doc(h[3].Doc).Get("id");
Assert.IsTrue(doc0.Equals("d2") || doc0.Equals("d4"), "doc0 should be d2 or d4: " + doc0);
Assert.IsTrue(doc1.Equals("d2") || doc1.Equals("d4"), "doc1 should be d2 or d4: " + doc0);
Assert.AreEqual(score0, score1, SCORE_COMP_THRESH, "score0 and score1 should match");
Assert.AreEqual("d3", doc2, "wrong third");
Assert.IsTrue(score1 > score2, "d3 does not have worse score then d2 and d4: " + score1 + " >? " + score2);
Assert.AreEqual("d1", doc3, "wrong fourth");
Assert.IsTrue(score2 > score3, "d1 does not have worse score then d3: " + score2 + " >? " + score3);
}
catch (System.ApplicationException e)
{
PrintHits("testBooleanOptionalWithTiebreaker", h, s);
throw e;
}
}
[Test]
public virtual void TestBooleanOptionalWithTiebreakerAndBoost()
{
BooleanQuery q = new BooleanQuery();
{
DisjunctionMaxQuery q1 = new DisjunctionMaxQuery(0.01f);
q1.Add(Tq("hed", "albino", 1.5f));
q1.Add(Tq("dek", "albino"));
q.Add(q1, Occur.SHOULD); //false,false);
}
{
DisjunctionMaxQuery q2 = new DisjunctionMaxQuery(0.01f);
q2.Add(Tq("hed", "elephant", 1.5f));
q2.Add(Tq("dek", "elephant"));
q.Add(q2, Occur.SHOULD); //false,false);
}
QueryUtils.Check(q, s);
ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs;
try
{
Assert.AreEqual(4, h.Length, "4 docs should match " + q.ToString());
float score0 = h[0].Score;
float score1 = h[1].Score;
float score2 = h[2].Score;
float score3 = h[3].Score;
System.String doc0 = s.Doc(h[0].Doc).Get("id");
System.String doc1 = s.Doc(h[1].Doc).Get("id");
System.String doc2 = s.Doc(h[2].Doc).Get("id");
System.String doc3 = s.Doc(h[3].Doc).Get("id");
Assert.AreEqual("d4", doc0, "doc0 should be d4: ");
Assert.AreEqual("d3", doc1, "doc1 should be d3: ");
Assert.AreEqual("d2", doc2, "doc2 should be d2: ");
Assert.AreEqual("d1", doc3, "doc3 should be d1: ");
Assert.IsTrue(score0 > score1, "d4 does not have a better score then d3: " + score0 + " >? " + score1);
Assert.IsTrue(score1 > score2, "d3 does not have a better score then d2: " + score1 + " >? " + score2);
Assert.IsTrue(score2 > score3, "d3 does not have a better score then d1: " + score2 + " >? " + score3);
}
catch (System.ApplicationException e)
{
PrintHits("testBooleanOptionalWithTiebreakerAndBoost", h, s);
throw e;
}
}
/// <summary>macro </summary>
protected internal virtual Query Tq(System.String f, System.String t)
{
return new TermQuery(new Term(f, t));
}
/// <summary>macro </summary>
protected internal virtual Query Tq(System.String f, System.String t, float b)
{
Query q = Tq(f, t);
q.Boost = b;
return q;
}
protected internal virtual void PrintHits(System.String test, ScoreDoc[] h, Searcher searcher)
{
System.Console.Error.WriteLine("------- " + test + " -------");
for (int i = 0; i < h.Length; i++)
{
Document d = searcher.Doc(h[i].Doc);
float score = h[i].Score;
System.Console.Error.WriteLine("#" + i + ": {0.000000000}" + score + " - " + d.Get("id"));
}
}
}
}
| |
// 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.ActiveDirectory
{
using System;
using System.Runtime.InteropServices;
using System.DirectoryServices;
using System.Diagnostics;
using System.ComponentModel;
using System.Globalization;
using System.Security.Permissions;
public enum NotificationStatus
{
NoNotification = 0,
IntraSiteOnly = 1,
NotificationAlways = 2
}
public enum ReplicationSpan
{
IntraSite = 0,
InterSite = 1
}
public class ReplicationConnection : IDisposable
{
internal DirectoryContext context = null;
internal DirectoryEntry cachedDirectoryEntry = null;
internal bool existingConnection = false;
private bool _disposed = false;
private bool _checkADAM = false;
private bool _isADAMServer = false;
private int _options = 0;
private string _connectionName = null;
private string _sourceServerName = null;
private string _destinationServerName = null;
private ActiveDirectoryTransportType _transport = ActiveDirectoryTransportType.Rpc;
private const string ADAMGuid = "1.2.840.113556.1.4.1851";
public static ReplicationConnection FindByName(DirectoryContext context, string name)
{
ValidateArgument(context, name);
// work with copy of the context
context = new DirectoryContext(context);
// bind to the rootdse to get the servername property
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
try
{
string serverDN = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ServerName);
string connectionContainer = "CN=NTDS Settings," + serverDN;
de = DirectoryEntryManager.GetDirectoryEntry(context, connectionContainer);
// doing the search to find the connection object based on its name
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=nTDSConnection)(objectCategory=NTDSConnection)(name=" + Utils.GetEscapedFilterValue(name) + "))",
new string[] { "distinguishedName" },
SearchScope.OneLevel,
false, /* no paged search */
false /* don't cache results */);
SearchResult srchResult = null;
try
{
srchResult = adSearcher.FindOne();
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
// object is not found since we cannot even find the container in which to search
throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ReplicationConnection), name);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
if (srchResult == null)
{
// no such connection object
Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ReplicationConnection), name);
throw e;
}
else
{
DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry();
return new ReplicationConnection(context, connectionEntry, name);
}
}
finally
{
de.Dispose();
}
}
internal ReplicationConnection(DirectoryContext context, DirectoryEntry connectionEntry, string name)
{
this.context = context;
cachedDirectoryEntry = connectionEntry;
_connectionName = name;
// this is an exising connection object
existingConnection = true;
}
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer) : this(context, name, sourceServer, null, ActiveDirectoryTransportType.Rpc)
{
}
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectorySchedule schedule) : this(context, name, sourceServer, schedule, ActiveDirectoryTransportType.Rpc)
{
}
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectoryTransportType transport) : this(context, name, sourceServer, null, transport)
{
}
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectorySchedule schedule, ActiveDirectoryTransportType transport)
{
ValidateArgument(context, name);
if (sourceServer == null)
throw new ArgumentNullException("sourceServer");
if (transport < ActiveDirectoryTransportType.Rpc || transport > ActiveDirectoryTransportType.Smtp)
throw new InvalidEnumArgumentException("value", (int)transport, typeof(ActiveDirectoryTransportType));
// work with copy of the context
context = new DirectoryContext(context);
ValidateTargetAndSourceServer(context, sourceServer);
this.context = context;
_connectionName = name;
_transport = transport;
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
try
{
string serverDN = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ServerName);
string connectionContainer = "CN=NTDS Settings," + serverDN;
de = DirectoryEntryManager.GetDirectoryEntry(context, connectionContainer);
// create the connection entry
string rdn = "cn=" + _connectionName;
rdn = Utils.GetEscapedPath(rdn);
cachedDirectoryEntry = de.Children.Add(rdn, "nTDSConnection");
// set all the properties
// sourceserver property
DirectoryContext sourceServerContext = sourceServer.Context;
de = DirectoryEntryManager.GetDirectoryEntry(sourceServerContext, WellKnownDN.RootDSE);
string serverName = (string)PropertyManager.GetPropertyValue(sourceServerContext, de, PropertyManager.ServerName);
serverName = "CN=NTDS Settings," + serverName;
cachedDirectoryEntry.Properties["fromServer"].Add(serverName);
// schedule property
if (schedule != null)
cachedDirectoryEntry.Properties["schedule"].Value = schedule.GetUnmanagedSchedule();
// transporttype property
string transportPath = Utils.GetDNFromTransportType(TransportType, context);
// verify that the transport is supported
de = DirectoryEntryManager.GetDirectoryEntry(context, transportPath);
try
{
de.Bind(true);
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
// if it is ADAM and transport type is SMTP, throw NotSupportedException.
DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp)
{
throw new NotSupportedException(SR.NotSupportTransportSMTP);
}
}
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
cachedDirectoryEntry.Properties["transportType"].Add(transportPath);
// enabledConnection property
cachedDirectoryEntry.Properties["enabledConnection"].Value = false;
// options
cachedDirectoryEntry.Properties["options"].Value = 0;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
de.Close();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing && cachedDirectoryEntry != null)
cachedDirectoryEntry.Dispose();
_disposed = true;
}
}
~ReplicationConnection()
{
Dispose(false); // finalizer is called => Dispose has not been called yet.
}
public string Name
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return _connectionName;
}
}
public string SourceServer
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// get the source server
if (_sourceServerName == null)
{
string sourceServerDN = (string)PropertyManager.GetPropertyValue(context, cachedDirectoryEntry, PropertyManager.FromServer);
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, sourceServerDN);
if (IsADAM)
{
int portnumber = (int)PropertyManager.GetPropertyValue(context, de, PropertyManager.MsDSPortLDAP);
string tmpServerName = (string)PropertyManager.GetPropertyValue(context, de.Parent, PropertyManager.DnsHostName);
if (portnumber != 389)
{
_sourceServerName = tmpServerName + ":" + portnumber;
}
}
else
{
_sourceServerName = (string)PropertyManager.GetPropertyValue(context, de.Parent, PropertyManager.DnsHostName);
}
}
return _sourceServerName;
}
}
public string DestinationServer
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (_destinationServerName == null)
{
DirectoryEntry NTDSObject = null;
DirectoryEntry serverObject = null;
try
{
NTDSObject = cachedDirectoryEntry.Parent;
serverObject = NTDSObject.Parent;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
string hostName = (string)PropertyManager.GetPropertyValue(context, serverObject, PropertyManager.DnsHostName);
if (IsADAM)
{
int portnumber = (int)PropertyManager.GetPropertyValue(context, NTDSObject, PropertyManager.MsDSPortLDAP);
if (portnumber != 389)
{
_destinationServerName = hostName + ":" + portnumber;
}
else
_destinationServerName = hostName;
}
else
_destinationServerName = hostName;
}
return _destinationServerName;
}
}
public bool Enabled
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// fetch the property value
try
{
if (cachedDirectoryEntry.Properties.Contains("enabledConnection"))
return (bool)cachedDirectoryEntry.Properties["enabledConnection"][0];
else
return false;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
cachedDirectoryEntry.Properties["enabledConnection"].Value = value;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public ActiveDirectoryTransportType TransportType
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// for exisint connection, we need to check its property, for newly created and not committed one, we just return
// the member variable value directly
if (existingConnection)
{
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["transportType"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
// if the property does not exist, then default is to RPC over IP
return ActiveDirectoryTransportType.Rpc;
}
else
{
return Utils.GetTransportTypeFromDN((string)propValue[0]);
}
}
else
return _transport;
}
}
public bool GeneratedByKcc
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_IS_GENERATED ( 1 << 0 ) object generated by DS, not admin
if ((_options & 0x1) == 0)
return false;
else
return true;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"];
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_IS_GENERATED ( 1 << 0 ) object generated by DS, not admin
if (value)
{
_options |= 0x1;
}
else
{
_options &= (~(0x1));
}
// put the value into cache
cachedDirectoryEntry.Properties["options"].Value = _options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public bool ReciprocalReplicationEnabled
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
// if the property does not exist, then default is to RPC over IP
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_TWOWAY_SYNC ( 1 << 1 ) force sync in opposite direction at end of sync
if ((_options & 0x2) == 0)
return false;
else
return true;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"];
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_TWOWAY_SYNC ( 1 << 1 ) force sync in opposite direction at end of sync
if (value == true)
{
_options |= 0x2;
}
else
{
_options &= (~(0x2));
}
// put the value into cache
cachedDirectoryEntry.Properties["options"].Value = _options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public NotificationStatus ChangeNotificationStatus
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
// if the property does not exist, then default is to RPC over IP
_options = 0;
}
else
{
_options = (int)propValue[0];
}
int overrideNotify = _options & 0x4;
int userNotify = _options & 0x8;
if (overrideNotify == 0x4 && userNotify == 0)
return NotificationStatus.NoNotification;
else if (overrideNotify == 0x4 && userNotify == 0x8)
return NotificationStatus.NotificationAlways;
else
return NotificationStatus.IntraSiteOnly;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (value < NotificationStatus.NoNotification || value > NotificationStatus.NotificationAlways)
throw new InvalidEnumArgumentException("value", (int)value, typeof(NotificationStatus));
try
{
PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"];
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
if (value == NotificationStatus.IntraSiteOnly)
{
_options &= (~(0x4));
_options &= (~(0x8));
}
else if (value == NotificationStatus.NoNotification)
{
_options |= (0x4);
_options &= (~(0x8));
}
else
{
_options |= (0x4);
_options |= (0x8);
}
// put the value into cache
cachedDirectoryEntry.Properties["options"].Value = _options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public bool DataCompressionEnabled
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
// if the property does not exist, then default is to RPC over IP
_options = 0;
}
else
{
_options = (int)propValue[0];
}
//NTDSCONN_OPT_DISABLE_INTERSITE_COMPRESSION (1 << 4)
// 0 - Compression of replication data enabled
// 1 - Compression of replication data disabled
if ((_options & 0x10) == 0)
return true;
else
return false;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"];
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
//NTDSCONN_OPT_DISABLE_INTERSITE_COMPRESSION (1 << 4)
// 0 - Compression of replication data enabled
// 1 - Compression of replication data disabled
if (value == false)
{
_options |= 0x10;
}
else
{
_options &= (~(0x10));
}
// put the value into cache
cachedDirectoryEntry.Properties["options"].Value = _options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public bool ReplicationScheduleOwnedByUser
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
// if the property does not exist, then default is to RPC over IP
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_USER_OWNED_SCHEDULE (1 << 5)
if ((_options & 0x20) == 0)
return false;
else
return true;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"];
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_USER_OWNED_SCHEDULE (1 << 5)
if (value == true)
{
_options |= 0x20;
}
else
{
_options &= (~(0x20));
}
// put the value into cache
cachedDirectoryEntry.Properties["options"].Value = _options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public ReplicationSpan ReplicationSpan
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// find out whether the site and the destination is in the same site
string destinationPath = (string)PropertyManager.GetPropertyValue(context, cachedDirectoryEntry, PropertyManager.FromServer);
string destinationSite = Utils.GetDNComponents(destinationPath)[3].Value;
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
string serverDN = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ServerName);
string serverSite = Utils.GetDNComponents(serverDN)[2].Value;
if (Utils.Compare(destinationSite, serverSite) == 0)
{
return ReplicationSpan.IntraSite;
}
else
{
return ReplicationSpan.InterSite;
}
}
}
public ActiveDirectorySchedule ReplicationSchedule
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
ActiveDirectorySchedule schedule = null;
bool scheduleExists = false;
try
{
scheduleExists = cachedDirectoryEntry.Properties.Contains("schedule");
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (scheduleExists)
{
byte[] tmpSchedule = (byte[])cachedDirectoryEntry.Properties["schedule"][0];
Debug.Assert(tmpSchedule != null && tmpSchedule.Length == 188);
schedule = new ActiveDirectorySchedule();
schedule.SetUnmanagedSchedule(tmpSchedule);
}
return schedule;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
if (value == null)
{
if (cachedDirectoryEntry.Properties.Contains("schedule"))
cachedDirectoryEntry.Properties["schedule"].Clear();
}
else
{
cachedDirectoryEntry.Properties["schedule"].Value = value.GetUnmanagedSchedule();
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
private bool IsADAM
{
get
{
if (!_checkADAM)
{
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
PropertyValueCollection values = null;
try
{
values = de.Properties["supportedCapabilities"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (values.Contains(ADAMGuid))
_isADAMServer = true;
}
return _isADAMServer;
}
}
public void Delete()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!existingConnection)
{
throw new InvalidOperationException(SR.CannotDelete);
}
else
{
try
{
cachedDirectoryEntry.Parent.Children.Remove(cachedDirectoryEntry);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public void Save()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
cachedDirectoryEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (!existingConnection)
{
existingConnection = true;
}
}
public override string ToString()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return Name;
}
public DirectoryEntry GetDirectoryEntry()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!existingConnection)
{
throw new InvalidOperationException(SR.CannotGetObject);
}
else
{
return DirectoryEntryManager.GetDirectoryEntryInternal(context, cachedDirectoryEntry.Path);
}
}
private static void ValidateArgument(DirectoryContext context, string name)
{
if (context == null)
throw new ArgumentNullException("context");
// the target of the scope must be server
if (context.Name == null || !context.isServer())
throw new ArgumentException(SR.DirectoryContextNeedHost);
if (name == null)
throw new ArgumentNullException("name");
if (name.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, "name");
}
private void ValidateTargetAndSourceServer(DirectoryContext context, DirectoryServer sourceServer)
{
bool targetIsDC = false;
DirectoryEntry targetDE = null;
DirectoryEntry sourceDE = null;
// first find out target is a dc or ADAM instance
targetDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
try
{
if (Utils.CheckCapability(targetDE, Capability.ActiveDirectory))
{
targetIsDC = true;
}
else if (!Utils.CheckCapability(targetDE, Capability.ActiveDirectoryApplicationMode))
{
// if it is also not an ADAM instance, it is invalid then
throw new ArgumentException(SR.DirectoryContextNeedHost, "context");
}
if (targetIsDC && !(sourceServer is DomainController))
{
// target and sourceServer are not of the same type
throw new ArgumentException(SR.ConnectionSourcServerShouldBeDC, "sourceServer");
}
else if (!targetIsDC && (sourceServer is DomainController))
{
// target and sourceServer are not of the same type
throw new ArgumentException(SR.ConnectionSourcServerShouldBeADAM, "sourceServer");
}
sourceDE = DirectoryEntryManager.GetDirectoryEntry(sourceServer.Context, WellKnownDN.RootDSE);
// now if they are both dc, we need to check whether they come from the same forest
if (targetIsDC)
{
string targetRoot = (string)PropertyManager.GetPropertyValue(context, targetDE, PropertyManager.RootDomainNamingContext);
string sourceRoot = (string)PropertyManager.GetPropertyValue(sourceServer.Context, sourceDE, PropertyManager.RootDomainNamingContext);
if (Utils.Compare(targetRoot, sourceRoot) != 0)
{
throw new ArgumentException(SR.ConnectionSourcServerSameForest, "sourceServer");
}
}
else
{
string targetRoot = (string)PropertyManager.GetPropertyValue(context, targetDE, PropertyManager.ConfigurationNamingContext);
string sourceRoot = (string)PropertyManager.GetPropertyValue(sourceServer.Context, sourceDE, PropertyManager.ConfigurationNamingContext);
if (Utils.Compare(targetRoot, sourceRoot) != 0)
{
throw new ArgumentException(SR.ConnectionSourcServerSameConfigSet, "sourceServer");
}
}
}
catch (COMException e)
{
ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (targetDE != null)
targetDE.Close();
if (sourceDE != null)
sourceDE.Close();
}
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://openapi-generator.tech
*/
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Org.OpenAPITools.Converters;
namespace Org.OpenAPITools.Models
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class Pipeline : IEquatable<Pipeline>
{
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name="_class", EmitDefaultValue=false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Organization
/// </summary>
[DataMember(Name="organization", EmitDefaultValue=false)]
public string Organization { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets DisplayName
/// </summary>
[DataMember(Name="displayName", EmitDefaultValue=false)]
public string DisplayName { get; set; }
/// <summary>
/// Gets or Sets FullName
/// </summary>
[DataMember(Name="fullName", EmitDefaultValue=false)]
public string FullName { get; set; }
/// <summary>
/// Gets or Sets WeatherScore
/// </summary>
[DataMember(Name="weatherScore", EmitDefaultValue=false)]
public int WeatherScore { get; set; }
/// <summary>
/// Gets or Sets EstimatedDurationInMillis
/// </summary>
[DataMember(Name="estimatedDurationInMillis", EmitDefaultValue=false)]
public int EstimatedDurationInMillis { get; set; }
/// <summary>
/// Gets or Sets LatestRun
/// </summary>
[DataMember(Name="latestRun", EmitDefaultValue=false)]
public PipelinelatestRun LatestRun { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Pipeline {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Organization: ").Append(Organization).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" DisplayName: ").Append(DisplayName).Append("\n");
sb.Append(" FullName: ").Append(FullName).Append("\n");
sb.Append(" WeatherScore: ").Append(WeatherScore).Append("\n");
sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n");
sb.Append(" LatestRun: ").Append(LatestRun).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((Pipeline)obj);
}
/// <summary>
/// Returns true if Pipeline instances are equal
/// </summary>
/// <param name="other">Instance of Pipeline to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Pipeline other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return
(
Class == other.Class ||
Class != null &&
Class.Equals(other.Class)
) &&
(
Organization == other.Organization ||
Organization != null &&
Organization.Equals(other.Organization)
) &&
(
Name == other.Name ||
Name != null &&
Name.Equals(other.Name)
) &&
(
DisplayName == other.DisplayName ||
DisplayName != null &&
DisplayName.Equals(other.DisplayName)
) &&
(
FullName == other.FullName ||
FullName != null &&
FullName.Equals(other.FullName)
) &&
(
WeatherScore == other.WeatherScore ||
WeatherScore.Equals(other.WeatherScore)
) &&
(
EstimatedDurationInMillis == other.EstimatedDurationInMillis ||
EstimatedDurationInMillis.Equals(other.EstimatedDurationInMillis)
) &&
(
LatestRun == other.LatestRun ||
LatestRun != null &&
LatestRun.Equals(other.LatestRun)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
var hashCode = 41;
// Suitable nullity checks etc, of course :)
if (Class != null)
hashCode = hashCode * 59 + Class.GetHashCode();
if (Organization != null)
hashCode = hashCode * 59 + Organization.GetHashCode();
if (Name != null)
hashCode = hashCode * 59 + Name.GetHashCode();
if (DisplayName != null)
hashCode = hashCode * 59 + DisplayName.GetHashCode();
if (FullName != null)
hashCode = hashCode * 59 + FullName.GetHashCode();
hashCode = hashCode * 59 + WeatherScore.GetHashCode();
hashCode = hashCode * 59 + EstimatedDurationInMillis.GetHashCode();
if (LatestRun != null)
hashCode = hashCode * 59 + LatestRun.GetHashCode();
return hashCode;
}
}
#region Operators
#pragma warning disable 1591
public static bool operator ==(Pipeline left, Pipeline right)
{
return Equals(left, right);
}
public static bool operator !=(Pipeline left, Pipeline right)
{
return !Equals(left, right);
}
#pragma warning restore 1591
#endregion Operators
}
}
| |
using UnityEngine;
using System.Collections.Generic;
#if UNITY_EDITOR
public class SgtQuads_Editor<T> : SgtEditor<T>
where T : SgtQuads
{
protected virtual void DrawMaterial(ref bool updateMaterial)
{
DrawDefault("Color", ref updateMaterial);
BeginError(Any(t => t.Brightness < 0.0f));
DrawDefault("Brightness", ref updateMaterial);
EndError();
DrawDefault("RenderQueue", ref updateMaterial);
DrawDefault("RenderQueueOffset", ref updateMaterial);
}
protected virtual void DrawAtlas(ref bool updateMaterial, ref bool updateMeshesAndModels)
{
BeginError(Any(t => t.MainTex == null));
DrawDefault("MainTex", ref updateMaterial);
EndError();
DrawDefault("Layout", ref updateMeshesAndModels);
BeginIndent();
if (Any(t => t.Layout == SgtQuadsLayoutType.Grid))
{
BeginError(Any(t => t.LayoutColumns <= 0));
DrawDefault("LayoutColumns", ref updateMeshesAndModels);
EndError();
BeginError(Any(t => t.LayoutRows <= 0));
DrawDefault("LayoutRows", ref updateMeshesAndModels);
EndError();
}
if (Any(t => t.Layout == SgtQuadsLayoutType.Custom))
{
DrawDefault("Rects", ref updateMeshesAndModels);
}
EndIndent();
}
}
#endif
// This is the base class for all starfields, providing a simple interface for generating meshes
// from a list of stars, as well as the material to render it
public abstract class SgtQuads : MonoBehaviour
{
[Tooltip("The color tint")]
public Color Color = Color.white;
[Tooltip("The amount the Color.rgb values are multiplied by")]
public float Brightness = 1.0f;
[Tooltip("The main texture of this material")]
public Texture MainTex;
[Tooltip("The layout of cells in the texture")]
public SgtQuadsLayoutType Layout = SgtQuadsLayoutType.Grid;
[Tooltip("The amount of columns in the texture")]
public int LayoutColumns = 1;
[Tooltip("The amount of rows in the texture")]
public int LayoutRows = 1;
[Tooltip("The rects of each cell in the texture")]
public List<Rect> Rects;
[Tooltip("The render queue group for this material")]
public SgtRenderQueue RenderQueue = SgtRenderQueue.Transparent;
[Tooltip("The render queue offset for this material")]
public int RenderQueueOffset;
// The models used to render all the quads (because each mesh can only store 65k vertices)
[HideInInspector]
public List<SgtQuadsModel> Models;
// The material applied to all models
[System.NonSerialized]
public Material Material;
[SerializeField]
private bool startCalled;
[System.NonSerialized]
private bool updateMaterialCalled;
[System.NonSerialized]
private bool updateMeshesAndModelsCalled;
protected static List<Vector4> tempCoords = new List<Vector4>();
protected abstract string ShaderName
{
get;
}
public void UpdateMainTex()
{
if (Material != null)
{
Material.SetTexture("_MainTex", MainTex);
}
}
[ContextMenu("Update Material")]
public void UpdateMaterial()
{
updateMaterialCalled = true;
if (Material == null)
{
Material = SgtHelper.CreateTempMaterial("Starfield (Generated)", ShaderName);
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.SetMaterial(Material);
}
}
}
}
BuildMaterial();
}
[ContextMenu("Update Meshes and Models")]
public void UpdateMeshesAndModels()
{
updateMeshesAndModelsCalled = true;
var starCount = BeginQuads();
var modelCount = 0;
// Build meshes and models until starCount reaches 0
if (starCount > 0)
{
BuildRects();
ConvertRectsToCoords();
while (starCount > 0)
{
var quadCount = Mathf.Min(starCount, SgtHelper.QuadsPerMesh);
var model = GetOrNewModel(modelCount);
var mesh = GetOrNewMesh(model);
model.SetMaterial(Material);
BuildMesh(mesh, modelCount * SgtHelper.QuadsPerMesh, quadCount);
modelCount += 1;
starCount -= quadCount;
}
}
// Remove any excess
if (Models != null)
{
for (var i = Models.Count - 1; i >= modelCount; i--)
{
SgtQuadsModel.Pool(Models[i]);
Models.RemoveAt(i);
}
}
EndQuads();
}
protected virtual void Start()
{
if (startCalled == false)
{
startCalled = true;
StartOnce();
}
}
protected virtual void OnEnable()
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.gameObject.SetActive(true);
}
}
}
if (startCalled == true)
{
CheckUpdateCalls();
}
}
protected virtual void OnDisable()
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.gameObject.SetActive(false);
}
}
}
}
protected virtual void OnDestroy()
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
SgtQuadsModel.MarkForDestruction(Models[i]);
}
}
SgtHelper.Destroy(Material);
}
protected abstract int BeginQuads();
protected abstract void EndQuads();
protected virtual void BuildMaterial()
{
Material.renderQueue = (int)RenderQueue + RenderQueueOffset;
Material.SetTexture("_MainTex", MainTex);
Material.SetColor("_Color", SgtHelper.Brighten(Color, Color.a * Brightness));
Material.SetFloat("_Scale", transform.lossyScale.x);
Material.SetFloat("_ScaleRecip", SgtHelper.Reciprocal(transform.lossyScale.x));
}
protected virtual void StartOnce()
{
CheckUpdateCalls();
}
protected void BuildRects()
{
if (Layout == SgtQuadsLayoutType.Grid)
{
if (Rects == null) Rects = new List<Rect>();
Rects.Clear();
if (LayoutColumns > 0 && LayoutRows > 0)
{
var invX = SgtHelper.Reciprocal(LayoutColumns);
var invY = SgtHelper.Reciprocal(LayoutRows );
for (var y = 0; y < LayoutRows; y++)
{
var offY = y * invY;
for (var x = 0; x < LayoutColumns; x++)
{
var offX = x * invX;
var rect = new Rect(offX, offY, invX, invY);
Rects.Add(rect);
}
}
}
}
}
protected abstract void BuildMesh(Mesh mesh, int starIndex, int starCount);
protected static void ExpandBounds(ref bool minMaxSet, ref Vector3 min, ref Vector3 max, Vector3 position, float radius)
{
var radius3 = new Vector3(radius, radius, radius);
if (minMaxSet == false)
{
minMaxSet = true;
min = position - radius3;
max = position + radius3;
}
min = Vector3.Min(min, position - radius3);
max = Vector3.Max(max, position + radius3);
}
private void ConvertRectsToCoords()
{
tempCoords.Clear();
if (Rects != null)
{
for (var i = 0; i < Rects.Count; i++)
{
var rect = Rects[i];
tempCoords.Add(new Vector4(rect.xMin, rect.yMin, rect.xMax, rect.yMax));
}
}
if (tempCoords.Count == 0) tempCoords.Add(default(Vector4));
}
private SgtQuadsModel GetOrNewModel(int index)
{
var model = default(SgtQuadsModel);
if (Models == null)
{
Models = new List<SgtQuadsModel>();
}
if (index < Models.Count)
{
model = Models[index];
}
else
{
Models.Add(model);
}
if (model == null || model.Quads != this)
{
model = Models[index] = SgtQuadsModel.Create(this);
model.SetMaterial(Material);
}
return model;
}
private Mesh GetOrNewMesh(SgtQuadsModel model)
{
var mesh = model.Mesh;
if (mesh == null)
{
mesh = SgtHelper.CreateTempMesh("Quads Mesh (Generated)");
model.SetMesh(mesh);
}
else
{
mesh.Clear(false);
}
return mesh;
}
private void CheckUpdateCalls()
{
if (updateMaterialCalled == false)
{
UpdateMaterial();
}
if (updateMeshesAndModelsCalled == false)
{
UpdateMeshesAndModels();
}
}
}
| |
using Qowaiv.Financial;
using System.Collections.ObjectModel;
namespace Qowaiv.Globalization;
internal partial struct CountryToCurrency
{
public static readonly ReadOnlyCollection<CountryToCurrency> All = new(new List<CountryToCurrency>
{
new(Country.AD, Currency.ADP),
new(Country.AD, Currency.EUR, new Date(2002, 01, 01)),
new(Country.AE, Currency.AED),
new(Country.AF, Currency.AFN),
new(Country.AG, Currency.XCD),
new(Country.AI, Currency.XCD),
new(Country.AL, Currency.ALL),
new(Country.AM, Currency.AMD),
new(Country.ANHH, Currency.ANG),
new(Country.AO, Currency.AOA),
new(Country.AR, Currency.ARS),
new(Country.AS, Currency.USD),
new(Country.AT, Currency.ATS),
new(Country.AT, Currency.EUR, new Date(2002, 01, 01)),
new(Country.AU, Currency.AUD),
new(Country.AW, Currency.AWG),
new(Country.AX, Currency.FIM),
new(Country.AX, Currency.EUR, new Date(2002, 01, 01)),
new(Country.AZ, Currency.AZN),
new(Country.BA, Currency.BAM),
new(Country.BB, Currency.BBD),
new(Country.BB, Currency.USD),
new(Country.BD, Currency.BDT),
new(Country.BE, Currency.BEF),
new(Country.BE, Currency.EUR, new Date(2002, 01, 01)),
new(Country.BF, Currency.XOF),
new(Country.BG, Currency.BGN),
new(Country.BH, Currency.BHD),
new(Country.BI, Currency.BIF),
new(Country.BJ, Currency.XOF),
new(Country.BL, Currency.FRF),
new(Country.BL, Currency.EUR, new Date(2002, 01, 01)),
new(Country.BM, Currency.BMD),
new(Country.BN, Currency.BND),
new(Country.BO, Currency.BOB),
new(Country.BQ, Currency.USD),
new(Country.BR, Currency.BRL),
new(Country.BS, Currency.BSD),
new(Country.BT, Currency.BTN),
new(Country.BUMM, Currency.MMK),
new(Country.BV, Currency.NOK),
new(Country.BW, Currency.BWP),
new(Country.BY, Currency.BYR),
new(Country.BZ, Currency.BZD),
new(Country.CA, Currency.CAD),
new(Country.CC, Currency.AUD),
new(Country.CD, Currency.CDF),
new(Country.CF, Currency.XAF),
new(Country.CG, Currency.XAF),
new(Country.CH, Currency.CHF),
new(Country.CI, Currency.XOF),
new(Country.CK, Currency.NZD),
new(Country.CL, Currency.CLP),
new(Country.CM, Currency.XAF),
new(Country.CN, Currency.CNY),
new(Country.CO, Currency.COP),
new(Country.CR, Currency.CRC),
new(Country.CSHH, Currency.CSK),
new(Country.CSXX, Currency.CSD),
new(Country.CU, Currency.CUC),
new(Country.CU, Currency.CUP),
new(Country.CV, Currency.CVE),
new(Country.CW, Currency.ANG),
new(Country.CX, Currency.AUD),
new(Country.CY, Currency.CYP),
new(Country.CY, Currency.EUR, new Date(2008, 01, 01)),
new(Country.CZ, Currency.CZK),
new(Country.DDDE, Currency.DDM),
new(Country.DDDE, Currency.DEM, new Date(1990, 07, 01)),
new(Country.DE, Currency.DEM),
new(Country.DE, Currency.EUR, new Date(2002, 01, 01)),
new(Country.DJ, Currency.DJF),
new(Country.DK, Currency.DKK),
new(Country.DM, Currency.XCD),
new(Country.DO, Currency.DOP),
new(Country.DZ, Currency.DZD),
new(Country.EC, Currency.ECS),
new(Country.EC, Currency.USD, new Date(2000, 03, 13)),
new(Country.EE, Currency.EEK),
new(Country.EE, Currency.EUR, new Date(2011, 01, 01)),
new(Country.EG, Currency.EGP),
new(Country.EH, Currency.MAD),
new(Country.ER, Currency.ERN),
new(Country.ES, Currency.ESP),
new(Country.ES, Currency.EUR, new Date(2002, 01, 01)),
new(Country.ET, Currency.ETB),
new(Country.FI, Currency.FIM),
new(Country.FI, Currency.EUR, new Date(2002, 01, 01)),
new(Country.FJ, Currency.FJD),
new(Country.FK, Currency.FKP),
new(Country.FM, Currency.USD),
new(Country.FO, Currency.DKK),
new(Country.FR, Currency.FRF),
new(Country.FR, Currency.EUR, new Date(2002, 01, 01)),
new(Country.GA, Currency.XAF),
new(Country.GB, Currency.GBP),
new(Country.GD, Currency.XCD),
new(Country.GE, Currency.GEL),
new(Country.GF, Currency.FRF),
new(Country.GF, Currency.EUR, new Date(2002, 01, 01)),
new(Country.GG, Currency.GBP),
new(Country.GH, Currency.GHS),
new(Country.GI, Currency.GIP),
new(Country.GL, Currency.DKK),
new(Country.GM, Currency.GMD),
new(Country.GN, Currency.GNF),
new(Country.GP, Currency.FRF),
new(Country.GP, Currency.EUR, new Date(2002, 01, 01)),
new(Country.GQ, Currency.XAF),
new(Country.GR, Currency.GRD),
new(Country.GR, Currency.EUR, new Date(2002, 01, 01)),
new(Country.GS, Currency.GBP),
new(Country.GT, Currency.GTQ),
new(Country.GU, Currency.USD),
new(Country.GW, Currency.XOF),
new(Country.GY, Currency.GYD),
new(Country.HK, Currency.HKD),
new(Country.HM, Currency.AUD),
new(Country.HN, Currency.HNL),
new(Country.HR, Currency.HRK),
new(Country.HT, Currency.HTG),
new(Country.HT, Currency.USD),
new(Country.HU, Currency.HUF),
new(Country.ID, Currency.IDR),
new(Country.IE, Currency.IEP),
new(Country.IE, Currency.EUR, new Date(2002, 01, 01)),
new(Country.IL, Currency.ILS),
new(Country.IM, Currency.GBP),
new(Country.IN, Currency.INR),
new(Country.IO, Currency.GBP),
new(Country.IQ, Currency.IQD),
new(Country.IR, Currency.IRR),
new(Country.IS, Currency.ISK),
new(Country.IT, Currency.ITL),
new(Country.IT, Currency.EUR, new Date(2002, 01, 01)),
new(Country.JE, Currency.GBP),
new(Country.JM, Currency.JMD),
new(Country.JO, Currency.JOD),
new(Country.JP, Currency.JPY),
new(Country.KE, Currency.KES),
new(Country.KG, Currency.KGS),
new(Country.KH, Currency.KHR),
new(Country.KI, Currency.AUD),
new(Country.KM, Currency.KMF),
new(Country.KN, Currency.XCD),
new(Country.KP, Currency.KPW),
new(Country.KR, Currency.KRW),
new(Country.KW, Currency.KWD),
new(Country.KY, Currency.KYD),
new(Country.KZ, Currency.KZT),
new(Country.LA, Currency.LAK),
new(Country.LB, Currency.LBP),
new(Country.LC, Currency.XCD),
new(Country.LI, Currency.CHF),
new(Country.LK, Currency.LKR),
new(Country.LR, Currency.LRD),
new(Country.LS, Currency.LSL),
new(Country.LT, Currency.LTL),
new(Country.LT, Currency.EUR, new Date(2015, 01, 01)),
new(Country.LU, Currency.LUF),
new(Country.LU, Currency.EUR, new Date(2002, 01, 01)),
new(Country.LV, Currency.LVL),
new(Country.LV, Currency.EUR, new Date(2014, 01, 01)),
new(Country.LY, Currency.LYD),
new(Country.MA, Currency.MAD),
new(Country.MC, Currency.MCF),
new(Country.MC, Currency.EUR, new Date(2002, 01, 01)),
new(Country.MD, Currency.MDL),
new(Country.ME, Currency.EUR, new Date(2002, 01, 01)),
new(Country.MF, Currency.EUR),
new(Country.MG, Currency.MGA),
new(Country.MH, Currency.USD),
new(Country.MK, Currency.MKD),
new(Country.ML, Currency.XOF),
new(Country.MM, Currency.MMK),
new(Country.MN, Currency.MNT),
new(Country.MO, Currency.HKD),
new(Country.MO, Currency.MOP),
new(Country.MP, Currency.USD),
new(Country.MQ, Currency.FRF),
new(Country.MQ, Currency.EUR, new Date(2002, 01, 01)),
new(Country.MR, Currency.MRO),
new(Country.MS, Currency.XCD),
new(Country.MT, Currency.MTL),
new(Country.MT, Currency.EUR, new Date(2008, 01, 01)),
new(Country.MU, Currency.MUR),
new(Country.MV, Currency.MVR),
new(Country.MW, Currency.MWK),
new(Country.MX, Currency.MXN),
new(Country.MX, Currency.MXV),
new(Country.MY, Currency.MYR),
new(Country.MZ, Currency.MZN),
new(Country.NA, Currency.NAD),
new(Country.NC, Currency.XPF),
new(Country.NE, Currency.XOF),
new(Country.NF, Currency.AUD),
new(Country.NG, Currency.NGN),
new(Country.NI, Currency.NIO),
new(Country.NL, Currency.NLG),
new(Country.NL, Currency.NLG),
new(Country.NL, Currency.EUR, new Date(2002, 01, 01)),
new(Country.NO, Currency.NOK),
new(Country.NP, Currency.NPR),
new(Country.NR, Currency.AUD),
new(Country.NU, Currency.NZD),
new(Country.NZ, Currency.NZD),
new(Country.OM, Currency.OMR),
new(Country.PA, Currency.PAB),
new(Country.PA, Currency.USD),
new(Country.PE, Currency.PEN),
new(Country.PF, Currency.XPF),
new(Country.PG, Currency.PGK),
new(Country.PH, Currency.PHP),
new(Country.PK, Currency.PKR),
new(Country.PL, Currency.PLN),
new(Country.PM, Currency.FRF),
new(Country.PM, Currency.EUR, new Date(2002, 01, 01)),
new(Country.PN, Currency.NZD),
new(Country.PR, Currency.USD),
new(Country.PS, Currency.ILS),
new(Country.PT, Currency.PTE),
new(Country.PT, Currency.EUR, new Date(2002, 01, 01)),
new(Country.PW, Currency.USD),
new(Country.PY, Currency.PYG),
new(Country.QA, Currency.QAR),
new(Country.RE, Currency.FRF),
new(Country.RE, Currency.EUR, new Date(2002, 01, 01)),
new(Country.RO, Currency.RON),
new(Country.RS, Currency.RSD),
new(Country.RU, Currency.RUB),
new(Country.RW, Currency.RWF),
new(Country.SA, Currency.SAR),
new(Country.SB, Currency.SBD),
new(Country.SC, Currency.SCR),
new(Country.SD, Currency.SDG),
new(Country.SE, Currency.SEK),
new(Country.SG, Currency.SGD),
new(Country.SH, Currency.GBP),
new(Country.SH, Currency.SHP),
new(Country.SI, Currency.SIT),
new(Country.SI, Currency.EUR, new Date(2007, 01, 01)),
new(Country.SJ, Currency.NOK),
new(Country.SK, Currency.SKK),
new(Country.SK, Currency.EUR, new Date(2009, 01, 01)),
new(Country.SL, Currency.SLL),
new(Country.SM, Currency.SML),
new(Country.SM, Currency.EUR, new Date(2002, 01, 01)),
new(Country.SN, Currency.XOF),
new(Country.SO, Currency.SOS),
new(Country.SR, Currency.SRD),
new(Country.SS, Currency.SSP),
new(Country.ST, Currency.STD),
new(Country.SUHH, Currency.SUR),
new(Country.SV, Currency.USD),
new(Country.SX, Currency.ANG),
new(Country.SY, Currency.SYP),
new(Country.SZ, Currency.SZL),
new(Country.TC, Currency.USD),
new(Country.TD, Currency.XAF),
new(Country.TF, Currency.FRF),
new(Country.TF, Currency.EUR, new Date(2002, 01, 01)),
new(Country.TG, Currency.XOF),
new(Country.TH, Currency.THB),
new(Country.TJ, Currency.TJS),
new(Country.TK, Currency.NZD),
new(Country.TL, Currency.USD),
new(Country.TM, Currency.TMT),
new(Country.TN, Currency.TND),
new(Country.TO, Currency.TOP),
new(Country.TR, Currency.TRY),
new(Country.TT, Currency.TTD),
new(Country.TV, Currency.AUD),
new(Country.TW, Currency.TWD),
new(Country.TZ, Currency.TZS),
new(Country.UA, Currency.UAH),
new(Country.UG, Currency.UGX),
new(Country.UM, Currency.USD),
new(Country.US, Currency.USD),
new(Country.UY, Currency.UYU),
new(Country.UZ, Currency.UZS),
new(Country.VA, Currency.VAL),
new(Country.VA, Currency.EUR, new Date(2002, 01, 01)),
new(Country.VC, Currency.XCD),
new(Country.VE, Currency.VEF),
new(Country.VG, Currency.USD),
new(Country.VI, Currency.USD),
new(Country.VN, Currency.VND),
new(Country.VU, Currency.VUV),
new(Country.WF, Currency.XPF),
new(Country.WS, Currency.WST),
new(Country.XK, Currency.EUR, new Date(2008, 02, 01)),
new(Country.YE, Currency.YER),
new(Country.YT, Currency.FRF),
new(Country.YT, Currency.EUR, new Date(2002, 01, 01)),
new(Country.YUCS, Currency.YUD, new Date(1961, 12, 31)),
new(Country.YUCS, Currency.YUN, new Date(1985, 12, 31)),
new(Country.YUCS, Currency.YUR, new Date(1988, 06, 30)),
new(Country.YUCS, Currency.YOU, new Date(1989, 09, 30)),
new(Country.YUCS, Currency.YUG, new Date(1989, 12, 31)),
new(Country.YUCS, Currency.YUM, new Date(1990, 01, 23)),
new(Country.ZA, Currency.ZAR),
new(Country.ZM, Currency.ZMW),
new(Country.ZRCD, Currency.ZRZ),
new(Country.ZRCD, Currency.ZRN, new Date(1993, 01, 01)),
new(Country.ZW, Currency.ZWC, new Date(1966, 02, 16)),
new(Country.ZW, Currency.ZWD, new Date(1976, 04, 17)),
new(Country.ZW, Currency.ZWN, new Date(2002, 07, 31)),
new(Country.ZW, Currency.ZWR, new Date(2004, 07, 31)),
new(Country.ZW, Currency.ZWL, new Date(2005, 02, 02)),
new(Country.ZW, Currency.USD, new Date(2009, 04, 12)),
new(Country.HVBF, Currency.XOF),
new(Country.BQAQ, Currency.GBP),
});
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using MyApp.Areas.HelpPage.Models;
namespace MyApp.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using System.Text;
using Xunit;
namespace System.Security.Cryptography.Encryption.Tests.Asymmetric
{
public static class CryptoStreamTests
{
[Fact]
public static void Ctor()
{
var transform = new IdentityTransform(1, 1, true);
Assert.Throws<ArgumentException>(() => new CryptoStream(new MemoryStream(), transform, (CryptoStreamMode)12345));
Assert.Throws<ArgumentException>(() => new CryptoStream(new MemoryStream(new byte[0], writable: false), transform, CryptoStreamMode.Write));
Assert.Throws<ArgumentException>(() => new CryptoStream(new CryptoStream(new MemoryStream(new byte[0]), transform, CryptoStreamMode.Write), transform, CryptoStreamMode.Read));
}
[Theory]
[InlineData(64, 64, true)]
[InlineData(64, 128, true)]
[InlineData(128, 64, true)]
[InlineData(1, 1, true)]
[InlineData(37, 24, true)]
[InlineData(128, 3, true)]
[InlineData(8192, 64, true)]
[InlineData(64, 64, false)]
public static void Roundtrip(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks)
{
ICryptoTransform encryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks);
ICryptoTransform decryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks);
var stream = new MemoryStream();
using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
{
Assert.True(encryptStream.CanWrite);
Assert.False(encryptStream.CanRead);
Assert.False(encryptStream.CanSeek);
Assert.False(encryptStream.HasFlushedFinalBlock);
Assert.Throws<NotSupportedException>(() => encryptStream.SetLength(1));
Assert.Throws<NotSupportedException>(() => encryptStream.Length);
Assert.Throws<NotSupportedException>(() => encryptStream.Position);
Assert.Throws<NotSupportedException>(() => encryptStream.Position = 0);
Assert.Throws<NotSupportedException>(() => encryptStream.Seek(0, SeekOrigin.Begin));
Assert.Throws<NotSupportedException>(() => encryptStream.Read(new byte[0], 0, 0));
Assert.Throws<NullReferenceException>(() => encryptStream.Write(null, 0, 0)); // No arg validation on buffer?
Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1));
Assert.Throws<ArgumentException>(() => encryptStream.Write(new byte[3], 1, 4));
byte[] toWrite = Encoding.UTF8.GetBytes(LoremText);
// Write it all at once
encryptStream.Write(toWrite, 0, toWrite.Length);
Assert.False(encryptStream.HasFlushedFinalBlock);
// Write in chunks
encryptStream.Write(toWrite, 0, toWrite.Length / 2);
encryptStream.Write(toWrite, toWrite.Length / 2, toWrite.Length - (toWrite.Length / 2));
Assert.False(encryptStream.HasFlushedFinalBlock);
// Write one byte at a time
for (int i = 0; i < toWrite.Length; i++)
{
encryptStream.WriteByte(toWrite[i]);
}
Assert.False(encryptStream.HasFlushedFinalBlock);
// Write async
encryptStream.WriteAsync(toWrite, 0, toWrite.Length).GetAwaiter().GetResult();
Assert.False(encryptStream.HasFlushedFinalBlock);
// Flush (nops)
encryptStream.Flush();
encryptStream.FlushAsync().GetAwaiter().GetResult();
encryptStream.FlushFinalBlock();
Assert.Throws<NotSupportedException>(() => encryptStream.FlushFinalBlock());
Assert.True(encryptStream.HasFlushedFinalBlock);
Assert.True(stream.Length > 0);
}
// Read/decrypt using Read
stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
{
Assert.False(decryptStream.CanWrite);
Assert.True(decryptStream.CanRead);
Assert.False(decryptStream.CanSeek);
Assert.False(decryptStream.HasFlushedFinalBlock);
Assert.Throws<NotSupportedException>(() => decryptStream.SetLength(1));
Assert.Throws<NotSupportedException>(() => decryptStream.Length);
Assert.Throws<NotSupportedException>(() => decryptStream.Position);
Assert.Throws<NotSupportedException>(() => decryptStream.Position = 0);
Assert.Throws<NotSupportedException>(() => decryptStream.Seek(0, SeekOrigin.Begin));
Assert.Throws<NotSupportedException>(() => decryptStream.Write(new byte[0], 0, 0));
Assert.Throws<NullReferenceException>(() => decryptStream.Read(null, 0, 0)); // No arg validation on buffer?
Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1));
Assert.Throws<ArgumentException>(() => decryptStream.Read(new byte[3], 1, 4));
using (StreamReader reader = new StreamReader(decryptStream))
{
Assert.Equal(
LoremText + LoremText + LoremText + LoremText,
reader.ReadToEnd());
}
}
// Read/decrypt using ReadToEnd
stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
using (StreamReader reader = new StreamReader(decryptStream))
{
Assert.Equal(
LoremText + LoremText + LoremText + LoremText,
reader.ReadToEndAsync().GetAwaiter().GetResult());
}
// Read/decrypt using a small buffer to force multiple calls to Read
stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
using (StreamReader reader = new StreamReader(decryptStream, Encoding.UTF8, true, bufferSize: 10))
{
Assert.Equal(
LoremText + LoremText + LoremText + LoremText,
reader.ReadToEndAsync().GetAwaiter().GetResult());
}
}
[Fact]
public static void NestedCryptoStreams()
{
ICryptoTransform encryptor = new IdentityTransform(1, 1, true);
using (MemoryStream output = new MemoryStream())
using (CryptoStream encryptStream1 = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
using (CryptoStream encryptStream2 = new CryptoStream(encryptStream1, encryptor, CryptoStreamMode.Write))
{
encryptStream2.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
}
}
[Fact]
public static void MultipleDispose()
{
ICryptoTransform encryptor = new IdentityTransform(1, 1, true);
using (MemoryStream output = new MemoryStream())
using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
{
encryptStream.Dispose();
}
}
private const string LoremText =
@"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa.
Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.
Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Proin pharetra nonummy pede. Mauris et orci.
Aenean nec lorem. In porttitor. Donec laoreet nonummy augue.
Suspendisse dui purus, scelerisque at, vulputate vitae, pretium mattis, nunc. Mauris eget neque at sem venenatis eleifend.
Ut nonummy.";
private sealed class IdentityTransform : ICryptoTransform
{
private readonly int _inputBlockSize, _outputBlockSize;
private readonly bool _canTransformMultipleBlocks;
private long _writePos, _readPos;
private MemoryStream _stream;
internal IdentityTransform(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks)
{
_inputBlockSize = inputBlockSize;
_outputBlockSize = outputBlockSize;
_canTransformMultipleBlocks = canTransformMultipleBlocks;
_stream = new MemoryStream();
}
public bool CanReuseTransform { get { return true; } }
public bool CanTransformMultipleBlocks { get { return _canTransformMultipleBlocks; } }
public int InputBlockSize { get { return _inputBlockSize; } }
public int OutputBlockSize { get { return _outputBlockSize; } }
public void Dispose() { }
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
_stream.Position = _writePos;
_stream.Write(inputBuffer, inputOffset, inputCount);
_writePos = _stream.Position;
_stream.Position = _readPos;
int copied = _stream.Read(outputBuffer, outputOffset, outputBuffer.Length - outputOffset);
_readPos = _stream.Position;
return copied;
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
_stream.Position = _writePos;
_stream.Write(inputBuffer, inputOffset, inputCount);
_stream.Position = _readPos;
long len = _stream.Length - _stream.Position;
byte[] outputBuffer = new byte[len];
_stream.Read(outputBuffer, 0, outputBuffer.Length);
_stream = new MemoryStream();
_writePos = 0;
_readPos = 0;
return outputBuffer;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Npgsql;
using OpenMetaverse;
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
namespace OpenSim.Data.PGSQL
{
public class PGSQLGenericTableHandler<T> : PGSqlFramework where T : class, new()
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_ConnectionString;
protected PGSQLManager m_database; //used for parameter type translation
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
protected Dictionary<string, string> m_FieldTypes = new Dictionary<string, string>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public PGSQLGenericTableHandler(string connectionString,
string realm, string storeName)
: base(connectionString)
{
m_Realm = realm;
m_ConnectionString = connectionString;
if (storeName != String.Empty)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, storeName);
m.Update();
}
}
m_database = new PGSQLManager(m_ConnectionString);
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
LoadFieldTypes();
if (fields.Length == 0)
return;
foreach (FieldInfo f in fields)
{
if (f.Name != "Data")
m_Fields[f.Name] = f;
else
m_DataField = f;
}
}
private void LoadFieldTypes()
{
m_FieldTypes = new Dictionary<string, string>();
string query = string.Format(@"select column_name,data_type
from INFORMATION_SCHEMA.COLUMNS
where table_name = lower('{0}');
", m_Realm);
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn))
{
conn.Open();
using (NpgsqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// query produces 0 to many rows of single column, so always add the first item in each row
m_FieldTypes.Add((string)rdr[0], (string)rdr[1]);
}
}
}
}
private void CheckColumnNames(NpgsqlDataReader reader)
{
if (m_ColumnNames != null)
return;
m_ColumnNames = new List<string>();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
if (row["ColumnName"] != null &&
(!m_Fields.ContainsKey(row["ColumnName"].ToString())))
m_ColumnNames.Add(row["ColumnName"].ToString());
}
}
// TODO GET CONSTRAINTS FROM POSTGRESQL
private List<string> GetConstraints()
{
List<string> constraints = new List<string>();
string query = string.Format(@"SELECT kcu.column_name
FROM information_schema.table_constraints tc
LEFT JOIN information_schema.key_column_usage kcu
ON tc.constraint_catalog = kcu.constraint_catalog
AND tc.constraint_schema = kcu.constraint_schema
AND tc.constraint_name = kcu.constraint_name
LEFT JOIN information_schema.referential_constraints rc
ON tc.constraint_catalog = rc.constraint_catalog
AND tc.constraint_schema = rc.constraint_schema
AND tc.constraint_name = rc.constraint_name
LEFT JOIN information_schema.constraint_column_usage ccu
ON rc.unique_constraint_catalog = ccu.constraint_catalog
AND rc.unique_constraint_schema = ccu.constraint_schema
AND rc.unique_constraint_name = ccu.constraint_name
where tc.table_name = lower('{0}')
and lower(tc.constraint_type) in ('primary key')
and kcu.column_name is not null
;", m_Realm);
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn))
{
conn.Open();
using (NpgsqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// query produces 0 to many rows of single column, so always add the first item in each row
constraints.Add((string)rdr[0]);
}
}
return constraints;
}
}
public virtual T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public virtual T[] Get(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return new T[0];
List<string> terms = new List<string>();
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
for (int i = 0; i < fields.Length; i++)
{
if ( m_FieldTypes.ContainsKey(fields[i]) )
cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]]));
else
cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
terms.Add(" \"" + fields[i] + "\" = :" + fields[i]);
}
string where = String.Join(" AND ", terms.ToArray());
string query = String.Format("SELECT * FROM {0} WHERE {1}",
m_Realm, where);
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
return DoQuery(cmd);
}
}
protected T[] DoQuery(NpgsqlCommand cmd)
{
List<T> result = new List<T>();
if (cmd.Connection == null)
{
cmd.Connection = new NpgsqlConnection(m_connectionString);
}
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
if (reader == null)
return new T[0];
CheckColumnNames(reader);
while (reader.Read())
{
T row = new T();
foreach (string name in m_Fields.Keys)
{
if (m_Fields[name].GetValue(row) is bool)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v != 0 ? true : false);
}
else if (m_Fields[name].GetValue(row) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(reader[name].ToString(), out uuid);
m_Fields[name].SetValue(row, uuid);
}
else if (m_Fields[name].GetValue(row) is int)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else
{
m_Fields[name].SetValue(row, reader[name]);
}
}
if (m_DataField != null)
{
Dictionary<string, string> data =
new Dictionary<string, string>();
foreach (string col in m_ColumnNames)
{
data[col] = reader[col].ToString();
if (data[col] == null)
data[col] = String.Empty;
}
m_DataField.SetValue(row, data);
}
result.Add(row);
}
return result.ToArray();
}
}
public virtual T[] Get(string where)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
string query = String.Format("SELECT * FROM {0} WHERE {1}",
m_Realm, where);
cmd.Connection = conn;
cmd.CommandText = query;
//m_log.WarnFormat("[PGSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where);
conn.Open();
return DoQuery(cmd);
}
}
public virtual T[] Get(string where, NpgsqlParameter parameter)
{
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
string query = String.Format("SELECT * FROM {0} WHERE {1}",
m_Realm, where);
cmd.Connection = conn;
cmd.CommandText = query;
cmd.Parameters.Add(parameter);
conn.Open();
return DoQuery(cmd);
}
}
public virtual bool Store(T row)
{
List<string> constraintFields = GetConstraints();
List<KeyValuePair<string, string>> constraints = new List<KeyValuePair<string, string>>();
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
StringBuilder query = new StringBuilder();
List<String> names = new List<String>();
List<String> values = new List<String>();
foreach (FieldInfo fi in m_Fields.Values)
{
names.Add(fi.Name);
values.Add(":" + fi.Name);
// Temporarily return more information about what field is unexpectedly null for
// http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the
// InventoryTransferModule or we may be required to substitute a DBNull here.
if (fi.GetValue(row) == null)
throw new NullReferenceException(
string.Format(
"[PGSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null",
fi.Name, row));
if (constraintFields.Count > 0 && constraintFields.Contains(fi.Name))
{
constraints.Add(new KeyValuePair<string, string>(fi.Name, fi.GetValue(row).ToString() ));
}
if (m_FieldTypes.ContainsKey(fi.Name))
cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row), m_FieldTypes[fi.Name]));
else
cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row)));
}
if (m_DataField != null)
{
Dictionary<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key))
{
constraints.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Key));
}
names.Add(kvp.Key);
values.Add(":" + kvp.Key);
if (m_FieldTypes.ContainsKey(kvp.Key))
cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value, m_FieldTypes[kvp.Key]));
else
cmd.Parameters.Add(m_database.CreateParameter("" + kvp.Key, kvp.Value));
}
}
query.AppendFormat("UPDATE {0} SET ", m_Realm);
int i = 0;
for (i = 0; i < names.Count - 1; i++)
{
query.AppendFormat("\"{0}\" = {1}, ", names[i], values[i]);
}
query.AppendFormat("\"{0}\" = {1} ", names[i], values[i]);
if (constraints.Count > 0)
{
List<string> terms = new List<string>();
for (int j = 0; j < constraints.Count; j++)
{
terms.Add(String.Format(" \"{0}\" = :{0}", constraints[j].Key));
}
string where = String.Join(" AND ", terms.ToArray());
query.AppendFormat(" WHERE {0} ", where);
}
cmd.Connection = conn;
cmd.CommandText = query.ToString();
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
//m_log.WarnFormat("[PGSQLGenericTable]: Updating {0}", m_Realm);
return true;
}
else
{
// assume record has not yet been inserted
query = new StringBuilder();
query.AppendFormat("INSERT INTO {0} (\"", m_Realm);
query.Append(String.Join("\",\"", names.ToArray()));
query.Append("\") values (" + String.Join(",", values.ToArray()) + ")");
cmd.Connection = conn;
cmd.CommandText = query.ToString();
// m_log.WarnFormat("[PGSQLGenericTable]: Inserting into {0} sql {1}", m_Realm, cmd.CommandText);
if (conn.State != ConnectionState.Open)
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
}
return false;
}
}
public virtual bool Delete(string field, string key)
{
return Delete(new string[] { field }, new string[] { key });
}
public virtual bool Delete(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return false;
List<string> terms = new List<string>();
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
for (int i = 0; i < fields.Length; i++)
{
if (m_FieldTypes.ContainsKey(fields[i]))
cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i], m_FieldTypes[fields[i]]));
else
cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
terms.Add(" \"" + fields[i] + "\" = :" + fields[i]);
}
string where = String.Join(" AND ", terms.ToArray());
string query = String.Format("DELETE FROM {0} WHERE {1}", m_Realm, where);
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
//m_log.Warn("[PGSQLGenericTable]: " + deleteCommand);
return true;
}
return false;
}
}
public long GetCount(string field, string key)
{
return GetCount(new string[] { field }, new string[] { key });
}
public long GetCount(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return 0;
List<string> terms = new List<string>();
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
for (int i = 0; i < fields.Length; i++)
{
cmd.Parameters.AddWithValue(fields[i], keys[i]);
terms.Add("\"" + fields[i] + "\" = :" + fields[i]);
}
string where = String.Join(" and ", terms.ToArray());
string query = String.Format("select count(*) from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
Object result = DoQueryScalar(cmd);
return Convert.ToInt64(result);
}
}
public long GetCount(string where)
{
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
string query = String.Format("select count(*) from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
object result = DoQueryScalar(cmd);
return Convert.ToInt64(result);
}
}
public object DoQueryScalar(NpgsqlCommand cmd)
{
using (NpgsqlConnection dbcon = new NpgsqlConnection(m_ConnectionString))
{
dbcon.Open();
cmd.Connection = dbcon;
return cmd.ExecuteScalar();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Apache.Cordova {
// Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']"
[global::Android.Runtime.Register ("org/apache/cordova/CallbackContext", DoNotGenerateAcw=true)]
public partial class CallbackContext : global::Java.Lang.Object {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/apache/cordova/CallbackContext", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (CallbackContext); }
}
protected CallbackContext (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Ljava_lang_String_Lorg_apache_cordova_CordovaWebView_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/constructor[@name='CallbackContext' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='org.apache.cordova.CordovaWebView']]"
[Register (".ctor", "(Ljava/lang/String;Lorg/apache/cordova/CordovaWebView;)V", "")]
public CallbackContext (string p0, global::Org.Apache.Cordova.CordovaWebView p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p0 = JNIEnv.NewString (p0);;
if (GetType () != typeof (CallbackContext)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/lang/String;Lorg/apache/cordova/CordovaWebView;)V", new JValue (native_p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/lang/String;Lorg/apache/cordova/CordovaWebView;)V", new JValue (native_p0), new JValue (p1));
JNIEnv.DeleteLocalRef (native_p0);
return;
}
if (id_ctor_Ljava_lang_String_Lorg_apache_cordova_CordovaWebView_ == IntPtr.Zero)
id_ctor_Ljava_lang_String_Lorg_apache_cordova_CordovaWebView_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;Lorg/apache/cordova/CordovaWebView;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_Lorg_apache_cordova_CordovaWebView_, new JValue (native_p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_lang_String_Lorg_apache_cordova_CordovaWebView_, new JValue (native_p0), new JValue (p1));
JNIEnv.DeleteLocalRef (native_p0);
}
static Delegate cb_getCallbackId;
#pragma warning disable 0169
static Delegate GetGetCallbackIdHandler ()
{
if (cb_getCallbackId == null)
cb_getCallbackId = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetCallbackId);
return cb_getCallbackId;
}
static IntPtr n_GetCallbackId (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewString (__this.CallbackId);
}
#pragma warning restore 0169
static IntPtr id_getCallbackId;
public virtual string CallbackId {
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='getCallbackId' and count(parameter)=0]"
[Register ("getCallbackId", "()Ljava/lang/String;", "GetGetCallbackIdHandler")]
get {
if (id_getCallbackId == IntPtr.Zero)
id_getCallbackId = JNIEnv.GetMethodID (class_ref, "getCallbackId", "()Ljava/lang/String;");
if (GetType () == ThresholdType)
return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getCallbackId), JniHandleOwnership.TransferLocalRef);
else
return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getCallbackId", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef);
}
}
static Delegate cb_isChangingThreads;
#pragma warning disable 0169
static Delegate GetIsChangingThreadsHandler ()
{
if (cb_isChangingThreads == null)
cb_isChangingThreads = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsChangingThreads);
return cb_isChangingThreads;
}
static bool n_IsChangingThreads (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.IsChangingThreads;
}
#pragma warning restore 0169
static IntPtr id_isChangingThreads;
public virtual bool IsChangingThreads {
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='isChangingThreads' and count(parameter)=0]"
[Register ("isChangingThreads", "()Z", "GetIsChangingThreadsHandler")]
get {
if (id_isChangingThreads == IntPtr.Zero)
id_isChangingThreads = JNIEnv.GetMethodID (class_ref, "isChangingThreads", "()Z");
if (GetType () == ThresholdType)
return JNIEnv.CallBooleanMethod (Handle, id_isChangingThreads);
else
return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isChangingThreads", "()Z"));
}
}
static Delegate cb_isFinished;
#pragma warning disable 0169
static Delegate GetIsFinishedHandler ()
{
if (cb_isFinished == null)
cb_isFinished = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsFinished);
return cb_isFinished;
}
static bool n_IsFinished (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.IsFinished;
}
#pragma warning restore 0169
static IntPtr id_isFinished;
public virtual bool IsFinished {
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='isFinished' and count(parameter)=0]"
[Register ("isFinished", "()Z", "GetIsFinishedHandler")]
get {
if (id_isFinished == IntPtr.Zero)
id_isFinished = JNIEnv.GetMethodID (class_ref, "isFinished", "()Z");
if (GetType () == ThresholdType)
return JNIEnv.CallBooleanMethod (Handle, id_isFinished);
else
return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isFinished", "()Z"));
}
}
static Delegate cb_error_I;
#pragma warning disable 0169
static Delegate GetError_IHandler ()
{
if (cb_error_I == null)
cb_error_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_Error_I);
return cb_error_I;
}
static void n_Error_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Error (p0);
}
#pragma warning restore 0169
static IntPtr id_error_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='error' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("error", "(I)V", "GetError_IHandler")]
public virtual void Error (int p0)
{
if (id_error_I == IntPtr.Zero)
id_error_I = JNIEnv.GetMethodID (class_ref, "error", "(I)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_error_I, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "error", "(I)V"), new JValue (p0));
}
static Delegate cb_error_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetError_Ljava_lang_String_Handler ()
{
if (cb_error_Ljava_lang_String_ == null)
cb_error_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_Error_Ljava_lang_String_);
return cb_error_Ljava_lang_String_;
}
static void n_Error_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.Error (p0);
}
#pragma warning restore 0169
static IntPtr id_error_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='error' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("error", "(Ljava/lang/String;)V", "GetError_Ljava_lang_String_Handler")]
public virtual void Error (string p0)
{
if (id_error_Ljava_lang_String_ == IntPtr.Zero)
id_error_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "error", "(Ljava/lang/String;)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_error_Ljava_lang_String_, new JValue (native_p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "error", "(Ljava/lang/String;)V"), new JValue (native_p0));
JNIEnv.DeleteLocalRef (native_p0);
}
static Delegate cb_error_Lorg_json_JSONObject_;
#pragma warning disable 0169
static Delegate GetError_Lorg_json_JSONObject_Handler ()
{
if (cb_error_Lorg_json_JSONObject_ == null)
cb_error_Lorg_json_JSONObject_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_Error_Lorg_json_JSONObject_);
return cb_error_Lorg_json_JSONObject_;
}
static void n_Error_Lorg_json_JSONObject_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Json.JSONObject p0 = global::Java.Lang.Object.GetObject<global::Org.Json.JSONObject> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.Error (p0);
}
#pragma warning restore 0169
static IntPtr id_error_Lorg_json_JSONObject_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='error' and count(parameter)=1 and parameter[1][@type='org.json.JSONObject']]"
[Register ("error", "(Lorg/json/JSONObject;)V", "GetError_Lorg_json_JSONObject_Handler")]
public virtual void Error (global::Org.Json.JSONObject p0)
{
if (id_error_Lorg_json_JSONObject_ == IntPtr.Zero)
id_error_Lorg_json_JSONObject_ = JNIEnv.GetMethodID (class_ref, "error", "(Lorg/json/JSONObject;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_error_Lorg_json_JSONObject_, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "error", "(Lorg/json/JSONObject;)V"), new JValue (p0));
}
static Delegate cb_sendPluginResult_Lorg_apache_cordova_PluginResult_;
#pragma warning disable 0169
static Delegate GetSendPluginResult_Lorg_apache_cordova_PluginResult_Handler ()
{
if (cb_sendPluginResult_Lorg_apache_cordova_PluginResult_ == null)
cb_sendPluginResult_Lorg_apache_cordova_PluginResult_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SendPluginResult_Lorg_apache_cordova_PluginResult_);
return cb_sendPluginResult_Lorg_apache_cordova_PluginResult_;
}
static void n_SendPluginResult_Lorg_apache_cordova_PluginResult_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Apache.Cordova.PluginResult p0 = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.PluginResult> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.SendPluginResult (p0);
}
#pragma warning restore 0169
static IntPtr id_sendPluginResult_Lorg_apache_cordova_PluginResult_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='sendPluginResult' and count(parameter)=1 and parameter[1][@type='org.apache.cordova.PluginResult']]"
[Register ("sendPluginResult", "(Lorg/apache/cordova/PluginResult;)V", "GetSendPluginResult_Lorg_apache_cordova_PluginResult_Handler")]
public virtual void SendPluginResult (global::Org.Apache.Cordova.PluginResult p0)
{
if (id_sendPluginResult_Lorg_apache_cordova_PluginResult_ == IntPtr.Zero)
id_sendPluginResult_Lorg_apache_cordova_PluginResult_ = JNIEnv.GetMethodID (class_ref, "sendPluginResult", "(Lorg/apache/cordova/PluginResult;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_sendPluginResult_Lorg_apache_cordova_PluginResult_, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "sendPluginResult", "(Lorg/apache/cordova/PluginResult;)V"), new JValue (p0));
}
static Delegate cb_success;
#pragma warning disable 0169
static Delegate GetSuccessHandler ()
{
if (cb_success == null)
cb_success = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Success);
return cb_success;
}
static void n_Success (IntPtr jnienv, IntPtr native__this)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Success ();
}
#pragma warning restore 0169
static IntPtr id_success;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='success' and count(parameter)=0]"
[Register ("success", "()V", "GetSuccessHandler")]
public virtual void Success ()
{
if (id_success == IntPtr.Zero)
id_success = JNIEnv.GetMethodID (class_ref, "success", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_success);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "success", "()V"));
}
static Delegate cb_success_arrayB;
#pragma warning disable 0169
static Delegate GetSuccess_arrayBHandler ()
{
if (cb_success_arrayB == null)
cb_success_arrayB = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_Success_arrayB);
return cb_success_arrayB;
}
static void n_Success_arrayB (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
byte[] p0 = (byte[]) JNIEnv.GetArray (native_p0, JniHandleOwnership.DoNotTransfer, typeof (byte));
__this.Success (p0);
if (p0 != null)
JNIEnv.CopyArray (p0, native_p0);
}
#pragma warning restore 0169
static IntPtr id_success_arrayB;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='success' and count(parameter)=1 and parameter[1][@type='byte[]']]"
[Register ("success", "([B)V", "GetSuccess_arrayBHandler")]
public virtual void Success (byte[] p0)
{
if (id_success_arrayB == IntPtr.Zero)
id_success_arrayB = JNIEnv.GetMethodID (class_ref, "success", "([B)V");
IntPtr native_p0 = JNIEnv.NewArray (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_success_arrayB, new JValue (native_p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "success", "([B)V"), new JValue (native_p0));
if (p0 != null) {
JNIEnv.CopyArray (native_p0, p0);
JNIEnv.DeleteLocalRef (native_p0);
}
}
static Delegate cb_success_I;
#pragma warning disable 0169
static Delegate GetSuccess_IHandler ()
{
if (cb_success_I == null)
cb_success_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_Success_I);
return cb_success_I;
}
static void n_Success_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Success (p0);
}
#pragma warning restore 0169
static IntPtr id_success_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='success' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("success", "(I)V", "GetSuccess_IHandler")]
public virtual void Success (int p0)
{
if (id_success_I == IntPtr.Zero)
id_success_I = JNIEnv.GetMethodID (class_ref, "success", "(I)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_success_I, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "success", "(I)V"), new JValue (p0));
}
static Delegate cb_success_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetSuccess_Ljava_lang_String_Handler ()
{
if (cb_success_Ljava_lang_String_ == null)
cb_success_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_Success_Ljava_lang_String_);
return cb_success_Ljava_lang_String_;
}
static void n_Success_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.Success (p0);
}
#pragma warning restore 0169
static IntPtr id_success_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='success' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("success", "(Ljava/lang/String;)V", "GetSuccess_Ljava_lang_String_Handler")]
public virtual void Success (string p0)
{
if (id_success_Ljava_lang_String_ == IntPtr.Zero)
id_success_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "success", "(Ljava/lang/String;)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_success_Ljava_lang_String_, new JValue (native_p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "success", "(Ljava/lang/String;)V"), new JValue (native_p0));
JNIEnv.DeleteLocalRef (native_p0);
}
static Delegate cb_success_Lorg_json_JSONArray_;
#pragma warning disable 0169
static Delegate GetSuccess_Lorg_json_JSONArray_Handler ()
{
if (cb_success_Lorg_json_JSONArray_ == null)
cb_success_Lorg_json_JSONArray_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_Success_Lorg_json_JSONArray_);
return cb_success_Lorg_json_JSONArray_;
}
static void n_Success_Lorg_json_JSONArray_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Json.JSONArray p0 = global::Java.Lang.Object.GetObject<global::Org.Json.JSONArray> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.Success (p0);
}
#pragma warning restore 0169
static IntPtr id_success_Lorg_json_JSONArray_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='success' and count(parameter)=1 and parameter[1][@type='org.json.JSONArray']]"
[Register ("success", "(Lorg/json/JSONArray;)V", "GetSuccess_Lorg_json_JSONArray_Handler")]
public virtual void Success (global::Org.Json.JSONArray p0)
{
if (id_success_Lorg_json_JSONArray_ == IntPtr.Zero)
id_success_Lorg_json_JSONArray_ = JNIEnv.GetMethodID (class_ref, "success", "(Lorg/json/JSONArray;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_success_Lorg_json_JSONArray_, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "success", "(Lorg/json/JSONArray;)V"), new JValue (p0));
}
static Delegate cb_success_Lorg_json_JSONObject_;
#pragma warning disable 0169
static Delegate GetSuccess_Lorg_json_JSONObject_Handler ()
{
if (cb_success_Lorg_json_JSONObject_ == null)
cb_success_Lorg_json_JSONObject_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_Success_Lorg_json_JSONObject_);
return cb_success_Lorg_json_JSONObject_;
}
static void n_Success_Lorg_json_JSONObject_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Apache.Cordova.CallbackContext __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CallbackContext> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Json.JSONObject p0 = global::Java.Lang.Object.GetObject<global::Org.Json.JSONObject> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.Success (p0);
}
#pragma warning restore 0169
static IntPtr id_success_Lorg_json_JSONObject_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CallbackContext']/method[@name='success' and count(parameter)=1 and parameter[1][@type='org.json.JSONObject']]"
[Register ("success", "(Lorg/json/JSONObject;)V", "GetSuccess_Lorg_json_JSONObject_Handler")]
public virtual void Success (global::Org.Json.JSONObject p0)
{
if (id_success_Lorg_json_JSONObject_ == IntPtr.Zero)
id_success_Lorg_json_JSONObject_ = JNIEnv.GetMethodID (class_ref, "success", "(Lorg/json/JSONObject;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_success_Lorg_json_JSONObject_, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "success", "(Lorg/json/JSONObject;)V"), new JValue (p0));
}
}
}
| |
using System;
using System.Collections.Immutable;
using System.Linq;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Resources.Annotations;
namespace JsonApiDotNetCore.Queries.Internal.Parsing
{
/// <summary>
/// Provides helper methods to resolve a chain of fields (relationships and attributes) from the resource graph.
/// </summary>
internal sealed class ResourceFieldChainResolver
{
private readonly IResourceGraph _resourceGraph;
public ResourceFieldChainResolver(IResourceGraph resourceGraph)
{
ArgumentGuard.NotNull(resourceGraph, nameof(resourceGraph));
_resourceGraph = resourceGraph;
}
/// <summary>
/// Resolves a chain of relationships that ends in a to-many relationship, for example: blogs.owner.articles.comments
/// </summary>
public IImmutableList<ResourceFieldAttribute> ResolveToManyChain(ResourceContext resourceContext, string path,
Action<ResourceFieldAttribute, ResourceContext, string> validateCallback = null)
{
ImmutableArray<ResourceFieldAttribute>.Builder chainBuilder = ImmutableArray.CreateBuilder<ResourceFieldAttribute>();
string[] publicNameParts = path.Split(".");
ResourceContext nextResourceContext = resourceContext;
foreach (string publicName in publicNameParts[..^1])
{
RelationshipAttribute relationship = GetRelationship(publicName, nextResourceContext, path);
validateCallback?.Invoke(relationship, nextResourceContext, path);
chainBuilder.Add(relationship);
nextResourceContext = _resourceGraph.GetResourceContext(relationship.RightType);
}
string lastName = publicNameParts[^1];
RelationshipAttribute lastToManyRelationship = GetToManyRelationship(lastName, nextResourceContext, path);
validateCallback?.Invoke(lastToManyRelationship, nextResourceContext, path);
chainBuilder.Add(lastToManyRelationship);
return chainBuilder.ToImmutable();
}
/// <summary>
/// Resolves a chain of relationships.
/// <example>
/// blogs.articles.comments
/// </example>
/// <example>
/// author.address
/// </example>
/// <example>
/// articles.revisions.author
/// </example>
/// </summary>
public IImmutableList<ResourceFieldAttribute> ResolveRelationshipChain(ResourceContext resourceContext, string path,
Action<RelationshipAttribute, ResourceContext, string> validateCallback = null)
{
ImmutableArray<ResourceFieldAttribute>.Builder chainBuilder = ImmutableArray.CreateBuilder<ResourceFieldAttribute>();
ResourceContext nextResourceContext = resourceContext;
foreach (string publicName in path.Split("."))
{
RelationshipAttribute relationship = GetRelationship(publicName, nextResourceContext, path);
validateCallback?.Invoke(relationship, nextResourceContext, path);
chainBuilder.Add(relationship);
nextResourceContext = _resourceGraph.GetResourceContext(relationship.RightType);
}
return chainBuilder.ToImmutable();
}
/// <summary>
/// Resolves a chain of to-one relationships that ends in an attribute.
/// <example>
/// author.address.country.name
/// </example>
/// <example>name</example>
/// </summary>
public IImmutableList<ResourceFieldAttribute> ResolveToOneChainEndingInAttribute(ResourceContext resourceContext, string path,
Action<ResourceFieldAttribute, ResourceContext, string> validateCallback = null)
{
ImmutableArray<ResourceFieldAttribute>.Builder chainBuilder = ImmutableArray.CreateBuilder<ResourceFieldAttribute>();
string[] publicNameParts = path.Split(".");
ResourceContext nextResourceContext = resourceContext;
foreach (string publicName in publicNameParts[..^1])
{
RelationshipAttribute toOneRelationship = GetToOneRelationship(publicName, nextResourceContext, path);
validateCallback?.Invoke(toOneRelationship, nextResourceContext, path);
chainBuilder.Add(toOneRelationship);
nextResourceContext = _resourceGraph.GetResourceContext(toOneRelationship.RightType);
}
string lastName = publicNameParts[^1];
AttrAttribute lastAttribute = GetAttribute(lastName, nextResourceContext, path);
validateCallback?.Invoke(lastAttribute, nextResourceContext, path);
chainBuilder.Add(lastAttribute);
return chainBuilder.ToImmutable();
}
/// <summary>
/// Resolves a chain of to-one relationships that ends in a to-many relationship.
/// <example>
/// article.comments
/// </example>
/// <example>
/// comments
/// </example>
/// </summary>
public IImmutableList<ResourceFieldAttribute> ResolveToOneChainEndingInToMany(ResourceContext resourceContext, string path,
Action<ResourceFieldAttribute, ResourceContext, string> validateCallback = null)
{
ImmutableArray<ResourceFieldAttribute>.Builder chainBuilder = ImmutableArray.CreateBuilder<ResourceFieldAttribute>();
string[] publicNameParts = path.Split(".");
ResourceContext nextResourceContext = resourceContext;
foreach (string publicName in publicNameParts[..^1])
{
RelationshipAttribute toOneRelationship = GetToOneRelationship(publicName, nextResourceContext, path);
validateCallback?.Invoke(toOneRelationship, nextResourceContext, path);
chainBuilder.Add(toOneRelationship);
nextResourceContext = _resourceGraph.GetResourceContext(toOneRelationship.RightType);
}
string lastName = publicNameParts[^1];
RelationshipAttribute toManyRelationship = GetToManyRelationship(lastName, nextResourceContext, path);
validateCallback?.Invoke(toManyRelationship, nextResourceContext, path);
chainBuilder.Add(toManyRelationship);
return chainBuilder.ToImmutable();
}
/// <summary>
/// Resolves a chain of to-one relationships that ends in either an attribute or a to-one relationship.
/// <example>
/// author.address.country.name
/// </example>
/// <example>
/// author.address
/// </example>
/// </summary>
public IImmutableList<ResourceFieldAttribute> ResolveToOneChainEndingInAttributeOrToOne(ResourceContext resourceContext, string path,
Action<ResourceFieldAttribute, ResourceContext, string> validateCallback = null)
{
ImmutableArray<ResourceFieldAttribute>.Builder chainBuilder = ImmutableArray.CreateBuilder<ResourceFieldAttribute>();
string[] publicNameParts = path.Split(".");
ResourceContext nextResourceContext = resourceContext;
foreach (string publicName in publicNameParts[..^1])
{
RelationshipAttribute toOneRelationship = GetToOneRelationship(publicName, nextResourceContext, path);
validateCallback?.Invoke(toOneRelationship, nextResourceContext, path);
chainBuilder.Add(toOneRelationship);
nextResourceContext = _resourceGraph.GetResourceContext(toOneRelationship.RightType);
}
string lastName = publicNameParts[^1];
ResourceFieldAttribute lastField = GetField(lastName, nextResourceContext, path);
if (lastField is HasManyAttribute)
{
throw new QueryParseException(path == lastName
? $"Field '{lastName}' must be an attribute or a to-one relationship on resource '{nextResourceContext.PublicName}'."
: $"Field '{lastName}' in '{path}' must be an attribute or a to-one relationship on resource '{nextResourceContext.PublicName}'.");
}
validateCallback?.Invoke(lastField, nextResourceContext, path);
chainBuilder.Add(lastField);
return chainBuilder.ToImmutable();
}
private RelationshipAttribute GetRelationship(string publicName, ResourceContext resourceContext, string path)
{
RelationshipAttribute relationship = resourceContext.TryGetRelationshipByPublicName(publicName);
if (relationship == null)
{
throw new QueryParseException(path == publicName
? $"Relationship '{publicName}' does not exist on resource '{resourceContext.PublicName}'."
: $"Relationship '{publicName}' in '{path}' does not exist on resource '{resourceContext.PublicName}'.");
}
return relationship;
}
private RelationshipAttribute GetToManyRelationship(string publicName, ResourceContext resourceContext, string path)
{
RelationshipAttribute relationship = GetRelationship(publicName, resourceContext, path);
if (relationship is not HasManyAttribute)
{
throw new QueryParseException(path == publicName
? $"Relationship '{publicName}' must be a to-many relationship on resource '{resourceContext.PublicName}'."
: $"Relationship '{publicName}' in '{path}' must be a to-many relationship on resource '{resourceContext.PublicName}'.");
}
return relationship;
}
private RelationshipAttribute GetToOneRelationship(string publicName, ResourceContext resourceContext, string path)
{
RelationshipAttribute relationship = GetRelationship(publicName, resourceContext, path);
if (relationship is not HasOneAttribute)
{
throw new QueryParseException(path == publicName
? $"Relationship '{publicName}' must be a to-one relationship on resource '{resourceContext.PublicName}'."
: $"Relationship '{publicName}' in '{path}' must be a to-one relationship on resource '{resourceContext.PublicName}'.");
}
return relationship;
}
private AttrAttribute GetAttribute(string publicName, ResourceContext resourceContext, string path)
{
AttrAttribute attribute = resourceContext.TryGetAttributeByPublicName(publicName);
if (attribute == null)
{
throw new QueryParseException(path == publicName
? $"Attribute '{publicName}' does not exist on resource '{resourceContext.PublicName}'."
: $"Attribute '{publicName}' in '{path}' does not exist on resource '{resourceContext.PublicName}'.");
}
return attribute;
}
public ResourceFieldAttribute GetField(string publicName, ResourceContext resourceContext, string path)
{
ResourceFieldAttribute field = resourceContext.Fields.FirstOrDefault(nextField => nextField.PublicName == publicName);
if (field == null)
{
throw new QueryParseException(path == publicName
? $"Field '{publicName}' does not exist on resource '{resourceContext.PublicName}'."
: $"Field '{publicName}' in '{path}' does not exist on resource '{resourceContext.PublicName}'.");
}
return field;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using Microsoft.CodeAnalysis.Shared;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.PatternMatching
{
/// <summary>
/// The pattern matcher is thread-safe. However, it maintains an internal cache of
/// information as it is used. Therefore, you should not keep it around forever and should get
/// and release the matcher appropriately once you no longer need it.
/// Also, while the pattern matcher is culture aware, it uses the culture specified in the
/// constructor.
/// </summary>
internal sealed partial class PatternMatcher : IDisposable
{
private static readonly char[] s_dotCharacterArray = { '.' };
private readonly object _gate = new object();
private readonly bool _allowFuzzyMatching;
private readonly bool _invalidPattern;
private readonly Segment _fullPatternSegment;
private readonly Segment[] _dotSeparatedSegments;
private readonly Dictionary<string, StringBreaks> _stringToWordSpans = new Dictionary<string, StringBreaks>();
private readonly Func<string, StringBreaks> _breakIntoWordSpans = StringBreaker.BreakIntoWordParts;
// PERF: Cache the culture's compareInfo to avoid the overhead of asking for them repeatedly in inner loops
private readonly CompareInfo _compareInfo;
/// <summary>
/// Construct a new PatternMatcher using the calling thread's culture for string searching and comparison.
/// </summary>
public PatternMatcher(
string pattern,
bool verbatimIdentifierPrefixIsWordCharacter = false,
bool allowFuzzyMatching = false) :
this(pattern, CultureInfo.CurrentCulture, verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching)
{
}
/// <summary>
/// Construct a new PatternMatcher using the specified culture.
/// </summary>
/// <param name="pattern">The pattern to make the pattern matcher for.</param>
/// <param name="culture">The culture to use for string searching and comparison.</param>
/// <param name="verbatimIdentifierPrefixIsWordCharacter">Whether to consider "@" as a word character</param>
/// <param name="allowFuzzyMatching">Whether or not close matches should count as matches.</param>
public PatternMatcher(
string pattern,
CultureInfo culture,
bool verbatimIdentifierPrefixIsWordCharacter,
bool allowFuzzyMatching)
{
pattern = pattern.Trim();
_compareInfo = culture.CompareInfo;
_allowFuzzyMatching = allowFuzzyMatching;
_fullPatternSegment = new Segment(pattern, verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching);
if (pattern.IndexOf('.') < 0)
{
// PERF: Avoid string.Split allocations when the pattern doesn't contain a dot.
_dotSeparatedSegments = pattern.Length > 0
? new Segment[1] { _fullPatternSegment }
: Array.Empty<Segment>();
}
else
{
_dotSeparatedSegments = pattern.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries)
.Select(text => new Segment(text.Trim(), verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching))
.ToArray();
}
_invalidPattern = _dotSeparatedSegments.Length == 0 || _dotSeparatedSegments.Any(s => s.IsInvalid);
}
public void Dispose()
{
_fullPatternSegment.Dispose();
foreach (var segment in _dotSeparatedSegments)
{
segment.Dispose();
}
}
public bool IsDottedPattern => _dotSeparatedSegments.Length > 1;
private bool SkipMatch(string candidate)
{
return _invalidPattern || string.IsNullOrWhiteSpace(candidate);
}
public ImmutableArray<PatternMatch> GetMatches(string candidate)
{
return GetMatches(candidate, includeMatchSpans: false);
}
/// <summary>
/// Determines if a given candidate string matches under a multiple word query text, as you
/// would find in features like Navigate To.
/// </summary>
/// <param name="candidate">The word being tested.</param>
/// <param name="includeMatchSpans">Whether or not the matched spans should be included with results</param>
/// <returns>If this was a match, a set of match types that occurred while matching the
/// patterns. If it was not a match, it returns null.</returns>
public ImmutableArray<PatternMatch> GetMatches(string candidate, bool includeMatchSpans)
{
if (SkipMatch(candidate))
{
return ImmutableArray<PatternMatch>.Empty;
}
var result = MatchSegment(candidate, includeMatchSpans, _fullPatternSegment, fuzzyMatch: true);
if (!result.IsEmpty)
{
return result;
}
return MatchSegment(candidate, includeMatchSpans, _fullPatternSegment, fuzzyMatch: false);
}
public ImmutableArray<PatternMatch> GetMatchesForLastSegmentOfPattern(string candidate)
{
if (SkipMatch(candidate))
{
return ImmutableArray<PatternMatch>.Empty;
}
var result = MatchSegment(candidate, includeMatchSpans: false, segment: _dotSeparatedSegments.Last(), fuzzyMatch: false);
if (!result.IsEmpty)
{
return result;
}
return MatchSegment(candidate, includeMatchSpans: false, segment: _dotSeparatedSegments.Last(), fuzzyMatch: true);
}
public PatternMatches GetMatches(string candidate, string dottedContainer)
{
return GetMatches(candidate, dottedContainer, includeMatchSpans: false);
}
/// <summary>
/// Matches a pattern against a candidate, and an optional dotted container for the
/// candidate. If the container is provided, and the pattern itself contains dots, then
/// the pattern will be tested against the candidate and container. Specifically,
/// the part of the pattern after the last dot will be tested against the candidate. If
/// a match occurs there, then the remaining dot-separated portions of the pattern will
/// be tested against every successive portion of the container from right to left.
///
/// i.e. if you have a pattern of "Con.WL" and the candidate is "WriteLine" with a
/// dotted container of "System.Console", then "WL" will be tested against "WriteLine".
/// With a match found there, "Con" will then be tested against "Console".
/// </summary>
public PatternMatches GetMatches(
string candidate, string dottedContainer, bool includeMatchSpans)
{
var result = GetMatches(candidate, dottedContainer, includeMatchSpans, fuzzyMatch: false);
if (!result.IsEmpty)
{
return result;
}
return GetMatches(candidate, dottedContainer, includeMatchSpans, fuzzyMatch: true);
}
private PatternMatches GetMatches(
string candidate, string dottedContainer, bool includeMatchSpans, bool fuzzyMatch)
{
if (fuzzyMatch && !_allowFuzzyMatching)
{
return PatternMatches.Empty;
}
if (SkipMatch(candidate))
{
return PatternMatches.Empty;
}
// First, check that the last part of the dot separated pattern matches the name of the
// candidate. If not, then there's no point in proceeding and doing the more
// expensive work.
var candidateMatch = MatchSegment(candidate, includeMatchSpans, _dotSeparatedSegments.Last(), fuzzyMatch);
if (candidateMatch.IsDefaultOrEmpty)
{
return PatternMatches.Empty;
}
dottedContainer = dottedContainer ?? string.Empty;
var containerParts = dottedContainer.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries);
// -1 because the last part was checked against the name, and only the rest
// of the parts are checked against the container.
var relevantDotSeparatedSegmentLength = _dotSeparatedSegments.Length - 1;
if (relevantDotSeparatedSegmentLength > containerParts.Length)
{
// There weren't enough container parts to match against the pattern parts.
// So this definitely doesn't match.
return PatternMatches.Empty;
}
// So far so good. Now break up the container for the candidate and check if all
// the dotted parts match up correctly.
var containerMatches = ArrayBuilder<PatternMatch>.GetInstance();
try
{
// Don't need to check the last segment. We did that as the very first bail out step.
for (int i = 0, j = containerParts.Length - relevantDotSeparatedSegmentLength;
i < relevantDotSeparatedSegmentLength;
i++, j++)
{
var segment = _dotSeparatedSegments[i];
var containerName = containerParts[j];
var containerMatch = MatchSegment(containerName, includeMatchSpans, segment, fuzzyMatch);
if (containerMatch.IsDefaultOrEmpty)
{
// This container didn't match the pattern piece. So there's no match at all.
return PatternMatches.Empty;
}
containerMatches.AddRange(containerMatch);
}
// Success, this symbol's full name matched against the dotted name the user was asking
// about.
return new PatternMatches(candidateMatch, containerMatches.ToImmutable());
}
finally
{
containerMatches.Free();
}
}
/// <summary>
/// Determines if a given candidate string matches under a multiple word query text, as you
/// would find in features like Navigate To.
/// </summary>
/// <remarks>
/// PERF: This is slightly faster and uses less memory than <see cref="GetMatches(string, bool)"/>
/// so, unless you need to know the full set of matches, use this version.
/// </remarks>
/// <param name="candidate">The word being tested.</param>
/// <param name="inludeMatchSpans">Whether or not the matched spans should be included with results</param>
/// <returns>If this was a match, the first element of the set of match types that occurred while matching the
/// patterns. If it was not a match, it returns null.</returns>
public PatternMatch? GetFirstMatch(string candidate, bool inludeMatchSpans = false)
{
if (SkipMatch(candidate))
{
return null;
}
return MatchSegment(candidate, inludeMatchSpans, _fullPatternSegment, wantAllMatches: false, allMatches: out var ignored, fuzzyMatch: false) ??
MatchSegment(candidate, inludeMatchSpans, _fullPatternSegment, wantAllMatches: false, allMatches: out ignored, fuzzyMatch: true);
}
private StringBreaks GetWordSpans(string word)
{
lock (_gate)
{
return _stringToWordSpans.GetOrAdd(word, _breakIntoWordSpans);
}
}
internal PatternMatch? MatchSingleWordPattern_ForTestingOnly(string candidate)
{
return MatchTextChunk(candidate, includeMatchSpans: true,
chunk: _fullPatternSegment.TotalTextChunk, punctuationStripped: false,
fuzzyMatch: false);
}
private static bool ContainsUpperCaseLetter(string pattern)
{
// Expansion of "foreach(char ch in pattern)" to avoid a CharEnumerator allocation
for (int i = 0; i < pattern.Length; i++)
{
if (char.IsUpper(pattern[i]))
{
return true;
}
}
return false;
}
private PatternMatch? MatchTextChunk(
string candidate,
bool includeMatchSpans,
TextChunk chunk,
bool punctuationStripped,
bool fuzzyMatch)
{
int caseInsensitiveIndex = _compareInfo.IndexOf(candidate, chunk.Text, CompareOptions.IgnoreCase);
if (caseInsensitiveIndex == 0)
{
if (chunk.Text.Length == candidate.Length)
{
// a) Check if the part matches the candidate entirely, in an case insensitive or
// sensitive manner. If it does, return that there was an exact match.
return new PatternMatch(
PatternMatchKind.Exact, punctuationStripped, isCaseSensitive: candidate == chunk.Text,
matchedSpan: GetMatchedSpan(includeMatchSpans, 0, candidate.Length));
}
else
{
// b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive
// manner. If it does, return that there was a prefix match.
return new PatternMatch(
PatternMatchKind.Prefix, punctuationStripped, isCaseSensitive: _compareInfo.IsPrefix(candidate, chunk.Text),
matchedSpan: GetMatchedSpan(includeMatchSpans, 0, chunk.Text.Length));
}
}
var isLowercase = !ContainsUpperCaseLetter(chunk.Text);
if (isLowercase)
{
if (caseInsensitiveIndex > 0)
{
// c) If the part is entirely lowercase, then check if it is contained anywhere in the
// candidate in a case insensitive manner. If so, return that there was a substring
// match.
//
// Note: We only have a substring match if the lowercase part is prefix match of some
// word part. That way we don't match something like 'Class' when the user types 'a'.
// But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
var wordSpans = GetWordSpans(candidate);
for (int i = 0; i < wordSpans.Count; i++)
{
var span = wordSpans[i];
if (PartStartsWith(candidate, span, chunk.Text, CompareOptions.IgnoreCase))
{
return new PatternMatch(PatternMatchKind.Substring, punctuationStripped,
isCaseSensitive: PartStartsWith(candidate, span, chunk.Text, CompareOptions.None),
matchedSpan: GetMatchedSpan(includeMatchSpans, span.Start, chunk.Text.Length));
}
}
}
}
else
{
// d) If the part was not entirely lowercase, then check if it is contained in the
// candidate in a case *sensitive* manner. If so, return that there was a substring
// match.
var caseSensitiveIndex = _compareInfo.IndexOf(candidate, chunk.Text);
if (caseSensitiveIndex > 0)
{
return new PatternMatch(
PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: true,
matchedSpan: GetMatchedSpan(includeMatchSpans, caseSensitiveIndex, chunk.Text.Length));
}
}
if (!isLowercase)
{
// e) If the part was not entirely lowercase, then attempt a camel cased match as well.
if (chunk.CharacterSpans.Count > 0)
{
var candidateParts = GetWordSpans(candidate);
var camelCaseWeight = TryCamelCaseMatch(candidate, includeMatchSpans, candidateParts, chunk, CompareOptions.None, out var matchedSpans);
if (camelCaseWeight.HasValue)
{
return new PatternMatch(
PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: true, camelCaseWeight: camelCaseWeight,
matchedSpans: GetMatchedSpans(includeMatchSpans, matchedSpans));
}
camelCaseWeight = TryCamelCaseMatch(candidate, includeMatchSpans, candidateParts, chunk, CompareOptions.IgnoreCase, out matchedSpans);
if (camelCaseWeight.HasValue)
{
return new PatternMatch(
PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: false, camelCaseWeight: camelCaseWeight,
matchedSpans: GetMatchedSpans(includeMatchSpans, matchedSpans));
}
}
}
if (isLowercase)
{
// f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries?
// We could check every character boundary start of the candidate for the pattern. However, that's
// an m * n operation in the worst case. Instead, find the first instance of the pattern
// substring, and see if it starts on a capital letter. It seems unlikely that the user will try to
// filter the list based on a substring that starts on a capital letter and also with a lowercase one.
// (Pattern: fogbar, Candidate: quuxfogbarFogBar).
if (chunk.Text.Length < candidate.Length)
{
if (caseInsensitiveIndex != -1 && char.IsUpper(candidate[caseInsensitiveIndex]))
{
return new PatternMatch(
PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: false,
matchedSpan: GetMatchedSpan(includeMatchSpans, caseInsensitiveIndex, chunk.Text.Length));
}
}
}
if (fuzzyMatch)
{
if (chunk.SimilarityChecker.AreSimilar(candidate))
{
return new PatternMatch(
PatternMatchKind.Fuzzy, punctuationStripped, isCaseSensitive: false, matchedSpan: null);
}
}
return null;
}
private ImmutableArray<TextSpan> GetMatchedSpans(bool includeMatchSpans, List<TextSpan> matchedSpans)
{
return includeMatchSpans
? new NormalizedTextSpanCollection(matchedSpans).ToImmutableArray()
: ImmutableArray<TextSpan>.Empty;
}
private static TextSpan? GetMatchedSpan(bool includeMatchSpans, int start, int length)
{
return includeMatchSpans ? new TextSpan(start, length) : (TextSpan?)null;
}
private static bool ContainsSpaceOrAsterisk(string text)
{
for (int i = 0; i < text.Length; i++)
{
char ch = text[i];
if (ch == ' ' || ch == '*')
{
return true;
}
}
return false;
}
private ImmutableArray<PatternMatch> MatchSegment(
string candidate, bool includeMatchSpans, Segment segment, bool fuzzyMatch)
{
if (fuzzyMatch && !_allowFuzzyMatching)
{
return ImmutableArray<PatternMatch>.Empty;
}
var singleMatch = MatchSegment(candidate, includeMatchSpans, segment,
wantAllMatches: true, fuzzyMatch: fuzzyMatch, allMatches: out var matches);
if (singleMatch.HasValue)
{
return ImmutableArray.Create(singleMatch.Value);
}
return matches;
}
/// <summary>
/// Internal helper for MatchPatternInternal
/// </summary>
/// <remarks>
/// PERF: Designed to minimize allocations in common cases.
/// If there's no match, then null is returned.
/// If there's a single match, or the caller only wants the first match, then it is returned (as a Nullable)
/// If there are multiple matches, and the caller wants them all, then a List is allocated.
/// </remarks>
/// <param name="candidate">The word being tested.</param>
/// <param name="segment">The segment of the pattern to check against the candidate.</param>
/// <param name="wantAllMatches">Does the caller want all matches or just the first?</param>
/// <param name="fuzzyMatch">If a fuzzy match should be performed</param>
/// <param name="allMatches">If <paramref name="wantAllMatches"/> is true, and there's more than one match, then the list of all matches.</param>
/// <param name="includeMatchSpans">Whether or not the matched spans should be included with results</param>
/// <returns>If there's only one match, then the return value is that match. Otherwise it is null.</returns>
private PatternMatch? MatchSegment(
string candidate,
bool includeMatchSpans,
Segment segment,
bool wantAllMatches,
bool fuzzyMatch,
out ImmutableArray<PatternMatch> allMatches)
{
allMatches = ImmutableArray<PatternMatch>.Empty;
if (fuzzyMatch && !_allowFuzzyMatching)
{
return null;
}
// First check if the segment matches as is. This is also useful if the segment contains
// characters we would normally strip when splitting into parts that we also may want to
// match in the candidate. For example if the segment is "@int" and the candidate is
// "@int", then that will show up as an exact match here.
//
// Note: if the segment contains a space or an asterisk then we must assume that it's a
// multi-word segment.
if (!ContainsSpaceOrAsterisk(segment.TotalTextChunk.Text))
{
var match = MatchTextChunk(candidate, includeMatchSpans,
segment.TotalTextChunk, punctuationStripped: false, fuzzyMatch: fuzzyMatch);
if (match != null)
{
return match;
}
}
// The logic for pattern matching is now as follows:
//
// 1) Break the segment passed in into words. Breaking is rather simple and a
// good way to think about it that if gives you all the individual alphanumeric words
// of the pattern.
//
// 2) For each word try to match the word against the candidate value.
//
// 3) Matching is as follows:
//
// a) Check if the word matches the candidate entirely, in an case insensitive or
// sensitive manner. If it does, return that there was an exact match.
//
// b) Check if the word is a prefix of the candidate, in a case insensitive or
// sensitive manner. If it does, return that there was a prefix match.
//
// c) If the word is entirely lowercase, then check if it is contained anywhere in the
// candidate in a case insensitive manner. If so, return that there was a substring
// match.
//
// Note: We only have a substring match if the lowercase part is prefix match of
// some word part. That way we don't match something like 'Class' when the user
// types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with
// 'a').
//
// d) If the word was not entirely lowercase, then check if it is contained in the
// candidate in a case *sensitive* manner. If so, return that there was a substring
// match.
//
// e) If the word was not entirely lowercase, then attempt a camel cased match as
// well.
//
// f) The word is all lower case. Is it a case insensitive substring of the candidate starting
// on a part boundary of the candidate?
//
// Only if all words have some sort of match is the pattern considered matched.
var subWordTextChunks = segment.SubWordTextChunks;
var matches = ArrayBuilder<PatternMatch>.GetInstance();
try
{
foreach (var subWordTextChunk in subWordTextChunks)
{
// Try to match the candidate with this word
var result = MatchTextChunk(candidate, includeMatchSpans,
subWordTextChunk, punctuationStripped: true, fuzzyMatch: fuzzyMatch);
if (result == null)
{
return null;
}
if (!wantAllMatches || subWordTextChunks.Length == 1)
{
// Stop at the first word
return result;
}
matches.Add(result.Value);
}
allMatches = matches.ToImmutable();
return null;
}
finally
{
matches.Free();
}
}
private static bool IsWordChar(char ch, bool verbatimIdentifierPrefixIsWordCharacter)
{
return char.IsLetterOrDigit(ch) || ch == '_' || (verbatimIdentifierPrefixIsWordCharacter && ch == '@');
}
/// <summary>
/// Do the two 'parts' match? i.e. Does the candidate part start with the pattern part?
/// </summary>
/// <param name="candidate">The candidate text</param>
/// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param>
/// <param name="pattern">The pattern text</param>
/// <param name="patternPart">The span within the <paramref name="pattern"/> text</param>
/// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param>
/// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with
/// the span identified by <paramref name="patternPart"/> within <paramref name="pattern"/>.</returns>
private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, TextSpan patternPart, CompareOptions compareOptions)
{
if (patternPart.Length > candidatePart.Length)
{
// Pattern part is longer than the candidate part. There can never be a match.
return false;
}
return _compareInfo.Compare(candidate, candidatePart.Start, patternPart.Length, pattern, patternPart.Start, patternPart.Length, compareOptions) == 0;
}
/// <summary>
/// Does the given part start with the given pattern?
/// </summary>
/// <param name="candidate">The candidate text</param>
/// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param>
/// <param name="pattern">The pattern text</param>
/// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param>
/// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with <paramref name="pattern"/></returns>
private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, CompareOptions compareOptions)
{
return PartStartsWith(candidate, candidatePart, pattern, new TextSpan(0, pattern.Length), compareOptions);
}
private int? TryCamelCaseMatch(
string candidate,
bool includeMatchedSpans,
StringBreaks candidateParts,
TextChunk chunk,
CompareOptions compareOption,
out List<TextSpan> matchedSpans)
{
matchedSpans = null;
var chunkCharacterSpans = chunk.CharacterSpans;
// Note: we may have more pattern parts than candidate parts. This is because multiple
// pattern parts may match a candidate part. For example "SiUI" against "SimpleUI".
// We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI. However, U
// and I will both match in UI.
int currentCandidate = 0;
int currentChunkSpan = 0;
int? firstMatch = null;
bool? contiguous = null;
while (true)
{
// Let's consider our termination cases
if (currentChunkSpan == chunkCharacterSpans.Count)
{
Contract.Requires(firstMatch.HasValue);
Contract.Requires(contiguous.HasValue);
// We did match! We shall assign a weight to this
int weight = 0;
// Was this contiguous?
if (contiguous.Value)
{
weight += 1;
}
// Did we start at the beginning of the candidate?
if (firstMatch.Value == 0)
{
weight += 2;
}
return weight;
}
else if (currentCandidate == candidateParts.Count)
{
// No match, since we still have more of the pattern to hit
matchedSpans = null;
return null;
}
var candidatePart = candidateParts[currentCandidate];
bool gotOneMatchThisCandidate = false;
// Consider the case of matching SiUI against SimpleUIElement. The candidate parts
// will be Simple/UI/Element, and the pattern parts will be Si/U/I. We'll match 'Si'
// against 'Simple' first. Then we'll match 'U' against 'UI'. However, we want to
// still keep matching pattern parts against that candidate part.
for (; currentChunkSpan < chunkCharacterSpans.Count; currentChunkSpan++)
{
var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan];
if (gotOneMatchThisCandidate)
{
// We've already gotten one pattern part match in this candidate. We will
// only continue trying to consume pattern parts if the last part and this
// part are both upper case.
if (!char.IsUpper(chunk.Text[chunkCharacterSpans[currentChunkSpan - 1].Start]) ||
!char.IsUpper(chunk.Text[chunkCharacterSpans[currentChunkSpan].Start]))
{
break;
}
}
if (!PartStartsWith(candidate, candidatePart, chunk.Text, chunkCharacterSpan, compareOption))
{
break;
}
if (includeMatchedSpans)
{
matchedSpans = matchedSpans ?? new List<TextSpan>();
matchedSpans.Add(new TextSpan(candidatePart.Start, chunkCharacterSpan.Length));
}
gotOneMatchThisCandidate = true;
firstMatch = firstMatch ?? currentCandidate;
// If we were contiguous, then keep that value. If we weren't, then keep that
// value. If we don't know, then set the value to 'true' as an initial match is
// obviously contiguous.
contiguous = contiguous ?? true;
candidatePart = new TextSpan(candidatePart.Start + chunkCharacterSpan.Length, candidatePart.Length - chunkCharacterSpan.Length);
}
// Check if we matched anything at all. If we didn't, then we need to unset the
// contiguous bit if we currently had it set.
// If we haven't set the bit yet, then that means we haven't matched anything so
// far, and we don't want to change that.
if (!gotOneMatchThisCandidate && contiguous.HasValue)
{
contiguous = false;
}
// Move onto the next candidate.
currentCandidate++;
}
}
}
}
| |
// 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.Security.Cryptography.Asn1;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Tests.Asn1
{
public sealed class ReadBoolean : Asn1ReaderTests
{
[Theory]
[InlineData(PublicEncodingRules.BER, false, 3, "010100")]
[InlineData(PublicEncodingRules.BER, true, 3, "010101")]
// Padded length
[InlineData(PublicEncodingRules.BER, true, 4, "01810101")]
[InlineData(PublicEncodingRules.BER, true, 3, "0101FF0500")]
[InlineData(PublicEncodingRules.CER, false, 3, "0101000500")]
[InlineData(PublicEncodingRules.CER, true, 3, "0101FF")]
[InlineData(PublicEncodingRules.DER, false, 3, "010100")]
[InlineData(PublicEncodingRules.DER, true, 3, "0101FF0500")]
// Context Specific 0
[InlineData(PublicEncodingRules.DER, true, 3, "8001FF0500")]
// Application 31
[InlineData(PublicEncodingRules.DER, true, 4, "5F1F01FF0500")]
// Private 253
[InlineData(PublicEncodingRules.CER, false, 5, "DF817D01000500")]
public static void ReadBoolean_Success(
PublicEncodingRules ruleSet,
bool expectedValue,
int expectedBytesRead,
string inputHex)
{
byte[] inputData = inputHex.HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
Asn1Tag tag = reader.PeekTag();
bool value;
if (tag.TagClass == TagClass.Universal)
{
value = reader.ReadBoolean();
}
else
{
value = reader.ReadBoolean(tag);
}
if (inputData.Length == expectedBytesRead)
{
Assert.False(reader.HasData, "reader.HasData");
}
else
{
Assert.True(reader.HasData, "reader.HasData");
}
if (expectedValue)
{
Assert.True(value, "value");
}
else
{
Assert.False(value, "value");
}
}
[Theory]
[InlineData(PublicEncodingRules.BER)]
[InlineData(PublicEncodingRules.CER)]
[InlineData(PublicEncodingRules.DER)]
public static void TagMustBeCorrect_Universal(PublicEncodingRules ruleSet)
{
byte[] inputData = { 1, 1, 0 };
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
AssertExtensions.Throws<ArgumentException>(
"expectedTag",
() => reader.ReadBoolean(Asn1Tag.Null));
Assert.True(reader.HasData, "HasData after bad universal tag");
Assert.Throws<CryptographicException>(() => reader.ReadBoolean(new Asn1Tag(TagClass.ContextSpecific, 0)));
Assert.True(reader.HasData, "HasData after wrong tag");
bool value = reader.ReadBoolean();
Assert.False(value, "value");
Assert.False(reader.HasData, "HasData after read");
}
[Theory]
[InlineData(PublicEncodingRules.BER)]
[InlineData(PublicEncodingRules.CER)]
[InlineData(PublicEncodingRules.DER)]
public static void TagMustBeCorrect_Custom(PublicEncodingRules ruleSet)
{
byte[] inputData = { 0x80, 1, 0xFF };
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
AssertExtensions.Throws<ArgumentException>(
"expectedTag",
() => reader.ReadBoolean(Asn1Tag.Null));
Assert.True(reader.HasData, "HasData after bad universal tag");
Assert.Throws<CryptographicException>(() => reader.ReadBoolean());
Assert.True(reader.HasData, "HasData after default tag");
Assert.Throws<CryptographicException>(() => reader.ReadBoolean(new Asn1Tag(TagClass.Application, 0)));
Assert.True(reader.HasData, "HasData after wrong custom class");
Assert.Throws<CryptographicException>(() => reader.ReadBoolean(new Asn1Tag(TagClass.ContextSpecific, 1)));
Assert.True(reader.HasData, "HasData after wrong custom tag value");
bool value = reader.ReadBoolean(new Asn1Tag(TagClass.ContextSpecific, 0));
Assert.True(value, "value");
Assert.False(reader.HasData, "HasData after reading value");
}
[Theory]
[InlineData(PublicEncodingRules.BER, "0101FF", PublicTagClass.Universal, 1)]
[InlineData(PublicEncodingRules.CER, "0101FF", PublicTagClass.Universal, 1)]
[InlineData(PublicEncodingRules.DER, "0101FF", PublicTagClass.Universal, 1)]
[InlineData(PublicEncodingRules.BER, "8001FF", PublicTagClass.ContextSpecific, 0)]
[InlineData(PublicEncodingRules.CER, "4C01FF", PublicTagClass.Application, 12)]
[InlineData(PublicEncodingRules.DER, "DF8A4601FF", PublicTagClass.Private, 1350)]
public static void ExpectedTag_IgnoresConstructed(
PublicEncodingRules ruleSet,
string inputHex,
PublicTagClass tagClass,
int tagValue)
{
byte[] inputData = inputHex.HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
bool val1 = reader.ReadBoolean(new Asn1Tag((TagClass)tagClass, tagValue, true));
Assert.False(reader.HasData);
reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
bool val2 = reader.ReadBoolean(new Asn1Tag((TagClass)tagClass, tagValue, false));
Assert.False(reader.HasData);
Assert.Equal(val1, val2);
}
[Theory]
[InlineData("Empty", PublicEncodingRules.DER, "")]
[InlineData("Empty", PublicEncodingRules.CER, "")]
[InlineData("Empty", PublicEncodingRules.BER, "")]
[InlineData("TagOnly", PublicEncodingRules.BER, "01")]
[InlineData("TagOnly", PublicEncodingRules.CER, "01")]
[InlineData("TagOnly", PublicEncodingRules.DER, "01")]
[InlineData("MultiByte TagOnly", PublicEncodingRules.DER, "9F1F")]
[InlineData("MultiByte TagOnly", PublicEncodingRules.CER, "9F1F")]
[InlineData("MultiByte TagOnly", PublicEncodingRules.BER, "9F1F")]
[InlineData("TagAndLength", PublicEncodingRules.BER, "0101")]
[InlineData("Tag and MultiByteLength", PublicEncodingRules.BER, "01820001")]
[InlineData("TagAndLength", PublicEncodingRules.CER, "8001")]
[InlineData("TagAndLength", PublicEncodingRules.DER, "C001")]
[InlineData("MultiByteTagAndLength", PublicEncodingRules.DER, "9F2001")]
[InlineData("MultiByteTagAndLength", PublicEncodingRules.CER, "9F2001")]
[InlineData("MultiByteTagAndLength", PublicEncodingRules.BER, "9F2001")]
[InlineData("MultiByteTagAndMultiByteLength", PublicEncodingRules.BER, "9F28200001")]
[InlineData("TooShort", PublicEncodingRules.BER, "0100")]
[InlineData("TooShort", PublicEncodingRules.CER, "8000")]
[InlineData("TooShort", PublicEncodingRules.DER, "0100")]
[InlineData("TooLong", PublicEncodingRules.DER, "C0020000")]
[InlineData("TooLong", PublicEncodingRules.CER, "01020000")]
[InlineData("TooLong", PublicEncodingRules.BER, "C081020000")]
[InlineData("MissingContents", PublicEncodingRules.BER, "C001")]
[InlineData("MissingContents", PublicEncodingRules.CER, "0101")]
[InlineData("MissingContents", PublicEncodingRules.DER, "8001")]
[InlineData("NonCanonical", PublicEncodingRules.DER, "0101FE")]
[InlineData("NonCanonical", PublicEncodingRules.CER, "800101")]
[InlineData("Constructed", PublicEncodingRules.BER, "2103010101")]
[InlineData("Constructed", PublicEncodingRules.CER, "2103010101")]
[InlineData("Constructed", PublicEncodingRules.DER, "2103010101")]
[InlineData("WrongTag", PublicEncodingRules.DER, "0400")]
[InlineData("WrongTag", PublicEncodingRules.CER, "0400")]
[InlineData("WrongTag", PublicEncodingRules.BER, "0400")]
public static void ReadBoolean_Failure(
string description,
PublicEncodingRules ruleSet,
string inputHex)
{
_ = description;
byte[] inputData = inputHex.HexToByteArray();
AsnReader reader = new AsnReader(inputData, (AsnEncodingRules)ruleSet);
Asn1Tag tag = default(Asn1Tag);
if (inputData.Length > 0)
{
tag = reader.PeekTag();
}
if (tag.TagClass == TagClass.Universal)
{
Assert.Throws<CryptographicException>(() => reader.ReadBoolean());
}
else
{
Assert.Throws<CryptographicException>(() => reader.ReadBoolean(tag));
}
if (inputData.Length == 0)
{
// If we started with nothing, where did the data come from?
Assert.False(reader.HasData, "reader.HasData");
}
else
{
// Nothing should have moved
Assert.True(reader.HasData, "reader.HasData");
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace WebApiContrib.Tracing.Slab.DemoApp.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// The command returns zero, one or more CimSession objects that represent
/// connections with remote computers established from the current PS Session.
/// </summary>
[Cmdlet(VerbsCommon.Get, "CimSession", DefaultParameterSetName = ComputerNameSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227966")]
[OutputType(typeof(CimSession))]
public sealed class GetCimSessionCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// constructor
/// </summary>
public GetCimSessionCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ComputerName".
/// Specifies one or more connections by providing their ComputerName(s). The
/// Cmdlet then gets CimSession(s) opened with those connections. This parameter
/// is an alternative to using CimSession(s) that also identifies the remote
/// computer(s).
/// </para>
/// <para>
/// This is the only optional parameter of the Cmdlet. If not provided, the
/// Cmdlet returns all CimSession(s) live/active in the runspace.
/// </para>
/// <para>
/// If an instance of CimSession is pipelined to Get-CimSession, the
/// ComputerName property of the instance is bound by name with this parameter.
/// </para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ComputerNameSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] ComputerName
{
get { return computername;}
set
{
computername = value;
base.SetParameter(value, nameComputerName);
}
}
private String[] computername;
/// <summary>
/// The following is the definition of the input parameter "Id".
/// Specifies one or more numeric Id(s) for which to get CimSession(s).
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
ParameterSetName = SessionIdSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public UInt32[] Id
{
get { return id;}
set
{
id = value;
base.SetParameter(value, nameId);
}
}
private UInt32[] id;
/// <summary>
/// The following is the definition of the input parameter "InstanceID".
/// Specifies one or Session Instance IDs
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = InstanceIdSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Guid[] InstanceId
{
get { return instanceid;}
set
{
instanceid = value;
base.SetParameter(value, nameInstanceId);
}
}
private Guid[] instanceid;
/// <summary>
/// The following is the definition of the input parameter "Name".
/// Specifies one or more session Name(s) for which to get CimSession(s). The
/// argument may contain wildcard characters.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = NameSet)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public String[] Name
{
get { return name;}
set
{
name = value;
base.SetParameter(value, nameName);
}
}
private String[] name;
#endregion
#region cmdlet processing methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
cimGetSession = new CimGetSession();
this.AtBeginProcess = false;
}//End BeginProcessing()
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
cimGetSession.GetCimSession(this);
}//End ProcessRecord()
#endregion
#region private members
/// <summary>
/// <see cref="CimGetSession"/> object used to search CimSession from cache
/// </summary>
private CimGetSession cimGetSession;
#region const string of parameter names
internal const string nameComputerName = "ComputerName";
internal const string nameId = "Id";
internal const string nameInstanceId = "InstanceId";
internal const string nameName = "Name";
#endregion
/// <summary>
/// static parameter definition entries
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ComputerNameSet, false),
}
},
{
nameId, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.SessionIdSet, true),
}
},
{
nameInstanceId, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.InstanceIdSet, true),
}
},
{
nameName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.NameSet, true),
}
},
};
/// <summary>
/// static parameter set entries
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.ComputerNameSet, new ParameterSetEntry(0, true) },
{ CimBaseCommand.SessionIdSet, new ParameterSetEntry(1) },
{ CimBaseCommand.InstanceIdSet, new ParameterSetEntry(1) },
{ CimBaseCommand.NameSet, new ParameterSetEntry(1) },
};
#endregion
}//End Class
}//End namespace
| |
#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.Reflection;
using Newtonsoft.Json.Utilities;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#endif
namespace Newtonsoft.Json.Serialization
{
/// <summary>
/// Maps a JSON property to a .NET member or constructor parameter.
/// </summary>
public class JsonProperty
{
internal Required? _required;
internal bool _hasExplicitDefaultValue;
private object _defaultValue;
private bool _hasGeneratedDefaultValue;
private string _propertyName;
internal bool _skipPropertyNameEscape;
private Type _propertyType;
// use to cache contract during deserialization
internal JsonContract PropertyContract { get; set; }
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
/// <value>The name of the property.</value>
public string PropertyName
{
get { return _propertyName; }
set
{
_propertyName = value;
_skipPropertyNameEscape = !JavaScriptUtils.ShouldEscapeJavaScriptString(_propertyName, JavaScriptUtils.HtmlCharEscapeFlags);
}
}
/// <summary>
/// Gets or sets the type that declared this property.
/// </summary>
/// <value>The type that declared this property.</value>
public Type DeclaringType { get; set; }
/// <summary>
/// Gets or sets the order of serialization of a member.
/// </summary>
/// <value>The numeric order of serialization.</value>
public int? Order { get; set; }
/// <summary>
/// Gets or sets the name of the underlying member or parameter.
/// </summary>
/// <value>The name of the underlying member or parameter.</value>
public string UnderlyingName { get; set; }
/// <summary>
/// Gets the <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.
/// </summary>
/// <value>The <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.</value>
public IValueProvider ValueProvider { get; set; }
/// <summary>
/// Gets or sets the <see cref="IAttributeProvider"/> for this property.
/// </summary>
/// <value>The <see cref="IAttributeProvider"/> for this property.</value>
public IAttributeProvider AttributeProvider { get; set; }
/// <summary>
/// Gets or sets the type of the property.
/// </summary>
/// <value>The type of the property.</value>
public Type PropertyType
{
get { return _propertyType; }
set
{
if (_propertyType != value)
{
_propertyType = value;
_hasGeneratedDefaultValue = false;
}
}
}
/// <summary>
/// Gets or sets the <see cref="JsonConverter" /> for the property.
/// If set this converter takes precedence over the contract converter for the property type.
/// </summary>
/// <value>The converter.</value>
public JsonConverter Converter { get; set; }
/// <summary>
/// Gets or sets the member converter.
/// </summary>
/// <value>The member converter.</value>
[Obsolete("MemberConverter is obsolete. Use Converter instead.")]
public JsonConverter MemberConverter
{
get { return Converter; }
set { Converter = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is ignored.
/// </summary>
/// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value>
public bool Ignored { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is readable.
/// </summary>
/// <value><c>true</c> if readable; otherwise, <c>false</c>.</value>
public bool Readable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is writable.
/// </summary>
/// <value><c>true</c> if writable; otherwise, <c>false</c>.</value>
public bool Writable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> has a member attribute.
/// </summary>
/// <value><c>true</c> if has a member attribute; otherwise, <c>false</c>.</value>
public bool HasMemberAttribute { get; set; }
/// <summary>
/// Gets the default value.
/// </summary>
/// <value>The default value.</value>
public object DefaultValue
{
get
{
if (!_hasExplicitDefaultValue)
{
return null;
}
return _defaultValue;
}
set
{
_hasExplicitDefaultValue = true;
_defaultValue = value;
}
}
internal object GetResolvedDefaultValue()
{
if (_propertyType == null)
{
return null;
}
if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue)
{
_defaultValue = ReflectionUtils.GetDefaultValue(PropertyType);
_hasGeneratedDefaultValue = true;
}
return _defaultValue;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is required.
/// </summary>
/// <value>A value indicating whether this <see cref="JsonProperty"/> is required.</value>
public Required Required
{
get { return _required ?? Required.Default; }
set { _required = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this property preserves object references.
/// </summary>
/// <value>
/// <c>true</c> if this instance is reference; otherwise, <c>false</c>.
/// </value>
public bool? IsReference { get; set; }
/// <summary>
/// Gets or sets the property null value handling.
/// </summary>
/// <value>The null value handling.</value>
public NullValueHandling? NullValueHandling { get; set; }
/// <summary>
/// Gets or sets the property default value handling.
/// </summary>
/// <value>The default value handling.</value>
public DefaultValueHandling? DefaultValueHandling { get; set; }
/// <summary>
/// Gets or sets the property reference loop handling.
/// </summary>
/// <value>The reference loop handling.</value>
public ReferenceLoopHandling? ReferenceLoopHandling { get; set; }
/// <summary>
/// Gets or sets the property object creation handling.
/// </summary>
/// <value>The object creation handling.</value>
public ObjectCreationHandling? ObjectCreationHandling { get; set; }
/// <summary>
/// Gets or sets or sets the type name handling.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling? TypeNameHandling { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialized.</value>
public Predicate<object> ShouldSerialize { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be deserialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be deserialized.</value>
public Predicate<object> ShouldDeserialize { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialized.</value>
public Predicate<object> GetIsSpecified { get; set; }
/// <summary>
/// Gets or sets an action used to set whether the property has been deserialized.
/// </summary>
/// <value>An action used to set whether the property has been deserialized.</value>
public Action<object, object> SetIsSpecified { get; set; }
/// <summary>
/// Returns a <see cref="String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="String"/> that represents this instance.
/// </returns>
public override string ToString()
{
return PropertyName;
}
/// <summary>
/// Gets or sets the converter used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items converter.</value>
public JsonConverter ItemConverter { get; set; }
/// <summary>
/// Gets or sets whether this property's collection items are serialized as a reference.
/// </summary>
/// <value>Whether this property's collection items are serialized as a reference.</value>
public bool? ItemIsReference { get; set; }
/// <summary>
/// Gets or sets the type name handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items type name handling.</value>
public TypeNameHandling? ItemTypeNameHandling { get; set; }
/// <summary>
/// Gets or sets the reference loop handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items reference loop handling.</value>
public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; }
internal void WritePropertyName(JsonWriter writer)
{
if (_skipPropertyNameEscape)
{
writer.WritePropertyName(PropertyName, false);
}
else
{
writer.WritePropertyName(PropertyName);
}
}
}
}
| |
// 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.IO.PortsTests;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
namespace System.IO.Ports.Tests
{
public class ReadChar_Generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low read will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the read method and the testcase fails.
private const double maxPercentageDifference = .15;
//The number of random characters to receive
private const int numRndChar = 8;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void ReadWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying read method throws exception without a call to Open()");
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying read method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verifying a read method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void Timeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout);
com.Open();
VerifyTimeout(com);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void SuccessiveReadTimeoutNoData()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout);
com.Open();
Assert.Throws<TimeoutException>(() => com.ReadChar());
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void SuccessiveReadTimeoutSomeData()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
var t = new Task(WriteToCom1);
com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Encoding = new UTF8Encoding();
Debug.WriteLine(
"Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call",
com1.ReadTimeout);
com1.Open();
//Call WriteToCom1 asynchronously this will write to com1 some time before the following call
//to a read method times out
t.Start();
try
{
com1.ReadChar();
}
catch (TimeoutException)
{
}
TCSupport.WaitForTaskCompletion(t);
//Make sure there is no bytes in the buffer so the next call to read will timeout
com1.DiscardInBuffer();
VerifyTimeout(com1);
}
}
private void WriteToCom1()
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] xmitBuffer = new byte[1];
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.Write(xmitBuffer, 0, xmitBuffer.Length);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DefaultParityReplaceByte()
{
VerifyParityReplaceByte(-1, numRndChar - 2);
}
[ConditionalFact(nameof(HasNullModem))]
public void NoParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndChar - 1));
}
[ConditionalFact(nameof(HasNullModem))]
public void RNDParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte(rndGen.Next(0, 128), 0);
}
[ConditionalFact(nameof(HasNullModem))]
public void ParityErrorOnLastByte()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(15);
byte[] bytesToWrite = new byte[numRndChar];
char[] expectedChars = new char[numRndChar];
char[] actualChars = new char[numRndChar + 1];
int actualCharIndex = 0;
/* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream
We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */
Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte");
//Genrate random characters without an parity error
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedChars[i] = (char)randByte;
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80);
//Create a parity error on the last byte
expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace;
// Set the last expected char to be the ParityReplace Byte
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.ReadTimeout = 250;
com1.Open();
com2.Open();
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1);
while (true)
{
int charRead;
try
{
charRead = com1.ReadChar();
}
catch (TimeoutException)
{
break;
}
actualChars[actualCharIndex] = (char)charRead;
actualCharIndex++;
}
Assert.Equal(expectedChars, actualChars.Take(expectedChars.Length).ToArray());
if (1 < com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead);
Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]);
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F);
//Clear the parity error on the last byte
expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1];
VerifyRead(com1, com2, bytesToWrite, expectedChars);
}
}
#endregion
#region Verification for Test Cases
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.ReadTimeout;
int actualTime = 0;
double percentageDifference;
Assert.Throws<TimeoutException>(() => com.ReadChar());
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
Assert.Throws<TimeoutException>(() => com.ReadChar());
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void VerifyReadException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.ReadChar());
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] byteBuffer = new byte[numRndChar];
char[] charBuffer = new char[numRndChar];
int expectedChar;
//Genrate random characters without an parity error
for (int i = 0; i < byteBuffer.Length; i++)
{
int randChar = rndGen.Next(0, 128);
byteBuffer[i] = (byte)randChar;
charBuffer[i] = (char)randChar;
}
if (-1 == parityReplace)
{
//If parityReplace is -1 and we should just use the default value
expectedChar = com1.ParityReplace;
}
else if ('\0' == parityReplace)
{
//If parityReplace is the null charachater and parity replacement should not occur
com1.ParityReplace = (byte)parityReplace;
expectedChar = charBuffer[parityErrorIndex];
}
else
{
//Else parityReplace was set to a value and we should expect this value to be returned on a parity error
com1.ParityReplace = (byte)parityReplace;
expectedChar = parityReplace;
}
//Create an parity error by setting the highest order bit to true
byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80);
charBuffer[parityErrorIndex] = (char)expectedChar;
Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace,
parityErrorIndex);
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.Open();
com2.Open();
VerifyRead(com1, com2, byteBuffer, charBuffer);
}
}
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars)
{
char[] charRcvBuffer = new char[expectedChars.Length];
int rcvBufferSize = 0;
int i;
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 250;
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
i = 0;
while (true)
{
int readInt;
try
{
readInt = com1.ReadChar();
}
catch (TimeoutException)
{
break;
}
//While their are more characters to be read
if (expectedChars.Length <= i)
{
//If we have read in more characters then we expecte
Fail("ERROR!!!: We have received more characters then were sent");
}
charRcvBuffer[i] = (char)readInt;
rcvBufferSize += com1.Encoding.GetByteCount(charRcvBuffer, i, 1);
if (bytesToWrite.Length - rcvBufferSize != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize, com1.BytesToRead);
}
if (readInt != expectedChars[i])
{
//If the character read is not the expected character
Fail("ERROR!!!: Expected to read {0} actual read char {1}", expectedChars[i], (char)readInt);
}
i++;
}
Assert.Equal(expectedChars.Length, i);
}
#endregion
}
}
| |
using System;
using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Configuration.Attributes;
using Glass.Mapper.Sc.DataMappers;
using NUnit.Framework;
using Sitecore.Data;
using Sitecore.FakeDb;
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
[TestFixture]
public class SitecoreFieldTypeMapperFixture
{
#region Method - CanHandle
[Test]
public void CanHandle_TypeHasBeenLoadedByGlass_ReturnsTrue()
{
//Assign
var mapper = new SitecoreFieldTypeMapper();
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyTrue");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubContaining)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_TypeHasNotBeenLoadedByGlass_ReturnsTrueOnDemand()
{
//Assign
var mapper = new SitecoreFieldTypeMapper();
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyFalse");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubContaining)));
//Act
var result = mapper.CanHandle(config, context);
//Assert
Assert.IsTrue(result);
}
#endregion
#region Method - GetField
[Test]
public void GetField_FieldContainsId_ReturnsConcreteType()
{
//Assign
var templateId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
using (Db database = new Db
{
new DbTemplate(new ID(templateId))
{
new DbField("Field")
{
Type = "text"
}
},
new Sitecore.FakeDb.DbItem("Target", ID.NewID, new ID(templateId))
})
{
var item = database.GetItem("/sitecore/content/Target");
var mapper = new SitecoreFieldTypeMapper();
var field = item.Fields["Field"];
var config = new SitecoreFieldConfiguration();
var options = new GetItemOptionsParams();
config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyTrue");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubContaining)));
var service = new SitecoreService(database.Database, context);
var scContext = new SitecoreDataMappingContext(null, item, service, options);
using (new ItemEditing(item, true))
{
field.Value = item.ID.ToString();
}
//Act
var result = mapper.GetField(field, config, scContext) as Stub;
//Assert
Assert.AreEqual(item.ID.Guid, result.Id);
}
}
[Test]
public void GetField_FieldEmpty_ReturnsNull()
{
//Assign
var templateId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
using (Db database = new Db
{
new DbTemplate(new ID(templateId))
{
new DbField("Field")
{
Type = "text"
}
},
new Sitecore.FakeDb.DbItem("Target", ID.NewID, new ID(templateId))
})
{
var item = database.GetItem("/sitecore/content/Target");
var targetId = string.Empty;
var mapper = new SitecoreFieldTypeMapper();
var field = item.Fields["Field"];
var config = new SitecoreFieldConfiguration();
var options = new GetItemOptionsParams();
config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyTrue");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubContaining)));
var service = new SitecoreService(database.Database, context);
var scContext = new SitecoreDataMappingContext(null, item, service, options);
using (new ItemEditing(item, true))
{
field.Value = targetId.ToString();
}
//Act
var result = mapper.GetField(field, config, scContext) as Stub;
//Assert
Assert.IsNull(result);
}
}
[Test]
public void GetField_FieldRandomText_ReturnsNull()
{
//Assign
var templateId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
using (Db database = new Db
{
new DbTemplate(new ID(templateId))
{
new DbField("Field")
{
Type = "text"
}
},
new Sitecore.FakeDb.DbItem("Target", ID.NewID, new ID(templateId))
})
{
var item = database.GetItem("/sitecore/content/Target");
var targetId = "some random text";
var mapper = new SitecoreFieldTypeMapper();
var field = item.Fields["Field"];
var config = new SitecoreFieldConfiguration();
var options = new GetItemOptionsParams();
config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyTrue");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubContaining)));
var service = new SitecoreService(database.Database, context);
var scContext = new SitecoreDataMappingContext(null, item, service, options);
using (new ItemEditing(item, true))
{
field.Value = targetId.ToString();
}
//Act
var result = mapper.GetField(field, config, scContext) as Stub;
//Assert
Assert.IsNull(result);
}
}
//#endregion
//#region Method - SetField
[Test]
public void SetField_ClassContainsId_IdSetInField()
{
var templateId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
using (Db database = new Db
{
new DbTemplate(new ID(templateId))
{
new DbField("Field")
{
Type = "text"
}
},
new Sitecore.FakeDb.DbItem("Target", ID.NewID, new ID(templateId))
})
{
var item = database.GetItem("/sitecore/content/Target");
var targetId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
var mapper = new SitecoreFieldTypeMapper();
var field = item.Fields["Field"];
var config = new SitecoreFieldConfiguration();
var options = new GetItemOptionsParams();
config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyTrue");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubContaining)));
var service = new SitecoreService(database.Database, context);
var propertyValue = new Stub();
propertyValue.Id = targetId;
var scContext = new SitecoreDataMappingContext(null, item, service, options);
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, propertyValue, config, scContext);
}
//Assert
Assert.AreEqual(targetId, Guid.Parse(item["Field"]));
}
}
[Test]
public void SetField_ClassContainsNoIdProperty_ThrowsException()
{
//Assign
var templateId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
using (Db database = new Db
{
new DbTemplate(new ID(templateId))
{
new DbField("Field")
{
Type = "text"
}
},
new Sitecore.FakeDb.DbItem("Target", ID.NewID, new ID(templateId))
})
{
var item = database.GetItem("/sitecore/content/Target");
var targetId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
var mapper = new SitecoreFieldTypeMapper();
var field = item.Fields["Field"];
var options = new GetItemOptionsParams();
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyNoId");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubContaining)));
var service = new SitecoreService(database.Database, context);
var propertyValue = new StubNoId();
var scContext = new SitecoreDataMappingContext(null, item, service, options);
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
Assert.Throws<NotSupportedException>(() =>
{
mapper.SetField(field, propertyValue, config,
scContext);
});
}
//Assert
Assert.AreEqual(string.Empty, item["Field"]);
}
}
[Test]
public void SetField_ContextDatabaseNull_ThrowsException()
{
//Assign
var templateId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
using (Db database = new Db
{
new DbTemplate(new ID(templateId))
{
new DbField("Field")
{
Type = "text"
}
},
new Sitecore.FakeDb.DbItem("Target", ID.NewID, new ID(templateId))
})
{
var item = database.GetItem("/sitecore/content/Target");
var mapper = new SitecoreFieldTypeMapper();
var field = item.Fields["Field"];
var options = new GetItemOptionsParams();
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyNoId");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubContaining)));
var service = new SitecoreService(null as Database, context);
var propertyValue = new StubNoId();
var scContext = new SitecoreDataMappingContext(null, item, service, options);
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
Assert.Throws<NullReferenceException>(() =>
{
mapper.SetField(field, propertyValue, config, scContext);
});
}
//Assert
Assert.AreEqual(string.Empty, item["Field"]);
}
}
[Test]
public void SetField_ContextNull_ThrowsException()
{
//Assign
var templateId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
using (Db database = new Db
{
new DbTemplate(new ID(templateId))
{
new DbField("Field")
{
Type = "text"
}
},
new Sitecore.FakeDb.DbItem("Target", ID.NewID, new ID(templateId))
})
{
var item = database.GetItem("/sitecore/content/Target");
var mapper = new SitecoreFieldTypeMapper();
var field = item.Fields["Field"];
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyNoId");
var propertyValue = new StubNoId();
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
using (new ItemEditing(item, true))
{
Assert.Throws<ArgumentNullException>(() =>
{
mapper.SetField(field, propertyValue, config, null);
});
}
}
//Assert
Assert.AreEqual(string.Empty, item["Field"]);
}
}
[Test]
public void SetField_ContextServiceNull_ThrowsException()
{
//Assign
var templateId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
using (Db database = new Db
{
new DbTemplate(new ID(templateId))
{
new DbField("Field")
{
Type = "text"
}
},
new Sitecore.FakeDb.DbItem("Target", ID.NewID, new ID(templateId))
})
{
var item = database.GetItem("/sitecore/content/Target");
var mapper = new SitecoreFieldTypeMapper();
var field = item.Fields["Field"];
var options = new GetItemOptionsParams();
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyNoId");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubContaining)));
var propertyValue = new StubNoId();
var scContext = new SitecoreDataMappingContext(null, item, null, options);
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
Assert.Throws<NullReferenceException>(() =>
{
mapper.SetField(field, propertyValue, config, scContext);
});
}
//Assert
Assert.AreEqual(string.Empty, item["Field"]);
}
}
[Test]
public void SetField_ClassContainsIdButItemMissing_ThrowsException()
{
//Assign
var templateId = Guid.Parse("{BB01B0A5-A3F0-410E-8A6D-07FF3A1E78C3}");
using (Db database = new Db
{
new DbTemplate(new ID(templateId))
{
new DbField("Field")
{
Type = "text"
}
},
new Sitecore.FakeDb.DbItem("Target", ID.NewID, new ID(templateId))
})
{
var item = database.GetItem("/sitecore/content/Target");
var targetId = Guid.Parse("{11111111-A3F0-410E-8A6D-07FF3A1E78C3}");
var mapper = new SitecoreFieldTypeMapper();
var field = item.Fields["Field"];
var options = new GetItemOptionsParams();
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(StubContaining).GetProperty("PropertyTrue");
var context = Context.Create(Utilities.CreateStandardResolver());
context.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(StubContaining)));
var service = new SitecoreService(database.Database, context);
var propertyValue = new Stub();
propertyValue.Id = targetId;
var scContext = new SitecoreDataMappingContext(null, item, service, options);
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
Assert.Throws<NullReferenceException>(() =>
{
mapper.SetField(field, propertyValue, config, scContext);
});
}
}
#endregion
#region Stubs
[SitecoreType]
public class Stub
{
[SitecoreId]
public virtual Guid Id { get; set; }
}
public class StubContaining : StubInterface
{
public Stub PropertyTrue { get; set; }
public StubContaining PropertyFalse { get; set; }
public StubNoId PropertyNoId { get; set; }
}
[SitecoreType]
public class StubNoId
{
}
public interface StubInterface
{
}
#endregion
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Internal;
using Orleans.Runtime;
using Orleans.Streams;
using Orleans.TestingHost.Utils;
using Tester;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
namespace UnitTests.StreamingTests
{
public class SingleStreamTestRunner
{
public const string SMS_STREAM_PROVIDER_NAME = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME;
public const string SMS_STREAM_PROVIDER_NAME_DO_NOT_OPTIMIZE_FOR_IMMUTABLE_DATA = "SMSProviderDoNotOptimizeForImmutableData";
public const string AQ_STREAM_PROVIDER_NAME = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME;
private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(30);
private ProducerProxy producer;
private ConsumerProxy consumer;
private const int Many = 3;
private const int ItemCount = 10;
private ILogger logger;
private readonly string streamProviderName;
private readonly int testNumber;
private readonly bool runFullTest;
private readonly SafeRandom random;
private readonly IInternalClusterClient client;
internal SingleStreamTestRunner(IInternalClusterClient client, string streamProvider, int testNum = 0, bool fullTest = true)
{
this.client = client;
this.streamProviderName = streamProvider;
this.logger = TestingUtils.CreateDefaultLoggerFactory($"{this.GetType().Name}.log").CreateLogger<SingleStreamTestRunner>();
this.testNumber = testNum;
this.runFullTest = fullTest;
this.random = TestConstants.random;
}
private void Heading(string testName)
{
logger.Info("\n\n************************ {0} {1}_{2} ********************************* \n\n", testNumber, streamProviderName, testName);
}
//------------------------ One to One ----------------------//
public async Task StreamTest_01_OneProducerGrainOneConsumerGrain()
{
Heading("StreamTest_01_ConsumerJoinsFirstProducerLater");
Guid streamId = Guid.NewGuid();
// consumer joins first, producer later
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
await BasicTestAsync();
await StopProxies();
streamId = Guid.NewGuid();
// produce joins first, consumer later
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_02_OneProducerGrainOneConsumerClient()
{
Heading("StreamTest_02_OneProducerGrainOneConsumerClient");
Guid streamId = Guid.NewGuid();
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
await BasicTestAsync();
await StopProxies();
streamId = Guid.NewGuid();
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_03_OneProducerClientOneConsumerGrain()
{
Heading("StreamTest_03_OneProducerClientOneConsumerGrain");
Guid streamId = Guid.NewGuid();
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client);
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client);
await BasicTestAsync();
await StopProxies();
streamId = Guid.NewGuid();
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client);
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_04_OneProducerClientOneConsumerClient()
{
Heading("StreamTest_04_OneProducerClientOneConsumerClient");
Guid streamId = Guid.NewGuid();
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client);
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client);
await BasicTestAsync();
await StopProxies();
streamId = Guid.NewGuid();
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client);
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client);
await BasicTestAsync();
await StopProxies();
}
//------------------------ MANY to Many different grains ----------------------//
public async Task StreamTest_05_ManyDifferent_ManyProducerGrainsManyConsumerGrains()
{
Heading("StreamTest_05_ManyDifferent_ManyProducerGrainsManyConsumerGrains");
Guid streamId = Guid.NewGuid();
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, null, Many);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, null, Many);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_06_ManyDifferent_ManyProducerGrainManyConsumerClients()
{
Heading("StreamTest_06_ManyDifferent_ManyProducerGrainManyConsumerClients");
Guid streamId = Guid.NewGuid();
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client, Many);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, null, Many);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_07_ManyDifferent_ManyProducerClientsManyConsumerGrains()
{
Heading("StreamTest_07_ManyDifferent_ManyProducerClientsManyConsumerGrains");
Guid streamId = Guid.NewGuid();
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, null, Many);
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client, Many);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_08_ManyDifferent_ManyProducerClientsManyConsumerClients()
{
Heading("StreamTest_08_ManyDifferent_ManyProducerClientsManyConsumerClients");
Guid streamId = Guid.NewGuid();
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client, Many);
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client, Many);
await BasicTestAsync();
await StopProxies();
}
//------------------------ MANY to Many Same grains ----------------------//
public async Task StreamTest_09_ManySame_ManyProducerGrainsManyConsumerGrains()
{
Heading("StreamTest_09_ManySame_ManyProducerGrainsManyConsumerGrains");
Guid streamId = Guid.NewGuid();
Guid grain1 = Guid.NewGuid();
Guid grain2 = Guid.NewGuid();
Guid[] consumerGrainIds = new Guid[] { grain1, grain1, grain1 };
Guid[] producerGrainIds = new Guid[] { grain2, grain2, grain2 };
// producer joins first, consumer later
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, producerGrainIds);
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, consumerGrainIds);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_10_ManySame_ManyConsumerGrainsManyProducerGrains()
{
Heading("StreamTest_10_ManySame_ManyConsumerGrainsManyProducerGrains");
Guid streamId = Guid.NewGuid();
Guid grain1 = Guid.NewGuid();
Guid grain2 = Guid.NewGuid();
Guid[] consumerGrainIds = new Guid[] { grain1, grain1, grain1 };
Guid[] producerGrainIds = new Guid[] { grain2, grain2, grain2 };
// consumer joins first, producer later
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, consumerGrainIds);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, producerGrainIds);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_11_ManySame_ManyProducerGrainsManyConsumerClients()
{
Heading("StreamTest_11_ManySame_ManyProducerGrainsManyConsumerClients");
Guid streamId = Guid.NewGuid();
Guid grain1 = Guid.NewGuid();
Guid[] producerGrainIds = new Guid[] { grain1, grain1, grain1, grain1 };
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, producerGrainIds);
consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, this.client, Many);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_12_ManySame_ManyProducerClientsManyConsumerGrains()
{
Heading("StreamTest_12_ManySame_ManyProducerClientsManyConsumerGrains");
Guid streamId = Guid.NewGuid();
Guid grain1 = Guid.NewGuid();
Guid[] consumerGrainIds = new Guid[] { grain1, grain1, grain1 };
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, consumerGrainIds);
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, null, logger, this.client, Many);
await BasicTestAsync();
await StopProxies();
}
//------------------------ MANY to Many producer consumer same grain ----------------------//
public async Task StreamTest_13_SameGrain_ConsumerFirstProducerLater(bool useReentrantGrain)
{
Heading("StreamTest_13_SameGrain_ConsumerFirstProducerLater");
Guid streamId = Guid.NewGuid();
int grain1 = random.Next();
int[] grainIds = new int[] { grain1 };
// consumer joins first, producer later
this.consumer = await ConsumerProxy.NewProducerConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, grainIds, useReentrantGrain, this.client);
this.producer = await ProducerProxy.NewProducerConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, grainIds, useReentrantGrain, this.client);
await BasicTestAsync();
await StopProxies();
}
public async Task StreamTest_14_SameGrain_ProducerFirstConsumerLater(bool useReentrantGrain)
{
Heading("StreamTest_14_SameGrain_ProducerFirstConsumerLater");
Guid streamId = Guid.NewGuid();
int grain1 = random.Next();
int[] grainIds = new int[] { grain1 };
// produce joins first, consumer later
this.producer = await ProducerProxy.NewProducerConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, grainIds, useReentrantGrain, this.client);
this.consumer = await ConsumerProxy.NewProducerConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, grainIds, useReentrantGrain, this.client);
await BasicTestAsync();
await StopProxies();
}
//----------------------------------------------//
public async Task StreamTest_15_ConsumeAtProducersRequest()
{
Heading("StreamTest_15_ConsumeAtProducersRequest");
Guid streamId = Guid.NewGuid();
// this reproduces a scenario was discovered to not work (deadlock) by the Halo team. the scenario is that
// where a producer calls a consumer, which subscribes to the calling producer.
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
Guid consumerGrainId = await producer.AddNewConsumerGrain();
this.consumer = ConsumerProxy.NewConsumerGrainAsync_WithoutBecomeConsumer(consumerGrainId, this.logger, this.client);
await BasicTestAsync();
await StopProxies();
}
internal async Task StreamTest_Create_OneProducerGrainOneConsumerGrain()
{
Guid streamId = Guid.NewGuid();
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client);
}
public async Task StreamTest_16_Deactivation_OneProducerGrainOneConsumerGrain()
{
Heading("StreamTest_16_Deactivation_OneProducerGrainOneConsumerGrain");
Guid streamId = Guid.NewGuid();
Guid[] consumerGrainIds = { Guid.NewGuid() };
Guid[] producerGrainIds = { Guid.NewGuid() };
// consumer joins first, producer later
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, consumerGrainIds);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, producerGrainIds);
await BasicTestAsync(false);
//await consumer.StopBeingConsumer();
await StopProxies();
await consumer.DeactivateOnIdle();
await producer.DeactivateOnIdle();
await TestingUtils.WaitUntilAsync(lastTry => CheckGrainsDeactivated(null, consumer, false), _timeout);
await TestingUtils.WaitUntilAsync(lastTry => CheckGrainsDeactivated(producer, null, false), _timeout);
logger.Info("\n\n\n*******************************************************************\n\n\n");
this.consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, this.streamProviderName, this.logger, this.client, consumerGrainIds);
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamId, this.streamProviderName, null, this.logger, this.client, producerGrainIds);
await BasicTestAsync(false);
await StopProxies();
}
//public async Task StreamTest_17_Persistence_OneProducerGrainOneConsumerGrain()
//{
// Heading("StreamTest_17_Persistence_OneProducerGrainOneConsumerGrain");
// StreamId streamId = StreamId.NewRandomStreamId();
// // consumer joins first, producer later
// consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(false);
// await consumer.DeactivateOnIdle();
// await producer.DeactivateOnIdle();
// await UnitTestBase.WaitUntilAsync(() => CheckGrainsDeactivated(null, consumer, assertAreEqual: false), _timeout);
// await UnitTestBase.WaitUntilAsync(() => CheckGrainsDeactivated(producer, null, assertAreEqual: false), _timeout);
// logger.Info("*******************************************************************");
// //await BasicTestAsync(false);
// //await StopProxies();
//}
public async Task StreamTest_19_ConsumerImplicitlySubscribedToProducerClient()
{
Heading("StreamTest_19_ConsumerImplicitlySubscribedToProducerClient");
string consumerTypeName = typeof(Streaming_ImplicitlySubscribedConsumerGrain).FullName;
Guid streamGuid = Guid.NewGuid();
producer = await ProducerProxy.NewProducerClientObjectsAsync(streamGuid, streamProviderName, "TestNamespace1", logger, this.client);
this.consumer = ConsumerProxy.NewConsumerGrainAsync_WithoutBecomeConsumer(streamGuid, this.logger, this.client, consumerTypeName);
logger.Info("\n** Starting Test {0}.\n", testNumber);
var producerCount = await producer.ProducerCount;
logger.Info("\n** Test {0} BasicTestAsync: producerCount={1}.\n", testNumber, producerCount);
Func<bool, Task<bool>> waitUntilFunc =
async lastTry =>
0 < await TestUtils.GetActivationCount(this.client, consumerTypeName) && await this.CheckCounters(this.producer, this.consumer, false);
await producer.ProduceSequentialSeries(ItemCount);
await TestingUtils.WaitUntilAsync(waitUntilFunc, _timeout);
await CheckCounters(producer, consumer);
await StopProxies();
}
public async Task StreamTest_20_ConsumerImplicitlySubscribedToProducerGrain()
{
Heading("StreamTest_20_ConsumerImplicitlySubscribedToProducerGrain");
string consumerTypeName = typeof(Streaming_ImplicitlySubscribedConsumerGrain).FullName;
Guid streamGuid = Guid.NewGuid();
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamGuid, this.streamProviderName, "TestNamespace1", this.logger, this.client);
this.consumer = ConsumerProxy.NewConsumerGrainAsync_WithoutBecomeConsumer(streamGuid, this.logger, this.client, consumerTypeName);
logger.Info("\n** Starting Test {0}.\n", testNumber);
var producerCount = await producer.ProducerCount;
logger.Info("\n** Test {0} BasicTestAsync: producerCount={1}.\n", testNumber, producerCount);
Func<bool, Task<bool>> waitUntilFunc =
async lastTry =>
0 < await TestUtils.GetActivationCount(this.client, consumerTypeName) && await this.CheckCounters(this.producer, this.consumer, false);
await producer.ProduceSequentialSeries(ItemCount);
await TestingUtils.WaitUntilAsync(waitUntilFunc, _timeout);
await CheckCounters(producer, consumer);
await StopProxies();
}
public async Task StreamTest_21_GenericConsumerImplicitlySubscribedToProducerGrain()
{
Heading("StreamTest_21_GenericConsumerImplicitlySubscribedToProducerGrain");
//ToDo in migrate: the following consumer grain is not implemented in VSO and all tests depend on it fail.
string consumerTypeName = "UnitTests.Grains.Streaming_ImplicitlySubscribedGenericConsumerGrain";//typeof(Streaming_ImplicitlySubscribedGenericConsumerGrain).FullName;
Guid streamGuid = Guid.NewGuid();
this.producer = await ProducerProxy.NewProducerGrainsAsync(streamGuid, this.streamProviderName, "TestNamespace1", this.logger, this.client);
this.consumer = ConsumerProxy.NewConsumerGrainAsync_WithoutBecomeConsumer(streamGuid, this.logger, this.client, consumerTypeName);
logger.Info("\n** Starting Test {0}.\n", testNumber);
var producerCount = await producer.ProducerCount;
logger.Info("\n** Test {0} BasicTestAsync: producerCount={1}.\n", testNumber, producerCount);
Func<bool, Task<bool>> waitUntilFunc =
async lastTry =>
0 < await TestUtils.GetActivationCount(this.client, consumerTypeName) && await this.CheckCounters(this.producer, this.consumer, false);
await producer.ProduceSequentialSeries(ItemCount);
await TestingUtils.WaitUntilAsync(waitUntilFunc, _timeout);
await CheckCounters(producer, consumer);
await StopProxies();
}
public async Task StreamTest_22_TestImmutabilityDuringStreaming()
{
Heading("StreamTest_22_TestImmutabilityDuringStreaming");
IStreamingImmutabilityTestGrain itemProducer = this.client.GetGrain<IStreamingImmutabilityTestGrain>(Guid.NewGuid());
string producerSilo = await itemProducer.GetSiloIdentifier();
// Obtain consumer in silo of item producer
IStreamingImmutabilityTestGrain consumerSameSilo = null;
do
{
var itemConsumer = this.client.GetGrain<IStreamingImmutabilityTestGrain>(Guid.NewGuid());
var consumerSilo = await itemConsumer.GetSiloIdentifier();
if (consumerSilo == producerSilo)
consumerSameSilo = itemConsumer;
} while (consumerSameSilo == null);
// Test behavior if immutability is enabled
await consumerSameSilo.SubscribeToStream(itemProducer.GetPrimaryKey(), SMS_STREAM_PROVIDER_NAME);
await itemProducer.SetTestObjectStringProperty("VALUE_IN_IMMUTABLE_STREAM");
await itemProducer.SendTestObject(SMS_STREAM_PROVIDER_NAME);
Assert.Equal("VALUE_IN_IMMUTABLE_STREAM", await consumerSameSilo.GetTestObjectStringProperty());
// Now violate immutability by updating the property in the consumer.
await consumerSameSilo.SetTestObjectStringProperty("ILLEGAL_CHANGE");
Assert.Equal("ILLEGAL_CHANGE", await itemProducer.GetTestObjectStringProperty());
await consumerSameSilo.UnsubscribeFromStream();
// Test behavior if immutability is disabled
itemProducer = this.client.GetGrain<IStreamingImmutabilityTestGrain>(Guid.NewGuid());
await consumerSameSilo.SubscribeToStream(itemProducer.GetPrimaryKey(), SMS_STREAM_PROVIDER_NAME_DO_NOT_OPTIMIZE_FOR_IMMUTABLE_DATA);
await itemProducer.SetTestObjectStringProperty("VALUE_IN_MUTABLE_STREAM");
await itemProducer.SendTestObject(SMS_STREAM_PROVIDER_NAME_DO_NOT_OPTIMIZE_FOR_IMMUTABLE_DATA);
Assert.Equal("VALUE_IN_MUTABLE_STREAM", await consumerSameSilo.GetTestObjectStringProperty());
// Modify the items property and check it has no impact
await consumerSameSilo.SetTestObjectStringProperty("ALLOWED_CHANGE");
Assert.Equal("ALLOWED_CHANGE", await consumerSameSilo.GetTestObjectStringProperty());
Assert.Equal("VALUE_IN_MUTABLE_STREAM", await itemProducer.GetTestObjectStringProperty());
await consumerSameSilo.UnsubscribeFromStream();
}
//-----------------------------------------------------------------------------//
public async Task BasicTestAsync(bool fullTest = true)
{
logger.Info("\n** Starting Test {0} BasicTestAsync.\n", testNumber);
var producerCount = await producer.ProducerCount;
var consumerCount = await consumer.ConsumerCount;
logger.Info("\n** Test {0} BasicTestAsync: producerCount={1}, consumerCount={2}.\n", testNumber, producerCount, consumerCount);
await producer.ProduceSequentialSeries(ItemCount);
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, false), _timeout);
await CheckCounters(producer, consumer);
if (runFullTest)
{
await producer.ProduceParallelSeries(ItemCount);
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, false), _timeout);
await CheckCounters(producer, consumer);
await producer.ProducePeriodicSeries(ItemCount);
await TestingUtils.WaitUntilAsync(lastTry => CheckCounters(producer, consumer, false), _timeout);
await CheckCounters(producer, consumer);
}
await ValidatePubSub(producer.StreamId, producer.ProviderName);
}
public async Task StopProxies()
{
await producer.StopBeingProducer();
await AssertProducerCount(0, producer.ProviderName, producer.StreamIdGuid);
await consumer.StopBeingConsumer();
}
private async Task<bool> CheckCounters(ProducerProxy producer, ConsumerProxy consumer, bool assertAreEqual = true)
{
var consumerCount = await consumer.ConsumerCount;
Assert.NotEqual(0, consumerCount); // "no consumers were detected."
var producerCount = await producer.ProducerCount;
var numProduced = await producer.ExpectedItemsProduced;
var expectConsumed = numProduced * consumerCount;
var numConsumed = await consumer.ItemsConsumed;
logger.Info("Test {0} CheckCounters: numProduced = {1}, expectConsumed = {2}, numConsumed = {3}", testNumber, numProduced, expectConsumed, numConsumed);
if (assertAreEqual)
{
Assert.Equal(expectConsumed, numConsumed); // String.Format("expectConsumed = {0}, numConsumed = {1}", expectConsumed, numConsumed));
return true;
}
else
{
return expectConsumed == numConsumed;
}
}
private async Task AssertProducerCount(int expectedCount, string providerName, Guid streamIdGuid)
{
// currently, we only support checking the producer count on the SMS rendezvous grain.
if (providerName == SMS_STREAM_PROVIDER_NAME)
{
var streamId = StreamId.Create(StreamTestsConstants.DefaultStreamNamespace, streamIdGuid);
var actualCount = await StreamTestUtils.GetStreamPubSub(this.client).ProducerCount(new InternalStreamId(providerName, streamId));
logger.Info("StreamingTestRunner.AssertProducerCount: expected={0} actual (SMSStreamRendezvousGrain.ProducerCount)={1} streamId={2}", expectedCount, actualCount, streamId);
Assert.Equal(expectedCount, actualCount);
}
}
private Task ValidatePubSub(StreamId streamId, string providerName)
{
var intStreamId = new InternalStreamId(providerName, streamId);
var rendez = this.client.GetGrain<IPubSubRendezvousGrain>(intStreamId.ToString());
return rendez.Validate();
}
private async Task<bool> CheckGrainsDeactivated(ProducerProxy producer, ConsumerProxy consumer, bool assertAreEqual = true)
{
var activationCount = 0;
string str = "";
if (producer != null)
{
str = "Producer";
activationCount = await producer.GetNumActivations(this.client);
}
else if (consumer != null)
{
str = "Consumer";
activationCount = await consumer.GetNumActivations(this.client);
}
var expectActivationCount = 0;
logger.Info(
"Test {testNumber} CheckGrainsDeactivated: {type}ActivationCount = {activationCount}, Expected{type}ActivationCount = {expectActivationCount}",
testNumber,
str,
activationCount,
str,
expectActivationCount);
if (assertAreEqual)
{
Assert.Equal(expectActivationCount, activationCount); // String.Format("Expected{0}ActivationCount = {1}, {0}ActivationCount = {2}", str, expectActivationCount, activationCount));
}
return expectActivationCount == activationCount;
}
}
}
//public async Task AQ_1_ConsumerJoinsFirstProducerLater()
//{
// logger.Info("\n\n ************************ AQ_1_ConsumerJoinsFirstProducerLater ********************************* \n\n");
// streamId = StreamId.NewRandomStreamId();
// streamProviderName = AQ_STREAM_PROVIDER_NAME;
// // consumer joins first, producer later
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//public async Task AQ_2_ProducerJoinsFirstConsumerLater()
//{
// logger.Info("\n\n ************************ AQ_2_ProducerJoinsFirstConsumerLater ********************************* \n\n");
// streamId = StreamId.NewRandomStreamId();
// streamProviderName = AQ_STREAM_PROVIDER_NAME;
// // produce joins first, consumer later
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("BVT"), TestCategory("Streaming")]
//public async Task StreamTest_2_ProducerJoinsFirstConsumerLater()
//{
// logger.Info("\n\n ************************ StreamTest_2_ProducerJoinsFirstConsumerLater ********************************* \n\n");
// streamId = Guid.NewGuid();
// streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// // produce joins first, consumer later
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("BVT"), TestCategory("Streaming")]
//public async Task StreamTestProducerOnly()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// await TestGrainProducerOnlyAsync(streamId, this.streamProviderName);
//}
//[Fact, TestCategory("BVT"), TestCategory("Streaming")]
//public void AQProducerOnly()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = AQ_STREAM_PROVIDER_NAME;
// TestGrainProducerOnlyAsync(streamId, this.streamProviderName).Wait();
//}
//private async Task TestGrainProducerOnlyAsync(Guid streamId, string streamProvider)
//{
// // no consumers, one producer
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProvider, logger);
// await producer.ProduceSequentialSeries(0, ItemsPerSeries);
// var numProduced = await producer.NumberProduced;
// logger.Info("numProduced = " + numProduced);
// Assert.Equal(numProduced, ItemsPerSeries);
// // note that the value returned from successive calls to Do...Production() methods is a cumulative total.
// await producer.ProduceParallelSeries(ItemsPerSeries, ItemsPerSeries);
// numProduced = await producer.NumberProduced;
// logger.Info("numProduced = " + numProduced);
// Assert.Equal(numProduced, ItemsPerSeries * 2);
//}
////------------------------ MANY to One ----------------------//
//[Fact, TestCategory("BVT"), TestCategory("Streaming")]
//public async Task StreamTest_Many_5_ManyProducerGrainsOneConsumerGrain()
//{
// logger.Info("\n\n ************************ StreamTest_6_ManyProducerGrainsOneConsumerGrain ********************************* \n\n");
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger, Many);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("BVT"), TestCategory("Streaming")]
//public async Task StreamTest_Many6_OneProducerGrainManyConsumerGrains()
//{
// logger.Info("\n\n ************************ StreamTest_7_OneProducerGrainManyConsumerGrains ********************************* \n\n");
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger, Many);
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("Streaming")]
//public async Task StreamTest_Many_8_ManyProducerGrainsOneConsumerClient()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger);
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger, Many);
// await BasicTestAsync(producer, consumer);
//}
//// note: this test currently fails intermittently due to synchronization issues in the StreamTest provider. it has been
//// removed from nightly builds until this has been addressed.
//[Fact, TestCategory("Streaming")]
//public async Task _StreamTestManyProducerClientsOneConsumerGrain()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger);
// var producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, logger, Many);
// await BasicTestAsync(producer, consumer);
//}
//// note: this test currently fails intermittently due to synchronization issues in the StreamTest provider. it has been
//// removed from nightly builds until this has been addressed.
//[Fact, TestCategory("Streaming")]
//public async Task _StreamTestManyProducerClientsOneConsumerClient()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger);
// var producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, logger, Many);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("Streaming")]
//public async Task _StreamTestOneProducerGrainManyConsumerClients()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, Many);
// var producer = await ProducerProxy.NewProducerGrainsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("Streaming")]
//public async Task _StreamTestOneProducerClientManyConsumerGrains()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerGrainsAsync(streamId, streamProviderName, logger, Many);
// var producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
//[Fact, TestCategory("Streaming")]
//public async Task _StreamTestOneProducerClientManyConsumerClients()
//{
// streamId = Guid.NewGuid();
// this.streamProviderName = StreamTest_STREAM_PROVIDER_NAME;
// var consumer = await ConsumerProxy.NewConsumerClientObjectsAsync(streamId, streamProviderName, logger, Many);
// var producer = await ProducerProxy.NewProducerClientObjectsAsync(streamId, streamProviderName, logger);
// await BasicTestAsync(producer, consumer);
//}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Text;
using System.Xml.XPath;
namespace MS.Internal.Xml.Cache
{
/// <summary>
/// The 0th node in each page contains a non-null reference to an XPathNodePageInfo internal class that provides
/// information about that node's page. The other fields in the 0th node are undefined and should never
/// be used.
/// </summary>
internal sealed class XPathNodePageInfo
{
private readonly int _pageNum;
private int _nodeCount;
private readonly XPathNode[] _pagePrev;
private XPathNode[] _pageNext;
/// <summary>
/// Constructor.
/// </summary>
public XPathNodePageInfo(XPathNode[] pagePrev, int pageNum)
{
_pagePrev = pagePrev;
_pageNum = pageNum;
_nodeCount = 1; // Every node page contains PageInfo at 0th position
}
/// <summary>
/// Return the sequential page number of the page containing nodes that share this information atom.
/// </summary>
public int PageNumber
{
get { return _pageNum; }
}
/// <summary>
/// Return the number of nodes allocated in this page.
/// </summary>
public int NodeCount
{
get { return _nodeCount; }
set { _nodeCount = value; }
}
/// <summary>
/// Return the previous node page in the document.
/// </summary>
public XPathNode[] PreviousPage
{
get { return _pagePrev; }
}
/// <summary>
/// Return the next node page in the document.
/// </summary>
public XPathNode[] NextPage
{
get { return _pageNext; }
set { _pageNext = value; }
}
}
/// <summary>
/// There is a great deal of redundancy in typical Xml documents. Even in documents with thousands or millions
/// of nodes, there are a small number of common names and types. And since nodes are allocated in pages in
/// document order, nodes on the same page with the same name and type are likely to have the same sibling and
/// parent pages as well.
/// Redundant information is shared by creating immutable, atomized objects. This is analogous to the
/// string.Intern() operation. If a node's name, type, or parent/sibling pages are modified, then a new
/// InfoAtom needs to be obtained, since other nodes may still be referencing the old InfoAtom.
/// </summary>
internal sealed class XPathNodeInfoAtom : IEquatable<XPathNodeInfoAtom>
{
private string _localName;
private string _namespaceUri;
private string _prefix;
private string _baseUri;
private XPathNode[] _pageParent;
private XPathNode[] _pageSibling;
private XPathNode[] _pageSimilar;
private XPathDocument _doc;
private int _lineNumBase;
private int _linePosBase;
private int _hashCode;
private int _localNameHash;
private XPathNodeInfoAtom _next;
private XPathNodePageInfo _pageInfo;
/// <summary>
/// Construct information for the 0th node in each page. The only field which is defined is this.pageInfo,
/// and it contains information about that page (pageNum, nextPage, etc.).
/// </summary>
public XPathNodeInfoAtom(XPathNodePageInfo pageInfo)
{
_pageInfo = pageInfo;
}
/// <summary>
/// Construct a new shared information atom. This method should only be used by the XNodeInfoTable.
/// </summary>
public XPathNodeInfoAtom(string localName, string namespaceUri, string prefix, string baseUri,
XPathNode[] pageParent, XPathNode[] pageSibling, XPathNode[] pageSimilar,
XPathDocument doc, int lineNumBase, int linePosBase)
{
Init(localName, namespaceUri, prefix, baseUri, pageParent, pageSibling, pageSimilar, doc, lineNumBase, linePosBase);
}
/// <summary>
/// Initialize an existing shared information atom. This method should only be used by the XNodeInfoTable.
/// </summary>
public void Init(string localName, string namespaceUri, string prefix, string baseUri,
XPathNode[] pageParent, XPathNode[] pageSibling, XPathNode[] pageSimilar,
XPathDocument doc, int lineNumBase, int linePosBase)
{
Debug.Assert(localName != null && namespaceUri != null && prefix != null && doc != null);
_localName = localName;
_namespaceUri = namespaceUri;
_prefix = prefix;
_baseUri = baseUri;
_pageParent = pageParent;
_pageSibling = pageSibling;
_pageSimilar = pageSimilar;
_doc = doc;
_lineNumBase = lineNumBase;
_linePosBase = linePosBase;
_next = null;
_pageInfo = null;
_hashCode = 0;
_localNameHash = 0;
for (int i = 0; i < _localName.Length; i++)
unchecked { _localNameHash += (_localNameHash << 7) ^ _localName[i]; }
}
/// <summary>
/// Returns information about the node page. Only the 0th node on each page has this property defined.
/// </summary>
public XPathNodePageInfo PageInfo
{
get { return _pageInfo; }
}
/// <summary>
/// Return the local name part of nodes that share this information atom.
/// </summary>
public string LocalName
{
get { return _localName; }
}
/// <summary>
/// Return the namespace name part of nodes that share this information atom.
/// </summary>
public string NamespaceUri
{
get { return _namespaceUri; }
}
/// <summary>
/// Return the prefix name part of nodes that share this information atom.
/// </summary>
public string Prefix
{
get { return _prefix; }
}
/// <summary>
/// Return the base Uri of nodes that share this information atom.
/// </summary>
public string BaseUri
{
get { return _baseUri; }
}
/// <summary>
/// Return the page containing the next sibling of nodes that share this information atom.
/// </summary>
public XPathNode[] SiblingPage
{
get { return _pageSibling; }
}
/// <summary>
/// Return the page containing the next element having a name which has same hashcode as this element.
/// </summary>
public XPathNode[] SimilarElementPage
{
get { return _pageSimilar; }
}
/// <summary>
/// Return the page containing the parent of nodes that share this information atom.
/// </summary>
public XPathNode[] ParentPage
{
get { return _pageParent; }
}
/// <summary>
/// Return the page containing the owner document of nodes that share this information atom.
/// </summary>
public XPathDocument Document
{
get { return _doc; }
}
/// <summary>
/// Return the line number to which a line number offset stored in the XPathNode is added.
/// </summary>
public int LineNumberBase
{
get { return _lineNumBase; }
}
/// <summary>
/// Return the line position to which a line position offset stored in the XPathNode is added.
/// </summary>
public int LinePositionBase
{
get { return _linePosBase; }
}
/// <summary>
/// Return cached hash code of the local name of nodes which share this information atom.
/// </summary>
public int LocalNameHashCode
{
get { return _localNameHash; }
}
/// <summary>
/// Link together InfoAtoms that hash to the same hashtable bucket (should only be used by XPathNodeInfoTable)
/// </summary>
public XPathNodeInfoAtom Next
{
get { return _next; }
set { _next = value; }
}
/// <summary>
/// Return this information atom's hash code, previously computed for performance.
/// </summary>
public override int GetHashCode()
{
if (_hashCode == 0)
{
int hashCode;
// Start with local name
hashCode = _localNameHash;
// Add page indexes
unchecked
{
if (_pageSibling != null)
hashCode += (hashCode << 7) ^ _pageSibling[0].PageInfo.PageNumber;
if (_pageParent != null)
hashCode += (hashCode << 7) ^ _pageParent[0].PageInfo.PageNumber;
if (_pageSimilar != null)
hashCode += (hashCode << 7) ^ _pageSimilar[0].PageInfo.PageNumber;
}
// Save hashcode. Don't save 0, so that it won't ever be recomputed.
_hashCode = ((hashCode == 0) ? 1 : hashCode);
}
return _hashCode;
}
/// <summary>
/// Return true if this InfoAtom has the same values as another InfoAtom.
/// </summary>
public override bool Equals(object other)
{
return Equals(other as XPathNodeInfoAtom);
}
public bool Equals(XPathNodeInfoAtom other)
{
Debug.Assert(other != null);
Debug.Assert((object)_doc == (object)other._doc);
Debug.Assert(_pageInfo == null);
// Assume that name parts are atomized
if (this.GetHashCode() == other.GetHashCode())
{
if ((object)_localName == (object)other._localName &&
(object)_pageSibling == (object)other._pageSibling &&
(object)_namespaceUri == (object)other._namespaceUri &&
(object)_pageParent == (object)other._pageParent &&
(object)_pageSimilar == (object)other._pageSimilar &&
(object)_prefix == (object)other._prefix &&
(object)_baseUri == (object)other._baseUri &&
_lineNumBase == other._lineNumBase &&
_linePosBase == other._linePosBase)
{
return true;
}
}
return false;
}
/// <summary>
/// Return InfoAtom formatted as a string:
/// hash=xxx, {http://my.com}foo:bar, parent=1, sibling=1, lineNum=0, linePos=0
/// </summary>
public override string ToString()
{
StringBuilder bldr = new StringBuilder();
bldr.Append("hash=");
bldr.Append(GetHashCode());
bldr.Append(", ");
if (_localName.Length != 0)
{
bldr.Append('{');
bldr.Append(_namespaceUri);
bldr.Append('}');
if (_prefix.Length != 0)
{
bldr.Append(_prefix);
bldr.Append(':');
}
bldr.Append(_localName);
bldr.Append(", ");
}
if (_pageParent != null)
{
bldr.Append("parent=");
bldr.Append(_pageParent[0].PageInfo.PageNumber);
bldr.Append(", ");
}
if (_pageSibling != null)
{
bldr.Append("sibling=");
bldr.Append(_pageSibling[0].PageInfo.PageNumber);
bldr.Append(", ");
}
if (_pageSimilar != null)
{
bldr.Append("similar=");
bldr.Append(_pageSimilar[0].PageInfo.PageNumber);
bldr.Append(", ");
}
bldr.Append("lineNum=");
bldr.Append(_lineNumBase);
bldr.Append(", ");
bldr.Append("linePos=");
bldr.Append(_linePosBase);
return bldr.ToString();
}
}
/// <summary>
/// An atomization table for XPathNodeInfoAtom.
/// </summary>
internal sealed class XPathNodeInfoTable
{
private XPathNodeInfoAtom[] _hashTable;
private int _sizeTable;
private XPathNodeInfoAtom _infoCached;
#if DEBUG
private const int DefaultTableSize = 2;
#else
private const int DefaultTableSize = 32;
#endif
/// <summary>
/// Constructor.
/// </summary>
public XPathNodeInfoTable()
{
_hashTable = new XPathNodeInfoAtom[DefaultTableSize];
_sizeTable = 0;
}
/// <summary>
/// Create a new XNodeInfoAtom and ensure it is atomized in the table.
/// </summary>
public XPathNodeInfoAtom Create(string localName, string namespaceUri, string prefix, string baseUri,
XPathNode[] pageParent, XPathNode[] pageSibling, XPathNode[] pageSimilar,
XPathDocument doc, int lineNumBase, int linePosBase)
{
XPathNodeInfoAtom info;
// If this.infoCached already exists, then reuse it; else create new InfoAtom
if (_infoCached == null)
{
info = new XPathNodeInfoAtom(localName, namespaceUri, prefix, baseUri,
pageParent, pageSibling, pageSimilar,
doc, lineNumBase, linePosBase);
}
else
{
info = _infoCached;
_infoCached = info.Next;
info.Init(localName, namespaceUri, prefix, baseUri,
pageParent, pageSibling, pageSimilar,
doc, lineNumBase, linePosBase);
}
return Atomize(info);
}
/// <summary>
/// Add a shared information item to the atomization table. If a matching item already exists, then that
/// instance is returned. Otherwise, a new item is created. Thus, if itemX and itemY have both been added
/// to the same InfoTable:
/// 1. itemX.Equals(itemY) != true
/// 2. (object) itemX != (object) itemY
/// </summary>
private XPathNodeInfoAtom Atomize(XPathNodeInfoAtom info)
{
XPathNodeInfoAtom infoNew, infoNext;
// Search for existing XNodeInfoAtom in the table
infoNew = _hashTable[info.GetHashCode() & (_hashTable.Length - 1)];
while (infoNew != null)
{
if (info.Equals(infoNew))
{
// Found existing atom, so return that. Reuse "info".
info.Next = _infoCached;
_infoCached = info;
return infoNew;
}
infoNew = infoNew.Next;
}
// Expand table and rehash if necessary
if (_sizeTable >= _hashTable.Length)
{
XPathNodeInfoAtom[] oldTable = _hashTable;
_hashTable = new XPathNodeInfoAtom[oldTable.Length * 2];
for (int i = 0; i < oldTable.Length; i++)
{
infoNew = oldTable[i];
while (infoNew != null)
{
infoNext = infoNew.Next;
AddInfo(infoNew);
infoNew = infoNext;
}
}
}
// Can't find an existing XNodeInfoAtom, so use the one that was passed in
AddInfo(info);
return info;
}
/// <summary>
/// Add a previously constructed InfoAtom to the table. If a collision occurs, then insert "info"
/// as the head of a linked list.
/// </summary>
private void AddInfo(XPathNodeInfoAtom info)
{
int idx = info.GetHashCode() & (_hashTable.Length - 1);
info.Next = _hashTable[idx];
_hashTable[idx] = info;
_sizeTable++;
}
/// <summary>
/// Return InfoAtomTable formatted as a string.
/// </summary>
public override string ToString()
{
StringBuilder bldr = new StringBuilder();
XPathNodeInfoAtom infoAtom;
for (int i = 0; i < _hashTable.Length; i++)
{
bldr.AppendFormat("{0,4}: ", i);
infoAtom = _hashTable[i];
while (infoAtom != null)
{
if ((object)infoAtom != (object)_hashTable[i])
bldr.Append("\n ");
bldr.Append(infoAtom);
infoAtom = infoAtom.Next;
}
bldr.Append('\n');
}
return bldr.ToString();
}
}
}
| |
// KlakSpout - Spout video frame sharing plugin for Unity
// https://github.com/keijiro/KlakSpout
using UnityEngine;
namespace Klak.Spout
{
[ExecuteInEditMode]
[AddComponentMenu("Klak/Spout/Spout Receiver")]
public sealed class SpoutReceiver : MonoBehaviour
{
#region Source settings
[SerializeField] string _sourceName;
public string sourceName {
get { return _sourceName; }
set {
if (_sourceName == value) return;
_sourceName = value;
RequestReconnect();
}
}
#endregion
#region Target settings
[SerializeField] RenderTexture _targetTexture;
public RenderTexture targetTexture {
get { return _targetTexture; }
set { _targetTexture = value; }
}
[SerializeField] Renderer _targetRenderer;
public Renderer targetRenderer {
get { return _targetRenderer; }
set { _targetRenderer = value; }
}
[SerializeField] string _targetMaterialProperty = null;
public string targetMaterialProperty {
get { return _targetMaterialProperty; }
set { _targetMaterialProperty = value; }
}
#endregion
#region Runtime properties
RenderTexture _receivedTexture;
public Texture receivedTexture {
get { return _targetTexture != null ? _targetTexture : _receivedTexture; }
}
#endregion
#region Private members
System.IntPtr _plugin;
Texture2D _sharedTexture;
Material _blitMaterial;
MaterialPropertyBlock _propertyBlock;
#endregion
#region Internal members
internal void RequestReconnect()
{
OnDisable();
}
#endregion
#region MonoBehaviour implementation
void OnDisable()
{
if (_plugin != System.IntPtr.Zero)
{
Util.IssuePluginEvent(PluginEntry.Event.Dispose, _plugin);
_plugin = System.IntPtr.Zero;
}
Util.Destroy(_sharedTexture);
}
void OnDestroy()
{
Util.Destroy(_blitMaterial);
Util.Destroy(_receivedTexture);
}
void Update()
{
// Release the plugin instance when the previously established
// connection is now invalid.
if (_plugin != System.IntPtr.Zero && !PluginEntry.CheckValid(_plugin))
{
Util.IssuePluginEvent(PluginEntry.Event.Dispose, _plugin);
_plugin = System.IntPtr.Zero;
}
// Plugin lazy initialization
if (_plugin == System.IntPtr.Zero)
{
_plugin = PluginEntry.CreateReceiver(_sourceName);
if (_plugin == System.IntPtr.Zero) return; // Spout may not be ready.
}
Util.IssuePluginEvent(PluginEntry.Event.Update, _plugin);
// Texture information retrieval
var ptr = PluginEntry.GetTexturePointer(_plugin);
var width = PluginEntry.GetTextureWidth(_plugin);
var height = PluginEntry.GetTextureHeight(_plugin);
// Resource validity check
if (_sharedTexture != null)
{
if (ptr != _sharedTexture.GetNativeTexturePtr() ||
width != _sharedTexture.width ||
height != _sharedTexture.height)
{
// Not match: Destroy to get refreshed.
Util.Destroy(_sharedTexture);
}
}
// Shared texture lazy (re)initialization
if (_sharedTexture == null && ptr != System.IntPtr.Zero)
{
_sharedTexture = Texture2D.CreateExternalTexture(
width, height, TextureFormat.ARGB32, false, false, ptr
);
_sharedTexture.hideFlags = HideFlags.DontSave;
// Destroy the previously allocated receiver texture to
// refresh specifications.
if (_receivedTexture == null) Util.Destroy(_receivedTexture);
}
// Texture format conversion with the blit shader
if (_sharedTexture != null)
{
// Blit shader lazy initialization
if (_blitMaterial == null)
{
_blitMaterial = new Material(Shader.Find("Hidden/Spout/Blit"));
_blitMaterial.hideFlags = HideFlags.DontSave;
}
if (_targetTexture != null)
{
// Blit the shared texture to the target texture.
Graphics.Blit(_sharedTexture, _targetTexture, _blitMaterial, 1);
}
else
{
// Receiver texture lazy initialization
if (_receivedTexture == null)
{
_receivedTexture = new RenderTexture
(_sharedTexture.width, _sharedTexture.height, 0);
_receivedTexture.hideFlags = HideFlags.DontSave;
}
// Blit the shared texture to the receiver texture.
Graphics.Blit(_sharedTexture, _receivedTexture, _blitMaterial, 1);
}
}
// Renderer override
if (_targetRenderer != null && receivedTexture != null)
{
// Material property block lazy initialization
if (_propertyBlock == null)
_propertyBlock = new MaterialPropertyBlock();
// Read-modify-write
_targetRenderer.GetPropertyBlock(_propertyBlock);
_propertyBlock.SetTexture(_targetMaterialProperty, receivedTexture);
_targetRenderer.SetPropertyBlock(_propertyBlock);
}
}
#if UNITY_EDITOR
// Invoke update on repaint in edit mode. This is needed to update the
// shared texture without getting the object marked dirty.
void OnRenderObject()
{
if (Application.isPlaying) return;
// Graphic.Blit used in Update will change the current active RT,
// so let us back it up and restore after Update.
var activeRT = RenderTexture.active;
Update();
RenderTexture.active = activeRT;
}
#endif
#endregion
}
}
| |
using System;
using System.Collections.Generic;
namespace Cocos2D
{
public enum CCTableViewVerticalFillOrder
{
FillTopDown,
FillBottomUp
};
///**
// * Sole purpose of this delegate is to single touch event in this version.
// */
public interface ICCTableViewDelegate : ICCScrollViewDelegate
{
/**
* Delegate to respond touch event
*
* @param table table contains the given cell
* @param cell cell that is touched
*/
void TableCellTouched(CCTableView table, CCTableViewCell cell);
/**
* Delegate to respond a table cell press event.
*
* @param table table contains the given cell
* @param cell cell that is pressed
*/
void TableCellHighlight(CCTableView table, CCTableViewCell cell);
/**
* Delegate to respond a table cell release event
*
* @param table table contains the given cell
* @param cell cell that is pressed
*/
void TableCellUnhighlight(CCTableView table, CCTableViewCell cell);
/**
* Delegate called when the cell is about to be recycled. Immediately
* after this call the cell will be removed from the scene graph and
* recycled.
*
* @param table table contains the given cell
* @param cell cell that is pressed
*/
void TableCellWillRecycle(CCTableView table, CCTableViewCell cell);
}
/**
* Data source that governs table backend data.
*/
public interface ICCTableViewDataSource
{
/**
* cell height for a given table.
*
* @param table table to hold the instances of Class
* @return cell size
*/
CCSize TableCellSizeForIndex(CCTableView table, int idx);
/**
* a cell instance at a given index
*
* @param idx index to search for a cell
* @return cell found at idx
*/
CCTableViewCell TableCellAtIndex(CCTableView table, int idx);
/**
* Returns number of cells in a given table view.
*
* @return number of cells
*/
int NumberOfCellsInTableView(CCTableView table);
};
/**
* UITableView counterpart for cocos2d for iphone.
*
* this is a very basic, minimal implementation to bring UITableView-like component into cocos2d world.
*
*/
public class CCTableView : CCScrollView, ICCScrollViewDelegate
{
protected CCTableViewCell _touchedCell;
protected CCTableViewVerticalFillOrder _vordering;
protected List<int> _indices;
protected List<float> _cellsPositions;
protected CCArrayForObjectSorting _cellsUsed;
protected CCArrayForObjectSorting _cellsFreed;
protected ICCTableViewDataSource _dataSource;
protected ICCTableViewDelegate _tableViewDelegate;
protected CCScrollViewDirection _oldDirection;
/**
* data source
*/
public ICCTableViewDataSource DataSource
{
get { return _dataSource; }
set { _dataSource = value; }
}
/**
* delegate
*/
public new ICCTableViewDelegate Delegate
{
get { return _tableViewDelegate; }
set { _tableViewDelegate = value; }
}
public CCTableView()
{
_oldDirection = CCScrollViewDirection.None;
}
/**
* An intialized table view object
*
* @param dataSource data source
* @param size view size
* @return table view
*/
public CCTableView(ICCTableViewDataSource dataSource, CCSize size)
: this(dataSource, size, null)
{ }
/**
* An initialized table view object
*
* @param dataSource data source;
* @param size view size
* @param container parent object for cells
* @return table view
*/
public CCTableView(ICCTableViewDataSource dataSource, CCSize size, CCNode container)
{
InitWithViewSize(size, container);
DataSource = dataSource;
_updateCellPositions();
_updateContentSize();
}
public new bool InitWithViewSize(CCSize size, CCNode container)
{
if (base.InitWithViewSize(size, container))
{
_cellsPositions = new List<float>();
_cellsUsed = new CCArrayForObjectSorting();
_cellsFreed = new CCArrayForObjectSorting();
_indices = new List<int>();
_vordering = CCTableViewVerticalFillOrder.FillBottomUp;
Direction = CCScrollViewDirection.Vertical;
base.Delegate = this;
return true;
}
return false;
}
/**
* determines how cell is ordered and filled in the view.
*/
public CCTableViewVerticalFillOrder VerticalFillOrder
{
get { return _vordering; }
set
{
if (_vordering != value)
{
_vordering = value;
if (_cellsUsed.Count > 0)
{
ReloadData();
}
}
}
}
/**
* reloads data from data source. the view will be refreshed.
*/
public void ReloadData()
{
_oldDirection = CCScrollViewDirection.None;
foreach (CCTableViewCell cell in _cellsUsed)
{
if (_tableViewDelegate != null)
{
_tableViewDelegate.TableCellWillRecycle(this, cell);
}
_cellsFreed.Add(cell);
cell.Reset();
if (cell.Parent == Container)
{
Container.RemoveChild(cell, true);
}
}
_indices.Clear();
_cellsUsed = new CCArrayForObjectSorting();
_updateCellPositions();
_updateContentSize();
if (_dataSource.NumberOfCellsInTableView(this) > 0)
{
ScrollViewDidScroll(this);
}
}
/**
* Returns an existing cell at a given index. Returns nil if a cell is nonexistent at the moment of query.
*
* @param idx index
* @return a cell at a given index
*/
public CCTableViewCell CellAtIndex(int idx)
{
CCTableViewCell found = null;
if (_indices.Contains(idx))
{
found = (CCTableViewCell)_cellsUsed.ObjectWithObjectID(idx);
}
return found;
}
/**
* Updates the content of the cell at a given index.
*
* @param idx index to find a cell
*/
public void UpdateCellAtIndex(int idx)
{
if (idx == CCArrayForObjectSorting.CC_INVALID_INDEX)
{
return;
}
var uCountOfItems = _dataSource.NumberOfCellsInTableView(this);
if (uCountOfItems == 0 || idx > uCountOfItems - 1)
{
return;
}
var cell = CellAtIndex(idx);
if (cell != null)
{
_moveCellOutOfSight(cell);
}
cell = _dataSource.TableCellAtIndex(this, idx);
_setIndexForCell(idx, cell);
_addCellIfNecessary(cell);
}
/**
* Removes a cell at a given index
*
* @param idx index to find a cell
*/
public void RemoveCellAtIndex(int idx)
{
if (idx == CCArrayForObjectSorting.CC_INVALID_INDEX)
{
return;
}
var uCountOfItems = _dataSource.NumberOfCellsInTableView(this);
if (uCountOfItems == 0 || idx > uCountOfItems - 1)
{
return;
}
int newIdx;
CCTableViewCell cell = CellAtIndex(idx);
if (cell == null)
{
return;
}
newIdx = _cellsUsed.IndexOfSortedObject(cell);
//remove first
_moveCellOutOfSight(cell);
_indices.Remove(idx);
// [_indices shiftIndexesStartingAtIndex:idx+1 by:-1];
for (int i = _cellsUsed.Count - 1; i > newIdx; i--)
{
cell = (CCTableViewCell)_cellsUsed[i];
_setIndexForCell(cell.Index - 1, cell);
}
}
/**
* Dequeues a free cell if available. nil if not.
*
* @return free cell
*/
public CCTableViewCell DequeueCell()
{
CCTableViewCell cell;
if (_cellsFreed.Count == 0)
{
cell = null;
}
else
{
cell = (CCTableViewCell)_cellsFreed[0];
_cellsFreed.RemoveAt(0);
}
return cell;
}
protected void _addCellIfNecessary(CCTableViewCell cell)
{
if (cell.Parent != Container)
{
Container.AddChild(cell);
}
_cellsUsed.InsertSortedObject(cell);
_indices.Add(cell.Index);
}
protected void _updateContentSize()
{
CCSize size = CCSize.Zero;
int cellsCount = _dataSource.NumberOfCellsInTableView(this);
if (cellsCount > 0)
{
float maxPosition = _cellsPositions[cellsCount];
switch (Direction)
{
case CCScrollViewDirection.Horizontal:
size = new CCSize(maxPosition, _viewSize.Height);
break;
default:
size = new CCSize(_viewSize.Width, maxPosition);
break;
}
}
ContentSize = size;
if (_oldDirection != _direction)
{
if (_direction == CCScrollViewDirection.Horizontal)
{
SetContentOffset(CCPoint.Zero);
}
else
{
SetContentOffset(new CCPoint(0, MinContainerOffset.Y));
}
_oldDirection = _direction;
}
}
protected CCPoint _offsetFromIndex(int index)
{
CCPoint offset = __offsetFromIndex(index);
CCSize cellSize = _dataSource.TableCellSizeForIndex(this, index);
if (_vordering == CCTableViewVerticalFillOrder.FillTopDown)
{
offset.Y = Container.ContentSize.Height - offset.Y - cellSize.Height;
}
return offset;
}
protected CCPoint __offsetFromIndex(int index)
{
CCPoint offset;
switch (Direction)
{
case CCScrollViewDirection.Horizontal:
offset = new CCPoint(_cellsPositions[index], 0.0f);
break;
default:
offset = new CCPoint(0.0f, _cellsPositions[index]);
break;
}
return offset;
}
protected int _indexFromOffset(CCPoint offset)
{
int index = 0;
int maxIdx = _dataSource.NumberOfCellsInTableView(this) - 1;
if (_vordering == CCTableViewVerticalFillOrder.FillTopDown)
{
offset.Y = Container.ContentSize.Height - offset.Y;
}
index = __indexFromOffset(offset);
if (index != -1)
{
index = Math.Max(0, index);
if (index > maxIdx)
{
index = CCArrayForObjectSorting.CC_INVALID_INDEX;
}
}
return index;
}
protected int __indexFromOffset(CCPoint offset)
{
int low = 0;
int high = _dataSource.NumberOfCellsInTableView(this) - 1;
float search;
switch (Direction)
{
case CCScrollViewDirection.Horizontal:
search = offset.X;
break;
default:
search = offset.Y;
break;
}
while (high >= low)
{
int index = low + (high - low) / 2;
float cellStart = _cellsPositions[index];
float cellEnd = _cellsPositions[index + 1];
if (search >= cellStart && search <= cellEnd)
{
return index;
}
else if (search < cellStart)
{
high = index - 1;
}
else
{
low = index + 1;
}
}
if (low <= 0)
{
return 0;
}
return -1;
}
protected void _moveCellOutOfSight(CCTableViewCell cell)
{
if (_tableViewDelegate != null)
{
_tableViewDelegate.TableCellWillRecycle(this, cell);
}
_cellsFreed.Add(cell);
_cellsUsed.RemoveSortedObject(cell);
_indices.Remove(cell.Index);
cell.Reset();
if (cell.Parent == Container)
{
Container.RemoveChild(cell, true);
}
}
protected void _setIndexForCell(int index, CCTableViewCell cell)
{
cell.AnchorPoint = CCPoint.Zero;
cell.Position = _offsetFromIndex(index);
cell.Index = index;
}
protected void _updateCellPositions()
{
int cellsCount = _dataSource.NumberOfCellsInTableView(this);
_cellsPositions.Clear();
if (cellsCount > 0)
{
float currentPos = 0;
CCSize cellSize;
for (int i=0; i < cellsCount; i++)
{
_cellsPositions.Add(currentPos);
cellSize = _dataSource.TableCellSizeForIndex(this, i);
switch (Direction)
{
case CCScrollViewDirection.Horizontal:
currentPos += cellSize.Width;
break;
default:
currentPos += cellSize.Height;
break;
}
}
_cellsPositions.Add(currentPos);//1 extra value allows us to get right/bottom of the last cell
}
}
#region CCScrollViewDelegate Members
public virtual void ScrollViewDidScroll(CCScrollView view)
{
var uCountOfItems = _dataSource.NumberOfCellsInTableView(this);
if (uCountOfItems == 0)
{
return;
}
if (_tableViewDelegate != null)
{
_tableViewDelegate.ScrollViewDidScroll(this);
}
int startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0;
CCPoint offset = GetContentOffset() * -1;
maxIdx = Math.Max(uCountOfItems - 1, 0);
if (_vordering == CCTableViewVerticalFillOrder.FillTopDown)
{
offset.Y = offset.Y + _viewSize.Height / Container.ScaleY;
}
startIdx = _indexFromOffset(offset);
if (startIdx == CCArrayForObjectSorting.CC_INVALID_INDEX)
{
startIdx = uCountOfItems - 1;
}
if (_vordering == CCTableViewVerticalFillOrder.FillTopDown)
{
offset.Y -= _viewSize.Height / Container.ScaleY;
}
else
{
offset.Y += _viewSize.Height / Container.ScaleY;
}
offset.X += _viewSize.Width / Container.ScaleX;
endIdx = _indexFromOffset(offset);
if (endIdx == CCArrayForObjectSorting.CC_INVALID_INDEX)
{
endIdx = uCountOfItems - 1;
}
#if DEBUG_ // For Testing.
int i = 0;
foreach (object pObj in _cellsUsed)
{
var pCell = (CCTableViewCell)pObj;
CCLog.Log("cells Used index {0}, value = {1}", i, pCell.getIdx());
i++;
}
CCLog.Log("---------------------------------------");
i = 0;
foreach(object pObj in _cellsFreed)
{
var pCell = (CCTableViewCell)pObj;
CCLog.Log("cells freed index {0}, value = {1}", i, pCell.getIdx());
i++;
}
CCLog.Log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
#endif
if (_cellsUsed.Count > 0)
{
var cell = (CCTableViewCell) _cellsUsed[0];
idx = cell.Index;
while (idx < startIdx)
{
_moveCellOutOfSight(cell);
if (_cellsUsed.Count > 0)
{
cell = (CCTableViewCell) _cellsUsed[0];
idx = cell.Index;
}
else
{
break;
}
}
}
if (_cellsUsed.Count > 0)
{
var cell = (CCTableViewCell) _cellsUsed[_cellsUsed.Count - 1];
idx = cell.Index;
while (idx <= maxIdx && idx > endIdx)
{
_moveCellOutOfSight(cell);
if (_cellsUsed.Count > 0)
{
cell = (CCTableViewCell) _cellsUsed[_cellsUsed.Count - 1];
idx = cell.Index;
}
else
{
break;
}
}
}
for (int i = startIdx; i <= endIdx; i++)
{
if (_indices.Contains(i))
{
continue;
}
UpdateCellAtIndex(i);
}
}
public virtual void ScrollViewDidZoom(CCScrollView view)
{
}
#endregion
public override void TouchEnded(CCTouch pTouch)
{
if (!Visible)
{
return;
}
if (_touchedCell != null)
{
CCRect bb = BoundingBox;
bb.Origin = Parent.ConvertToWorldSpace(bb.Origin);
if (bb.ContainsPoint(pTouch.Location) && _tableViewDelegate != null)
{
_tableViewDelegate.TableCellUnhighlight(this, _touchedCell);
_tableViewDelegate.TableCellTouched(this, _touchedCell);
}
_touchedCell = null;
}
base.TouchEnded(pTouch);
}
public override bool TouchBegan(CCTouch pTouch)
{
if (!Visible)
{
return false;
}
bool touchResult = base.TouchBegan(pTouch);
if (_touches.Count == 1)
{
var point = Container.ConvertTouchToNodeSpace(pTouch);
var index = _indexFromOffset(point);
if (index == CCArrayForObjectSorting.CC_INVALID_INDEX)
{
_touchedCell = null;
}
else
{
_touchedCell = CellAtIndex(index);
}
if (_touchedCell != null && _tableViewDelegate != null)
{
_tableViewDelegate.TableCellHighlight(this, _touchedCell);
}
}
else if (_touchedCell != null)
{
if (_tableViewDelegate != null)
{
_tableViewDelegate.TableCellUnhighlight(this, _touchedCell);
}
_touchedCell = null;
}
return touchResult;
}
public override void TouchMoved(CCTouch touch)
{
base.TouchMoved(touch);
if (_touchedCell != null && IsTouchMoved)
{
if (_tableViewDelegate != null)
{
_tableViewDelegate.TableCellUnhighlight(this, _touchedCell);
}
_touchedCell = null;
}
}
public override void TouchCancelled(CCTouch touch)
{
base.TouchCancelled(touch);
if (_touchedCell != null)
{
if (_tableViewDelegate != null)
{
_tableViewDelegate.TableCellUnhighlight(this, _touchedCell);
}
_touchedCell = null;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for OriginsOperations.
/// </summary>
public static partial class OriginsOperationsExtensions
{
/// <summary>
/// Lists the existing CDN origins within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
public static Microsoft.Rest.Azure.IPage<Origin> ListByEndpoint(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IOriginsOperations)s).ListByEndpointAsync(resourceGroupName, profileName, endpointName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the existing CDN origins within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Origin>> ListByEndpointAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListByEndpointWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
public static Origin Get(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IOriginsOperations)s).GetAsync(resourceGroupName, profileName, endpointName, originName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Origin> GetAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, originName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
/// <param name='originUpdateProperties'>
/// Origin properties
/// </param>
public static Origin Update(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IOriginsOperations)s).UpdateAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
/// <param name='originUpdateProperties'>
/// Origin properties
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Origin> UpdateAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
/// <param name='originUpdateProperties'>
/// Origin properties
/// </param>
public static Origin BeginUpdate(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IOriginsOperations)s).BeginUpdateAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing CDN origin within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='originName'>
/// Name of the origin which is unique within the endpoint.
/// </param>
/// <param name='originUpdateProperties'>
/// Origin properties
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Origin> BeginUpdateAsync(this IOriginsOperations operations, string resourceGroupName, string profileName, string endpointName, string originName, OriginUpdateParameters originUpdateProperties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, originName, originUpdateProperties, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the existing CDN origins within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<Origin> ListByEndpointNext(this IOriginsOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IOriginsOperations)s).ListByEndpointNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the existing CDN origins within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<Origin>> ListByEndpointNextAsync(this IOriginsOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListByEndpointNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using static System.Runtime.Intrinsics.X86.Sse;
using static System.Runtime.Intrinsics.X86.Sse2;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void InsertSingle128()
{
var test = new InsertVector128Test__InsertSingle128();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class InsertVector128Test__InsertSingle128
{
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(InsertVector128Test__InsertSingle128 testClass)
{
var result = Sse41.Insert(_fld1, _fld2, 128);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static InsertVector128Test__InsertSingle128()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public InsertVector128Test__InsertSingle128()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.Insert(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
128
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.Insert(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
LoadVector128((Single*)(_dataTable.inArray2Ptr)),
128
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.Insert(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
128
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
(byte)128
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
LoadVector128((Single*)(_dataTable.inArray2Ptr)),
(byte)128
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
(byte)128
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Insert(
_clsVar1,
_clsVar2,
128
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse41.Insert(left, right, 128);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.Insert(left, right, 128);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.Insert(left, right, 128);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertVector128Test__InsertSingle128();
var result = Sse41.Insert(test._fld1, test._fld2, 128);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Insert(_fld1, _fld2, 128);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Insert(test._fld1, test._fld2, 128);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(right[2]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Single>(Vector128<Single>, Vector128<Single>.128): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class AverageTests
{
//
// Average
//
// Get a set of ranges from 0 to each count, with an extra parameter containing the expected average.
public static IEnumerable<object[]> AverageData(int[] counts)
{
Func<int, double> average = x => (x - 1) / 2.0;
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), average)) yield return results;
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Int(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(average, query.Average());
Assert.Equal((double?)average, query.Select(x => (int?)x).Average());
Assert.Equal(-average, query.Average(x => -x));
Assert.Equal(-(double?)average, query.Average(x => -(int?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(AverageData), (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }))]
public static void Average_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
Average_Int(labeled, count, average);
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (int?)x : null).Average());
Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(int?)x : null));
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (int?)null).Average());
Assert.Null(query.Average(x => (int?)null));
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Long(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(average, query.Select(x => (long)x).Average());
Assert.Equal((double?)average, query.Select(x => (long?)x).Average());
Assert.Equal(-average, query.Average(x => -(long)x));
Assert.Equal(-(double?)average, query.Average(x => -(long?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(AverageData), (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }))]
public static void Average_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
Average_Long(labeled, count, average);
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Average_Long_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? 1 : long.MaxValue).Average());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? (long?)1 : long.MaxValue).Average());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Average(x => x == 0 ? -1 : long.MinValue));
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Average(x => x == 0 ? (long?)-1 : long.MinValue));
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (long?)x : null).Average());
Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(long?)x : null));
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (long?)null).Average());
Assert.Null(query.Average(x => (long?)null));
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Float(Labeled<ParallelQuery<int>> labeled, int count, float average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(average, query.Select(x => (float)x).Average());
Assert.Equal((float?)average, query.Select(x => (float?)x).Average());
Assert.Equal(-average, query.Average(x => -(float)x));
Assert.Equal(-(float?)average, query.Average(x => -(float?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(AverageData), (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }))]
public static void Average_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float average)
{
Average_Float(labeled, count, average);
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal((float?)Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (float?)x : null).Average());
Assert.Equal((float?)Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(float?)x : null));
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (float?)null).Average());
Assert.Null(query.Average(x => (float?)null));
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Double(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(average, query.Select(x => (double)x).Average());
Assert.Equal((double?)average, query.Select(x => (double?)x).Average());
Assert.Equal(-average, query.Average(x => -(double)x));
Assert.Equal(-(double?)average, query.Average(x => -(double?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(AverageData), (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }))]
public static void Average_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
Average_Double(labeled, count, average);
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (double?)x : null).Average());
Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(double?)x : null));
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (double?)null).Average());
Assert.Null(query.Average(x => (double?)null));
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(average, query.Select(x => (decimal)x).Average());
Assert.Equal((decimal?)average, query.Select(x => (decimal?)x).Average());
Assert.Equal(-average, query.Average(x => -(decimal)x));
Assert.Equal(-(decimal?)average, query.Average(x => -(decimal?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(AverageData), (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }))]
public static void Average_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal average)
{
Average_Decimal(labeled, count, average);
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (decimal?)x : null).Average());
Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(decimal?)x : null));
}
[Theory]
[MemberData(nameof(AverageData), (object)(new int[] { 1, 2, 16 }))]
public static void Average_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (decimal?)null).Average());
Assert.Null(query.Average(x => (decimal?)null));
}
[Fact]
public static void Average_InvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<long>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<long>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<float>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<float>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<double>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<double>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<decimal>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<decimal>().Average(x => x));
// Nullables return null when empty
Assert.Null(ParallelEnumerable.Empty<int?>().Average());
Assert.Null(ParallelEnumerable.Empty<int?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<long?>().Average());
Assert.Null(ParallelEnumerable.Empty<long?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<float?>().Average());
Assert.Null(ParallelEnumerable.Empty<float?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<double?>().Average());
Assert.Null(ParallelEnumerable.Empty<double?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<decimal?>().Average());
Assert.Null(ParallelEnumerable.Empty<decimal?>().Average(x => x));
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))]
public static void Average_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (int?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (long)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (long?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (float)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (float?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (double)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (double?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (decimal)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (decimal?)x));
}
[Theory]
[MemberData(nameof(Sources.Ranges), (object)(new int[] { 1 }), MemberType = typeof(UnorderedSources))]
public static void Average_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, int>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, int?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, long>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, long?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, float>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, float?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, double>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, double?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, decimal>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, decimal?>)(x => { throw new DeliberateTestException(); })));
}
[Fact]
public static void Average_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Average((Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Average((Func<int?, int?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Average((Func<long, long>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Average((Func<long?, long?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Average((Func<float, float>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Average((Func<float?, float?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Average((Func<double, double>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Average((Func<double?, double?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Average((Func<decimal, decimal>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Average((Func<decimal?, decimal?>)null));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Search
{
/*
* 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
/// <summary>
/// A <see cref="Rescorer"/> that uses a provided <see cref="Query"/> to assign
/// scores to the first-pass hits.
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class QueryRescorer : Rescorer
{
private readonly Query query;
/// <summary>
/// Sole constructor, passing the 2nd pass query to
/// assign scores to the 1st pass hits.
/// </summary>
public QueryRescorer(Query query)
{
this.query = query;
}
/// <summary>
/// Implement this in a subclass to combine the first pass and
/// second pass scores. If <paramref name="secondPassMatches"/> is <c>false</c> then
/// the second pass query failed to match a hit from the
/// first pass query, and you should ignore the
/// <paramref name="secondPassScore"/>.
/// </summary>
protected abstract float Combine(float firstPassScore, bool secondPassMatches, float secondPassScore);
public override TopDocs Rescore(IndexSearcher searcher, TopDocs firstPassTopDocs, int topN)
{
ScoreDoc[] hits = (ScoreDoc[])firstPassTopDocs.ScoreDocs.Clone();
Array.Sort(hits, new ComparerAnonymousInnerClassHelper(this));
IList<AtomicReaderContext> leaves = searcher.IndexReader.Leaves;
Weight weight = searcher.CreateNormalizedWeight(query);
// Now merge sort docIDs from hits, with reader's leaves:
int hitUpto = 0;
int readerUpto = -1;
int endDoc = 0;
int docBase = 0;
Scorer scorer = null;
while (hitUpto < hits.Length)
{
ScoreDoc hit = hits[hitUpto];
int docID = hit.Doc;
AtomicReaderContext readerContext = null;
while (docID >= endDoc)
{
readerUpto++;
readerContext = leaves[readerUpto];
endDoc = readerContext.DocBase + readerContext.Reader.MaxDoc;
}
if (readerContext != null)
{
// We advanced to another segment:
docBase = readerContext.DocBase;
scorer = weight.GetScorer(readerContext, null);
}
int targetDoc = docID - docBase;
int actualDoc = scorer.DocID;
if (actualDoc < targetDoc)
{
actualDoc = scorer.Advance(targetDoc);
}
if (actualDoc == targetDoc)
{
// Query did match this doc:
hit.Score = Combine(hit.Score, true, scorer.GetScore());
}
else
{
// Query did not match this doc:
Debug.Assert(actualDoc > targetDoc);
hit.Score = Combine(hit.Score, false, 0.0f);
}
hitUpto++;
}
// TODO: we should do a partial sort (of only topN)
// instead, but typically the number of hits is
// smallish:
Array.Sort(hits, new ComparerAnonymousInnerClassHelper2(this));
if (topN < hits.Length)
{
ScoreDoc[] subset = new ScoreDoc[topN];
Array.Copy(hits, 0, subset, 0, topN);
hits = subset;
}
return new TopDocs(firstPassTopDocs.TotalHits, hits, hits[0].Score);
}
private class ComparerAnonymousInnerClassHelper : IComparer<ScoreDoc>
{
private readonly QueryRescorer outerInstance;
public ComparerAnonymousInnerClassHelper(QueryRescorer outerInstance)
{
this.outerInstance = outerInstance;
}
public virtual int Compare(ScoreDoc a, ScoreDoc b)
{
return a.Doc - b.Doc;
}
}
private class ComparerAnonymousInnerClassHelper2 : IComparer<ScoreDoc>
{
private readonly QueryRescorer outerInstance;
public ComparerAnonymousInnerClassHelper2(QueryRescorer outerInstance)
{
this.outerInstance = outerInstance;
}
public virtual int Compare(ScoreDoc a, ScoreDoc b)
{
// Sort by score descending, then docID ascending:
if (a.Score > b.Score)
{
return -1;
}
else if (a.Score < b.Score)
{
return 1;
}
else
{
// this subtraction can't overflow int
// because docIDs are >= 0:
return a.Doc - b.Doc;
}
}
}
public override Explanation Explain(IndexSearcher searcher, Explanation firstPassExplanation, int docID)
{
Explanation secondPassExplanation = searcher.Explain(query, docID);
float? secondPassScore = secondPassExplanation.IsMatch ? (float?)secondPassExplanation.Value : null;
float score;
if (secondPassScore == null)
{
score = Combine(firstPassExplanation.Value, false, 0.0f);
}
else
{
score = Combine(firstPassExplanation.Value, true, (float)secondPassScore);
}
Explanation result = new Explanation(score, "combined first and second pass score using " + this.GetType());
Explanation first = new Explanation(firstPassExplanation.Value, "first pass score");
first.AddDetail(firstPassExplanation);
result.AddDetail(first);
Explanation second;
if (secondPassScore == null)
{
second = new Explanation(0.0f, "no second pass score");
}
else
{
second = new Explanation((float)secondPassScore, "second pass score");
}
second.AddDetail(secondPassExplanation);
result.AddDetail(second);
return result;
}
/// <summary>
/// Sugar API, calling <see cref="QueryRescorer.Rescore(IndexSearcher, TopDocs, int)"/> using a simple linear
/// combination of firstPassScore + <paramref name="weight"/> * secondPassScore
/// </summary>
public static TopDocs Rescore(IndexSearcher searcher, TopDocs topDocs, Query query, double weight, int topN)
{
return new QueryRescorerAnonymousInnerClassHelper(query, weight).Rescore(searcher, topDocs, topN);
}
private class QueryRescorerAnonymousInnerClassHelper : QueryRescorer
{
private double weight;
public QueryRescorerAnonymousInnerClassHelper(Lucene.Net.Search.Query query, double weight)
: base(query)
{
this.weight = weight;
}
protected override float Combine(float firstPassScore, bool secondPassMatches, float secondPassScore)
{
float score = firstPassScore;
if (secondPassMatches)
{
score += (float)(weight * secondPassScore);
}
return score;
}
}
}
}
| |
/*
* 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.IO;
using System.Linq;
using QuantConnect.Brokerages;
using QuantConnect.Configuration;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Packets;
using QuantConnect.Statistics;
using QuantConnect.Util;
using QuantConnect.Lean.Engine.Alphas;
namespace QuantConnect.Lean.Engine.Results
{
/// <summary>
/// Backtesting result handler passes messages back from the Lean to the User.
/// </summary>
public class BacktestingResultHandler : BaseResultsHandler, IResultHandler
{
private const double Samples = 4000;
private const double MinimumSamplePeriod = 4;
private BacktestNodePacket _job;
private int _jobDays;
private DateTime _nextUpdate;
private DateTime _nextS3Update;
private string _errorMessage;
private int _daysProcessed;
private int _daysProcessedFrontier;
private readonly HashSet<string> _chartSeriesExceededDataPoints;
/// <summary>
/// Calculates the capacity of a strategy per Symbol in real-time
/// </summary>
private CapacityEstimate _capacityEstimate;
//Processing Time:
private DateTime _nextSample;
private string _algorithmId;
private int _projectId;
/// <summary>
/// A dictionary containing summary statistics
/// </summary>
public Dictionary<string, string> FinalStatistics { get; private set; }
/// <summary>
/// Creates a new instance
/// </summary>
public BacktestingResultHandler()
{
ResamplePeriod = TimeSpan.FromMinutes(4);
NotificationPeriod = TimeSpan.FromSeconds(2);
_chartSeriesExceededDataPoints = new HashSet<string>();
// Delay uploading first packet
_nextS3Update = StartTime.AddSeconds(30);
//Default charts:
Charts.AddOrUpdate("Strategy Equity", new Chart("Strategy Equity"));
Charts["Strategy Equity"].Series.Add("Equity", new Series("Equity", SeriesType.Candle, 0, "$"));
Charts["Strategy Equity"].Series.Add("Daily Performance", new Series("Daily Performance", SeriesType.Bar, 1, "%"));
}
/// <summary>
/// Initialize the result handler with this result packet.
/// </summary>
/// <param name="job">Algorithm job packet for this result handler</param>
/// <param name="messagingHandler">The handler responsible for communicating messages to listeners</param>
/// <param name="api">The api instance used for handling logs</param>
/// <param name="transactionHandler">The transaction handler used to get the algorithms <see cref="Order"/> information</param>
public override void Initialize(AlgorithmNodePacket job, IMessagingHandler messagingHandler, IApi api, ITransactionHandler transactionHandler)
{
_algorithmId = job.AlgorithmId;
_projectId = job.ProjectId;
_job = (BacktestNodePacket)job;
if (_job == null) throw new Exception("BacktestingResultHandler.Constructor(): Submitted Job type invalid.");
base.Initialize(job, messagingHandler, api, transactionHandler);
}
/// <summary>
/// The main processing method steps through the messaging queue and processes the messages one by one.
/// </summary>
protected override void Run()
{
try
{
while (!(ExitTriggered && Messages.Count == 0))
{
//While there's no work to do, go back to the algorithm:
if (Messages.Count == 0)
{
ExitEvent.WaitOne(50);
}
else
{
//1. Process Simple Messages in Queue
Packet packet;
if (Messages.TryDequeue(out packet))
{
MessagingHandler.Send(packet);
}
}
//2. Update the packet scanner:
Update();
} // While !End.
}
catch (Exception err)
{
// unexpected error, we need to close down shop
Algorithm.SetRuntimeError(err, "ResultHandler");
}
Log.Trace("BacktestingResultHandler.Run(): Ending Thread...");
} // End Run();
/// <summary>
/// Send a backtest update to the browser taking a latest snapshot of the charting data.
/// </summary>
private void Update()
{
try
{
//Sometimes don't run the update, if not ready or we're ending.
if (Algorithm?.Transactions == null || ExitTriggered)
{
return;
}
var utcNow = DateTime.UtcNow;
if (utcNow <= _nextUpdate || _daysProcessed < _daysProcessedFrontier) return;
var deltaOrders = GetDeltaOrders(LastDeltaOrderPosition, shouldStop: orderCount => orderCount >= 50);
// Deliberately skip to the end of order event collection to prevent overloading backtesting UX
LastDeltaOrderPosition = TransactionHandler.OrderEvents.Count();
//Reset loop variables:
try
{
_daysProcessedFrontier = _daysProcessed + 1;
_nextUpdate = utcNow.AddSeconds(3);
}
catch (Exception err)
{
Log.Error(err, "Can't update variables");
}
var deltaCharts = new Dictionary<string, Chart>();
var serverStatistics = GetServerStatistics(utcNow);
var performanceCharts = new Dictionary<string, Chart>();
// Process our charts updates
lock (ChartLock)
{
foreach (var kvp in Charts)
{
var chart = kvp.Value;
// Get a copy of this chart with updates only since last request
var updates = chart.GetUpdates();
if (!updates.IsEmpty())
{
deltaCharts.Add(chart.Name, updates);
}
// Update our algorithm performance charts
if (AlgorithmPerformanceCharts.Contains(kvp.Key))
{
performanceCharts[kvp.Key] = chart.Clone();
}
}
}
//Get the runtime statistics from the user algorithm:
var runtimeStatistics = new Dictionary<string, string>();
lock (RuntimeStatistics)
{
foreach (var pair in RuntimeStatistics)
{
runtimeStatistics.Add(pair.Key, pair.Value);
}
}
var summary = GenerateStatisticsResults(performanceCharts, estimatedStrategyCapacity: _capacityEstimate).Summary;
GetAlgorithmRuntimeStatistics(summary, runtimeStatistics, _capacityEstimate);
var progress = (decimal)_daysProcessed / _jobDays;
if (progress > 0.999m) progress = 0.999m;
//1. Cloud Upload -> Upload the whole packet to S3 Immediately:
if (utcNow > _nextS3Update)
{
// For intermediate backtesting results, we truncate the order list to include only the last 100 orders
// The final packet will contain the full list of orders.
const int maxOrders = 100;
var orderCount = TransactionHandler.Orders.Count;
var completeResult = new BacktestResult(new BacktestResultParameters(
Charts,
orderCount > maxOrders ? TransactionHandler.Orders.Skip(orderCount - maxOrders).ToDictionary() : TransactionHandler.Orders.ToDictionary(),
Algorithm.Transactions.TransactionRecord,
new Dictionary<string, string>(),
runtimeStatistics,
new Dictionary<string, AlgorithmPerformance>(),
// we store the last 100 order events, the final packet will contain the full list
TransactionHandler.OrderEvents.Reverse().Take(100).ToList()));
StoreResult(new BacktestResultPacket(_job, completeResult, Algorithm.EndDate, Algorithm.StartDate, progress));
_nextS3Update = DateTime.UtcNow.AddSeconds(30);
}
//2. Backtest Update -> Send the truncated packet to the backtester:
var splitPackets = SplitPackets(deltaCharts, deltaOrders, runtimeStatistics, progress, serverStatistics);
foreach (var backtestingPacket in splitPackets)
{
MessagingHandler.Send(backtestingPacket);
}
// let's re update this value after we finish just in case, so we don't re enter in the next loop
_nextUpdate = DateTime.UtcNow.Add(MainUpdateInterval);
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Run over all the data and break it into smaller packets to ensure they all arrive at the terminal
/// </summary>
public virtual IEnumerable<BacktestResultPacket> SplitPackets(Dictionary<string, Chart> deltaCharts, Dictionary<int, Order> deltaOrders, Dictionary<string, string> runtimeStatistics, decimal progress, Dictionary<string, string> serverStatistics)
{
// break the charts into groups
var splitPackets = new List<BacktestResultPacket>();
foreach (var chart in deltaCharts.Values)
{
splitPackets.Add(new BacktestResultPacket(_job, new BacktestResult
{
Charts = new Dictionary<string, Chart>
{
{chart.Name, chart}
}
}, Algorithm.EndDate, Algorithm.StartDate, progress));
}
// Send alpha run time statistics
splitPackets.Add(new BacktestResultPacket(_job, new BacktestResult { AlphaRuntimeStatistics = AlphaRuntimeStatistics }, Algorithm.EndDate, Algorithm.StartDate, progress));
// only send orders if there is actually any update
if (deltaOrders.Count > 0)
{
// Add the orders into the charting packet:
splitPackets.Add(new BacktestResultPacket(_job, new BacktestResult { Orders = deltaOrders }, Algorithm.EndDate, Algorithm.StartDate, progress));
}
//Add any user runtime statistics into the backtest.
splitPackets.Add(new BacktestResultPacket(_job, new BacktestResult { ServerStatistics = serverStatistics, RuntimeStatistics = runtimeStatistics }, Algorithm.EndDate, Algorithm.StartDate, progress));
return splitPackets;
}
/// <summary>
/// Save the snapshot of the total results to storage.
/// </summary>
/// <param name="packet">Packet to store.</param>
protected override void StoreResult(Packet packet)
{
try
{
// Make sure this is the right type of packet:
if (packet.Type != PacketType.BacktestResult) return;
// Port to packet format:
var result = packet as BacktestResultPacket;
if (result != null)
{
// Get Storage Location:
var key = $"{AlgorithmId}.json";
BacktestResult results;
lock (ChartLock)
{
results = new BacktestResult(new BacktestResultParameters(
result.Results.Charts.ToDictionary(x => x.Key, x => x.Value.Clone()),
result.Results.Orders,
result.Results.ProfitLoss,
result.Results.Statistics,
result.Results.RuntimeStatistics,
result.Results.RollingWindow,
null, // null order events, we store them separately
result.Results.TotalPerformance,
result.Results.AlphaRuntimeStatistics));
}
// Save results
SaveResults(key, results);
// Store Order Events in a separate file
StoreOrderEvents(Algorithm?.UtcTime ?? DateTime.UtcNow, result.Results.OrderEvents);
}
else
{
Log.Error("BacktestingResultHandler.StoreResult(): Result Null.");
}
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Send a final analysis result back to the IDE.
/// </summary>
protected void SendFinalResult()
{
try
{
BacktestResultPacket result;
// could happen if algorithm failed to init
if (Algorithm != null)
{
//Convert local dictionary:
var charts = new Dictionary<string, Chart>(Charts);
var orders = new Dictionary<int, Order>(TransactionHandler.Orders);
var profitLoss = new SortedDictionary<DateTime, decimal>(Algorithm.Transactions.TransactionRecord);
var statisticsResults = GenerateStatisticsResults(charts, profitLoss, _capacityEstimate);
var runtime = GetAlgorithmRuntimeStatistics(statisticsResults.Summary, capacityEstimate: _capacityEstimate);
FinalStatistics = statisticsResults.Summary;
// clear the trades collection before placing inside the backtest result
foreach (var ap in statisticsResults.RollingPerformances.Values)
{
ap.ClosedTrades.Clear();
}
var orderEvents = TransactionHandler.OrderEvents.ToList();
//Create a result packet to send to the browser.
result = new BacktestResultPacket(_job,
new BacktestResult(new BacktestResultParameters(charts, orders, profitLoss, statisticsResults.Summary, runtime, statisticsResults.RollingPerformances, orderEvents, statisticsResults.TotalPerformance, AlphaRuntimeStatistics)),
Algorithm.EndDate, Algorithm.StartDate);
}
else
{
result = BacktestResultPacket.CreateEmpty(_job);
}
var utcNow = DateTime.UtcNow;
result.ProcessingTime = (utcNow - StartTime).TotalSeconds;
result.DateFinished = DateTime.Now;
result.Progress = 1;
//Place result into storage.
StoreResult(result);
result.Results.ServerStatistics = GetServerStatistics(utcNow);
//Second, send the truncated packet:
MessagingHandler.Send(result);
Log.Trace("BacktestingResultHandler.SendAnalysisResult(): Processed final packet");
}
catch (Exception err)
{
Log.Error(err);
}
}
/// <summary>
/// Set the Algorithm instance for ths result.
/// </summary>
/// <param name="algorithm">Algorithm we're working on.</param>
/// <param name="startingPortfolioValue">Algorithm starting capital for statistics calculations</param>
/// <remarks>While setting the algorithm the backtest result handler.</remarks>
public virtual void SetAlgorithm(IAlgorithm algorithm, decimal startingPortfolioValue)
{
Algorithm = algorithm;
StartingPortfolioValue = startingPortfolioValue;
PreviousUtcSampleTime = Algorithm.UtcTime;
DailyPortfolioValue = StartingPortfolioValue;
CumulativeMaxPortfolioValue = StartingPortfolioValue;
AlgorithmCurrencySymbol = Currencies.GetCurrencySymbol(Algorithm.AccountCurrency);
_capacityEstimate = new CapacityEstimate(Algorithm);
//Get the resample period:
var totalMinutes = (algorithm.EndDate - algorithm.StartDate).TotalMinutes;
var resampleMinutes = totalMinutes < MinimumSamplePeriod * Samples ? MinimumSamplePeriod : totalMinutes / Samples; // Space out the sampling every
ResamplePeriod = TimeSpan.FromMinutes(resampleMinutes);
Log.Trace("BacktestingResultHandler(): Sample Period Set: " + resampleMinutes.ToStringInvariant("00.00"));
//Setup the sampling periods:
_jobDays = Algorithm.Securities.Count > 0
? Time.TradeableDates(Algorithm.Securities.Values, algorithm.StartDate, algorithm.EndDate)
: Convert.ToInt32((algorithm.EndDate.Date - algorithm.StartDate.Date).TotalDays) + 1;
//Set the security / market types.
var types = new List<SecurityType>();
foreach (var kvp in Algorithm.Securities)
{
var security = kvp.Value;
if (!types.Contains(security.Type)) types.Add(security.Type);
}
SecurityType(types);
ConfigureConsoleTextWriter(algorithm);
}
/// <summary>
/// Send a debug message back to the browser console.
/// </summary>
/// <param name="message">Message we'd like shown in console.</param>
public virtual void DebugMessage(string message)
{
Messages.Enqueue(new DebugPacket(_projectId, AlgorithmId, CompileId, message));
AddToLogStore(message);
}
/// <summary>
/// Send a system debug message back to the browser console.
/// </summary>
/// <param name="message">Message we'd like shown in console.</param>
public virtual void SystemDebugMessage(string message)
{
Messages.Enqueue(new SystemDebugPacket(_projectId, AlgorithmId, CompileId, message));
AddToLogStore(message);
}
/// <summary>
/// Send a logging message to the log list for storage.
/// </summary>
/// <param name="message">Message we'd in the log.</param>
public virtual void LogMessage(string message)
{
Messages.Enqueue(new LogPacket(AlgorithmId, message));
AddToLogStore(message);
}
/// <summary>
/// Add message to LogStore
/// </summary>
/// <param name="message">Message to add</param>
protected override void AddToLogStore(string message)
{
lock (LogStore)
{
var messageToLog = Algorithm != null
? new LogEntry(Algorithm.Time.ToStringInvariant(DateFormat.UI) + " " + message)
: new LogEntry("Algorithm Initialization: " + message);
LogStore.Add(messageToLog);
}
}
/// <summary>
/// Send list of security asset types the algortihm uses to browser.
/// </summary>
public virtual void SecurityType(List<SecurityType> types)
{
var packet = new SecurityTypesPacket
{
Types = types
};
Messages.Enqueue(packet);
}
/// <summary>
/// Send an error message back to the browser highlighted in red with a stacktrace.
/// </summary>
/// <param name="message">Error message we'd like shown in console.</param>
/// <param name="stacktrace">Stacktrace information string</param>
public virtual void ErrorMessage(string message, string stacktrace = "")
{
if (message == _errorMessage) return;
if (Messages.Count > 500) return;
Messages.Enqueue(new HandledErrorPacket(AlgorithmId, message, stacktrace));
_errorMessage = message;
}
/// <summary>
/// Send a runtime error message back to the browser highlighted with in red
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="stacktrace">Stacktrace information string</param>
public virtual void RuntimeError(string message, string stacktrace = "")
{
PurgeQueue();
Messages.Enqueue(new RuntimeErrorPacket(_job.UserId, AlgorithmId, message, stacktrace));
_errorMessage = message;
}
/// <summary>
/// Process brokerage message events
/// </summary>
/// <param name="brokerageMessageEvent">The brokerage message event</param>
public virtual void BrokerageMessage(BrokerageMessageEvent brokerageMessageEvent)
{
// NOP
}
/// <summary>
/// Add a sample to the chart specified by the chartName, and seriesName.
/// </summary>
/// <param name="chartName">String chart name to place the sample.</param>
/// <param name="seriesIndex">Type of chart we should create if it doesn't already exist.</param>
/// <param name="seriesName">Series name for the chart.</param>
/// <param name="seriesType">Series type for the chart.</param>
/// <param name="time">Time for the sample</param>
/// <param name="unit">Unit of the sample</param>
/// <param name="value">Value for the chart sample.</param>
protected override void Sample(string chartName, string seriesName, int seriesIndex, SeriesType seriesType, DateTime time, decimal value, string unit = "$")
{
// Sampling during warming up period skews statistics
if (Algorithm.IsWarmingUp)
{
return;
}
lock (ChartLock)
{
//Add a copy locally:
Chart chart;
if (!Charts.TryGetValue(chartName, out chart))
{
chart = new Chart(chartName);
Charts.AddOrUpdate(chartName, chart);
}
//Add the sample to our chart:
Series series;
if (!chart.Series.TryGetValue(seriesName, out series))
{
series = new Series(seriesName, seriesType, seriesIndex, unit);
chart.Series.Add(seriesName, series);
}
//Add our value:
if (series.Values.Count == 0 || time > Time.UnixTimeStampToDateTime(series.Values[series.Values.Count - 1].x))
{
series.AddPoint(time, value);
}
}
}
/// <summary>
/// Sample the current equity of the strategy directly with time-value pair.
/// </summary>
/// <param name="time">Current backtest time.</param>
/// <param name="value">Current equity value.</param>
protected override void SampleEquity(DateTime time, decimal value)
{
base.SampleEquity(time, value);
try
{
//Recalculate the days processed. We use 'int' so it's thread safe
_daysProcessed = (int) (time - Algorithm.StartDate).TotalDays;
}
catch (OverflowException)
{
}
}
/// <summary>
/// Sample estimated strategy capacity
/// </summary>
/// <param name="time">Time of the sample</param>
protected override void SampleCapacity(DateTime time)
{
// Sample strategy capacity, round to 1k
var roundedCapacity = _capacityEstimate.Capacity;
Sample("Capacity", "Strategy Capacity", 0, SeriesType.Line, time,
roundedCapacity, AlgorithmCurrencySymbol);
}
/// <summary>
/// Add a range of samples from the users algorithms to the end of our current list.
/// </summary>
/// <param name="updates">Chart updates since the last request.</param>
protected void SampleRange(List<Chart> updates)
{
lock (ChartLock)
{
foreach (var update in updates)
{
//Create the chart if it doesn't exist already:
Chart chart;
if (!Charts.TryGetValue(update.Name, out chart))
{
chart = new Chart(update.Name);
Charts.AddOrUpdate(update.Name, chart);
}
// for alpha assets chart, we always create a new series instance (step on previous value)
var forceNewSeries = update.Name == ChartingInsightManagerExtension.AlphaAssets;
//Add these samples to this chart.
foreach (var series in update.Series.Values)
{
if (series.Values.Count > 0)
{
var thisSeries = chart.TryAddAndGetSeries(series.Name, series.SeriesType, series.Index,
series.Unit, series.Color, series.ScatterMarkerSymbol,
forceNewSeries);
if (series.SeriesType == SeriesType.Pie)
{
var dataPoint = series.ConsolidateChartPoints();
if (dataPoint != null)
{
thisSeries.AddPoint(dataPoint);
}
}
else
{
var values = thisSeries.Values;
if ((values.Count + series.Values.Count) <= _job.Controls.MaximumDataPointsPerChartSeries) // check chart data point limit first
{
//We already have this record, so just the new samples to the end:
values.AddRange(series.Values);
}
else if (!_chartSeriesExceededDataPoints.Contains(chart.Name + series.Name))
{
_chartSeriesExceededDataPoints.Add(chart.Name + series.Name);
DebugMessage($"Exceeded maximum data points per series, chart update skipped. Chart Name {update.Name}. Series name {series.Name}. " +
$"Limit is currently set at {_job.Controls.MaximumDataPointsPerChartSeries}");
}
}
}
}
}
}
}
/// <summary>
/// Terminate the result thread and apply any required exit procedures like sending final results.
/// </summary>
public override void Exit()
{
// Only process the logs once
if (!ExitTriggered)
{
Log.Trace("BacktestingResultHandler.Exit(): starting...");
List<LogEntry> copy;
lock (LogStore)
{
copy = LogStore.ToList();
}
ProcessSynchronousEvents(true);
Log.Trace("BacktestingResultHandler.Exit(): Saving logs...");
var logLocation = SaveLogs(_algorithmId, copy);
SystemDebugMessage("Your log was successfully created and can be retrieved from: " + logLocation);
// Set exit flag, update task will send any message before stopping
ExitTriggered = true;
ExitEvent.Set();
StopUpdateRunner();
SendFinalResult();
base.Exit();
}
}
/// <summary>
/// Send an algorithm status update to the browser.
/// </summary>
/// <param name="status">Status enum value.</param>
/// <param name="message">Additional optional status message.</param>
public virtual void SendStatusUpdate(AlgorithmStatus status, string message = "")
{
var statusPacket = new AlgorithmStatusPacket(_algorithmId, _projectId, status, message) { OptimizationId = _job.OptimizationId };
MessagingHandler.Send(statusPacket);
}
/// <summary>
/// Set the current runtime statistics of the algorithm.
/// These are banner/title statistics which show at the top of the live trading results.
/// </summary>
/// <param name="key">Runtime headline statistic name</param>
/// <param name="value">Runtime headline statistic value</param>
public virtual void RuntimeStatistic(string key, string value)
{
lock (RuntimeStatistics)
{
RuntimeStatistics[key] = value;
}
}
/// <summary>
/// Handle order event
/// </summary>
/// <param name="newEvent">Event to process</param>
public override void OrderEvent(OrderEvent newEvent)
{
_capacityEstimate?.OnOrderEvent(newEvent);
}
/// <summary>
/// Process the synchronous result events, sampling and message reading.
/// This method is triggered from the algorithm manager thread.
/// </summary>
/// <remarks>Prime candidate for putting into a base class. Is identical across all result handlers.</remarks>
public virtual void ProcessSynchronousEvents(bool forceProcess = false)
{
if (Algorithm == null) return;
_capacityEstimate.UpdateMarketCapacity(forceProcess);
var time = Algorithm.UtcTime;
if (time > _nextSample || forceProcess)
{
//Set next sample time: 4000 samples per backtest
_nextSample = time.Add(ResamplePeriod);
//Sample the portfolio value over time for chart.
SampleEquity(time, Math.Round(Algorithm.Portfolio.TotalPortfolioValue, 4));
//Also add the user samples / plots to the result handler tracking:
SampleRange(Algorithm.GetChartUpdates());
}
ProcessAlgorithmLogs();
//Set the running statistics:
foreach (var pair in Algorithm.RuntimeStatistics)
{
RuntimeStatistic(pair.Key, pair.Value);
}
}
/// <summary>
/// Configures the <see cref="Console.Out"/> and <see cref="Console.Error"/> <see cref="TextWriter"/>
/// instances. By default, we forward <see cref="Console.WriteLine(string)"/> to <see cref="IAlgorithm.Debug"/>.
/// This is perfect for running in the cloud, but since they're processed asynchronously, the ordering of these
/// messages with respect to <see cref="Log"/> messages is broken. This can lead to differences in regression
/// test logs based solely on the ordering of messages. To disable this forwarding, set <code>"forward-console-messages"</code>
/// to <code>false</code> in the configuration.
/// </summary>
protected virtual void ConfigureConsoleTextWriter(IAlgorithm algorithm)
{
if (Config.GetBool("forward-console-messages", true))
{
// we need to forward Console.Write messages to the algorithm's Debug function
Console.SetOut(new FuncTextWriter(algorithm.Debug));
Console.SetError(new FuncTextWriter(algorithm.Error));
}
else
{
// we need to forward Console.Write messages to the standard Log functions
Console.SetOut(new FuncTextWriter(msg => Log.Trace(msg)));
Console.SetError(new FuncTextWriter(msg => Log.Error(msg)));
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class Is
{
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public static ConstraintExpression Not
{
get { return new ConstraintExpression().Not; }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public static ConstraintExpression All
{
get { return new ConstraintExpression().All; }
}
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public static NullConstraint Null
{
get { return new NullConstraint(); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public static TrueConstraint True
{
get { return new TrueConstraint(); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public static FalseConstraint False
{
get { return new FalseConstraint(); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public static GreaterThanConstraint Positive
{
get { return new GreaterThanConstraint(0); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public static LessThanConstraint Negative
{
get { return new LessThanConstraint(0); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public static NaNConstraint NaN
{
get { return new NaNConstraint(); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public static EmptyConstraint Empty
{
get { return new EmptyConstraint(); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public static UniqueItemsConstraint Unique
{
get { return new UniqueItemsConstraint(); }
}
#endregion
#region BinarySerializable
#if !NETCF && !SILVERLIGHT && !PORTABLE
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public static BinarySerializableConstraint BinarySerializable
{
get { return new BinarySerializableConstraint(); }
}
#endif
#endregion
#region XmlSerializable
#if !SILVERLIGHT
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in xml format.
/// </summary>
public static XmlSerializableConstraint XmlSerializable
{
get { return new XmlSerializableConstraint(); }
}
#endif
#endregion
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public static EqualConstraint EqualTo(object expected)
{
return new EqualConstraint(expected);
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public static SameAsConstraint SameAs(object expected)
{
return new SameAsConstraint(expected);
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the supplied argument
/// </summary>
public static GreaterThanConstraint GreaterThan(object expected)
{
return new GreaterThanConstraint(expected);
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public static GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public static GreaterThanOrEqualConstraint AtLeast(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the supplied argument
/// </summary>
public static LessThanConstraint LessThan(object expected)
{
return new LessThanConstraint(expected);
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public static LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public static LessThanOrEqualConstraint AtMost(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public static ExactTypeConstraint TypeOf(Type expectedType)
{
return new ExactTypeConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public static ExactTypeConstraint TypeOf<TExpected>()
{
return new ExactTypeConstraint(typeof(TExpected));
}
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public static InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public static InstanceOfTypeConstraint InstanceOf<TExpected>()
{
return new InstanceOfTypeConstraint(typeof(TExpected));
}
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableFromConstraint AssignableFrom(Type expectedType)
{
return new AssignableFromConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public static AssignableFromConstraint AssignableFrom<TExpected>()
{
return new AssignableFromConstraint(typeof(TExpected));
}
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable to the type supplied as an argument.
/// </summary>
public static AssignableToConstraint AssignableTo(Type expectedType)
{
return new AssignableToConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable to the type supplied as an argument.
/// </summary>
public static AssignableToConstraint AssignableTo<TExpected>()
{
return new AssignableToConstraint(typeof(TExpected));
}
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public static CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return new CollectionEquivalentConstraint(expected);
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public static CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return new CollectionSubsetConstraint(expected);
}
#endregion
#region SupersetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a superset of the collection supplied as an argument.
/// </summary>
public static CollectionSupersetConstraint SupersetOf(IEnumerable expected)
{
return new CollectionSupersetConstraint(expected);
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public static CollectionOrderedConstraint Ordered
{
get { return new CollectionOrderedConstraint(); }
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Contain")]
public static SubstringConstraint StringContaining(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
#region StringStarting
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.StartWith")]
public static StartsWithConstraint StringStarting(string expected)
{
return new StartsWithConstraint(expected);
}
#endregion
#region StringEnding
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.EndWith")]
public static EndsWithConstraint StringEnding(string expected)
{
return new EndsWithConstraint(expected);
}
#endregion
#region StringMatching
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Match")]
public static RegexConstraint StringMatching(string pattern)
{
return new RegexConstraint(pattern);
}
#endregion
#if !PORTABLE
#region SamePath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public static SamePathConstraint SamePath(string expected)
{
return new SamePathConstraint(expected);
}
#endregion
#region SubPath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is a subpath of the expected path after canonicalization.
/// </summary>
public static SubPathConstraint SubPathOf(string expected)
{
return new SubPathConstraint(expected);
}
#endregion
#region SamePathOrUnder
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public static SamePathOrUnderConstraint SamePathOrUnder(string expected)
{
return new SamePathOrUnderConstraint(expected);
}
#endregion
#endif
#region InRange
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// inclusively within a specified range.
/// </summary>
/// <remarks>from must be less than or equal to true</remarks>
/// <param name="from">Inclusive beginning of the range. Must be less than or equal to to.</param>
/// <param name="to">Inclusive end of the range. Must be greater than or equal to from.</param>
/// <returns></returns>
public static RangeConstraint InRange(IComparable from, IComparable to)
{
return new RangeConstraint(from, to);
}
#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.
/*============================================================
**
**
**
** Purpose: This class will encapsulate a long and provide an
** Object representation of it.
**
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Int64 : IComparable, IFormattable, IConvertible
, IComparable<Int64>, IEquatable<Int64>
{
internal long m_value;
public const long MaxValue = 0x7fffffffffffffffL;
public const long MinValue = unchecked((long)0x8000000000000000L);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Int64, this method throws an ArgumentException.
//
public int CompareTo(Object value) {
if (value == null) {
return 1;
}
if (value is Int64) {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
long i = (long)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException (Environment.GetResourceString("Arg_MustBeInt64"));
}
public int CompareTo(Int64 value) {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj) {
if (!(obj is Int64)) {
return false;
}
return m_value == ((Int64)obj).m_value;
}
[System.Runtime.Versioning.NonVersionable]
public bool Equals(Int64 obj)
{
return m_value == obj;
}
// The value of the lower 32 bits XORed with the uppper 32 bits.
public override int GetHashCode() {
return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32));
}
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, format, NumberFormatInfo.GetInstance(provider));
}
public static long Parse(String s) {
return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
public static long Parse(String s, NumberStyles style) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt64(s, style, NumberFormatInfo.CurrentInfo);
}
public static long Parse(String s, IFormatProvider provider) {
return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses a long from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
public static long Parse(String s, NumberStyles style, IFormatProvider provider) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt64(s, style, NumberFormatInfo.GetInstance(provider));
}
public static Boolean TryParse(String s, out Int64 result) {
return Number.TryParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Int64 result) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt64(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode() {
return TypeCode.Int64;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
return Convert.ToBoolean(m_value);
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
return Convert.ToChar(m_value);
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider) {
return Convert.ToSByte(m_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return Convert.ToByte(m_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
return Convert.ToInt16(m_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider) {
return Convert.ToUInt16(m_value);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
return Convert.ToInt32(m_value);
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider) {
return Convert.ToUInt32(m_value);
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
return m_value;
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider) {
return Convert.ToUInt64(m_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
return Convert.ToSingle(m_value);
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
return Convert.ToDouble(m_value);
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider) {
return Convert.ToDecimal(m_value);
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int64", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// 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.Data.Common;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Runtime.CompilerServices;
namespace System.Data.SqlTypes
{
internal enum SqlBytesCharsState
{
Null = 0,
Buffer = 1,
//IntPtr = 2,
Stream = 3,
}
[Serializable]
[XmlSchemaProvider("GetXsdType")]
public sealed class SqlBytes : INullable, IXmlSerializable, ISerializable
{
// --------------------------------------------------------------
// Data members
// --------------------------------------------------------------
// SqlBytes has five possible states
// 1) SqlBytes is Null
// - m_stream must be null, m_lCuLen must be x_lNull.
// 2) SqlBytes contains a valid buffer,
// - m_rgbBuf must not be null,m_stream must be null
// 3) SqlBytes contains a valid pointer
// - m_rgbBuf could be null or not,
// if not null, content is garbage, should never look into it.
// - m_stream must be null.
// 4) SqlBytes contains a Stream
// - m_stream must not be null
// - m_rgbBuf could be null or not. if not null, content is garbage, should never look into it.
// - m_lCurLen must be x_lNull.
// 5) SqlBytes contains a Lazy Materialized Blob (ie, StorageState.Delayed)
//
internal byte[] _rgbBuf; // Data buffer
private long _lCurLen; // Current data length
internal Stream _stream;
private SqlBytesCharsState _state;
private byte[] _rgbWorkBuf; // A 1-byte work buffer.
// The max data length that we support at this time.
private const long x_lMaxLen = System.Int32.MaxValue;
private const long x_lNull = -1L;
// --------------------------------------------------------------
// Constructor(s)
// --------------------------------------------------------------
// Public default constructor used for XML serialization
public SqlBytes()
{
SetNull();
}
// Create a SqlBytes with an in-memory buffer
public SqlBytes(byte[] buffer)
{
_rgbBuf = buffer;
_stream = null;
if (_rgbBuf == null)
{
_state = SqlBytesCharsState.Null;
_lCurLen = x_lNull;
}
else
{
_state = SqlBytesCharsState.Buffer;
_lCurLen = _rgbBuf.Length;
}
_rgbWorkBuf = null;
AssertValid();
}
// Create a SqlBytes from a SqlBinary
public SqlBytes(SqlBinary value) : this(value.IsNull ? null : value.Value)
{
}
public SqlBytes(Stream s)
{
// Create a SqlBytes from a Stream
_rgbBuf = null;
_lCurLen = x_lNull;
_stream = s;
_state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream;
_rgbWorkBuf = null;
AssertValid();
}
// Constructor required for serialization. Deserializes as a Buffer. If the bits have been tampered with
// then this will throw a SerializationException or a InvalidCastException.
private SqlBytes(SerializationInfo info, StreamingContext context)
{
_stream = null;
_rgbWorkBuf = null;
if (info.GetBoolean("IsNull"))
{
_state = SqlBytesCharsState.Null;
_rgbBuf = null;
}
else
{
_state = SqlBytesCharsState.Buffer;
_rgbBuf = (byte[])info.GetValue("data", typeof(byte[]));
_lCurLen = _rgbBuf.Length;
}
AssertValid();
}
// --------------------------------------------------------------
// Public properties
// --------------------------------------------------------------
// INullable
public bool IsNull
{
get
{
return _state == SqlBytesCharsState.Null;
}
}
// Property: the in-memory buffer of SqlBytes
// Return Buffer even if SqlBytes is Null.
public byte[] Buffer
{
get
{
if (FStream())
{
CopyStreamToBuffer();
}
return _rgbBuf;
}
}
// Property: the actual length of the data
public long Length
{
get
{
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
return _stream.Length;
default:
return _lCurLen;
}
}
}
// Property: the max length of the data
// Return MaxLength even if SqlBytes is Null.
// When the buffer is also null, return -1.
// If containing a Stream, return -1.
public long MaxLength
{
get
{
switch (_state)
{
case SqlBytesCharsState.Stream:
return -1L;
default:
return (_rgbBuf == null) ? -1L : _rgbBuf.Length;
}
}
}
// Property: get a copy of the data in a new byte[] array.
public byte[] Value
{
get
{
byte[] buffer;
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
if (_stream.Length > x_lMaxLen)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
buffer = new byte[_stream.Length];
if (_stream.Position != 0)
_stream.Seek(0, SeekOrigin.Begin);
_stream.Read(buffer, 0, checked((int)_stream.Length));
break;
default:
buffer = new byte[_lCurLen];
Array.Copy(_rgbBuf, 0, buffer, 0, (int)_lCurLen);
break;
}
return buffer;
}
}
// class indexer
public byte this[long offset]
{
get
{
if (offset < 0 || offset >= Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (_rgbWorkBuf == null)
_rgbWorkBuf = new byte[1];
Read(offset, _rgbWorkBuf, 0, 1);
return _rgbWorkBuf[0];
}
set
{
if (_rgbWorkBuf == null)
_rgbWorkBuf = new byte[1];
_rgbWorkBuf[0] = value;
Write(offset, _rgbWorkBuf, 0, 1);
}
}
public StorageState Storage
{
get
{
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
return StorageState.Stream;
case SqlBytesCharsState.Buffer:
return StorageState.Buffer;
default:
return StorageState.UnmanagedBuffer;
}
}
}
public Stream Stream
{
get
{
return FStream() ? _stream : new StreamOnSqlBytes(this);
}
set
{
_lCurLen = x_lNull;
_stream = value;
_state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream;
AssertValid();
}
}
// --------------------------------------------------------------
// Public methods
// --------------------------------------------------------------
public void SetNull()
{
_lCurLen = x_lNull;
_stream = null;
_state = SqlBytesCharsState.Null;
AssertValid();
}
// Set the current length of the data
// If the SqlBytes is Null, setLength will make it non-Null.
public void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
if (FStream())
{
_stream.SetLength(value);
}
else
{
// If there is a buffer, even the value of SqlBytes is Null,
// still allow setting length to zero, which will make it not Null.
// If the buffer is null, raise exception
//
if (null == _rgbBuf)
throw new SqlTypeException(SR.SqlMisc_NoBufferMessage);
if (value > _rgbBuf.Length)
throw new ArgumentOutOfRangeException(nameof(value));
else if (IsNull)
// At this point we know that value is small enough
// Go back in buffer mode
_state = SqlBytesCharsState.Buffer;
_lCurLen = value;
}
AssertValid();
}
// Read data of specified length from specified offset into a buffer
public long Read(long offset, byte[] buffer, int offsetInBuffer, int count)
{
if (IsNull)
throw new SqlNullValueException();
// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset > Length || offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (offsetInBuffer > buffer.Length || offsetInBuffer < 0)
throw new ArgumentOutOfRangeException(nameof(offsetInBuffer));
if (count < 0 || count > buffer.Length - offsetInBuffer)
throw new ArgumentOutOfRangeException(nameof(count));
// Adjust count based on data length
if (count > Length - offset)
count = (int)(Length - offset);
if (count != 0)
{
switch (_state)
{
case SqlBytesCharsState.Stream:
if (_stream.Position != offset)
_stream.Seek(offset, SeekOrigin.Begin);
_stream.Read(buffer, offsetInBuffer, count);
break;
default:
Array.Copy(_rgbBuf, offset, buffer, offsetInBuffer, count);
break;
}
}
return count;
}
// Write data of specified length into the SqlBytes from specified offset
public void Write(long offset, byte[] buffer, int offsetInBuffer, int count)
{
if (FStream())
{
if (_stream.Position != offset)
_stream.Seek(offset, SeekOrigin.Begin);
_stream.Write(buffer, offsetInBuffer, count);
}
else
{
// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (_rgbBuf == null)
throw new SqlTypeException(SR.SqlMisc_NoBufferMessage);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (offset > _rgbBuf.Length)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offsetInBuffer));
if (count < 0 || count > buffer.Length - offsetInBuffer)
throw new ArgumentOutOfRangeException(nameof(count));
if (count > _rgbBuf.Length - offset)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
if (IsNull)
{
// If NULL and there is buffer inside, we only allow writing from
// offset zero.
//
if (offset != 0)
throw new SqlTypeException(SR.SqlMisc_WriteNonZeroOffsetOnNullMessage);
// treat as if our current length is zero.
// Note this has to be done after all inputs are validated, so that
// we won't throw exception after this point.
//
_lCurLen = 0;
_state = SqlBytesCharsState.Buffer;
}
else if (offset > _lCurLen)
{
// Don't allow writing from an offset that this larger than current length.
// It would leave uninitialized data in the buffer.
//
throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage);
}
if (count != 0)
{
Array.Copy(buffer, offsetInBuffer, _rgbBuf, offset, count);
// If the last position that has been written is after
// the current data length, reset the length
if (_lCurLen < offset + count)
_lCurLen = offset + count;
}
}
AssertValid();
}
public SqlBinary ToSqlBinary()
{
return IsNull ? SqlBinary.Null : new SqlBinary(Value);
}
// --------------------------------------------------------------
// Conversion operators
// --------------------------------------------------------------
// Alternative method: ToSqlBinary()
public static explicit operator SqlBinary(SqlBytes value)
{
return value.ToSqlBinary();
}
// Alternative method: constructor SqlBytes(SqlBinary)
public static explicit operator SqlBytes(SqlBinary value)
{
return new SqlBytes(value);
}
// --------------------------------------------------------------
// Private utility functions
// --------------------------------------------------------------
[Conditional("DEBUG")]
private void AssertValid()
{
Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream);
if (IsNull)
{
}
else
{
Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream());
Debug.Assert(FStream() || (_rgbBuf != null && _lCurLen <= _rgbBuf.Length));
Debug.Assert(!FStream() || (_lCurLen == x_lNull));
}
Debug.Assert(_rgbWorkBuf == null || _rgbWorkBuf.Length == 1);
}
// Copy the data from the Stream to the array buffer.
// If the SqlBytes doesn't hold a buffer or the buffer
// is not big enough, allocate new byte array.
private void CopyStreamToBuffer()
{
Debug.Assert(FStream());
long lStreamLen = _stream.Length;
if (lStreamLen >= x_lMaxLen)
throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage);
if (_rgbBuf == null || _rgbBuf.Length < lStreamLen)
_rgbBuf = new byte[lStreamLen];
if (_stream.Position != 0)
_stream.Seek(0, SeekOrigin.Begin);
_stream.Read(_rgbBuf, 0, (int)lStreamLen);
_stream = null;
_lCurLen = lStreamLen;
_state = SqlBytesCharsState.Buffer;
AssertValid();
}
// whether the SqlBytes contains a pointer
// whether the SqlBytes contains a Stream
internal bool FStream()
{
return _state == SqlBytesCharsState.Stream;
}
private void SetBuffer(byte[] buffer)
{
_rgbBuf = buffer;
_lCurLen = (_rgbBuf == null) ? x_lNull : _rgbBuf.Length;
_stream = null;
_state = (_rgbBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer;
AssertValid();
}
// --------------------------------------------------------------
// XML Serialization
// --------------------------------------------------------------
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
void IXmlSerializable.ReadXml(XmlReader r)
{
byte[] value = null;
string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
r.ReadElementString();
SetNull();
}
else
{
string base64 = r.ReadElementString();
if (base64 == null)
{
value = Array.Empty<byte>();
}
else
{
base64 = base64.Trim();
if (base64.Length == 0)
value = Array.Empty<byte>();
else
value = Convert.FromBase64String(base64);
}
}
SetBuffer(value);
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (IsNull)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
byte[] value = Buffer;
writer.WriteString(Convert.ToBase64String(value, 0, (int)(Length)));
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("base64Binary", XmlSchema.Namespace);
}
// --------------------------------------------------------------
// Serialization using ISerializable
// --------------------------------------------------------------
// State information is not saved. The current state is converted to Buffer and only the underlying
// array is serialized, except for Null, in which case this state is kept.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
switch (_state)
{
case SqlBytesCharsState.Null:
info.AddValue("IsNull", true);
break;
case SqlBytesCharsState.Buffer:
info.AddValue("IsNull", false);
info.AddValue("data", _rgbBuf);
break;
case SqlBytesCharsState.Stream:
CopyStreamToBuffer();
goto case SqlBytesCharsState.Buffer;
default:
Debug.Assert(false);
goto case SqlBytesCharsState.Null;
}
}
// --------------------------------------------------------------
// Static fields, properties
// --------------------------------------------------------------
// Get a Null instance.
// Since SqlBytes is mutable, have to be property and create a new one each time.
public static SqlBytes Null
{
get
{
return new SqlBytes((byte[])null);
}
}
} // class SqlBytes
// StreamOnSqlBytes is a stream build on top of SqlBytes, and
// provides the Stream interface. The purpose is to help users
// to read/write SqlBytes object. After getting the stream from
// SqlBytes, users could create a BinaryReader/BinaryWriter object
// to easily read and write primitive types.
internal sealed class StreamOnSqlBytes : Stream
{
// --------------------------------------------------------------
// Data members
// --------------------------------------------------------------
private SqlBytes _sb; // the SqlBytes object
private long _lPosition;
// --------------------------------------------------------------
// Constructor(s)
// --------------------------------------------------------------
internal StreamOnSqlBytes(SqlBytes sb)
{
_sb = sb;
_lPosition = 0;
}
// --------------------------------------------------------------
// Public properties
// --------------------------------------------------------------
// Always can read/write/seek, unless sb is null,
// which means the stream has been closed.
public override bool CanRead
{
get
{
return _sb != null && !_sb.IsNull;
}
}
public override bool CanSeek
{
get
{
return _sb != null;
}
}
public override bool CanWrite
{
get
{
return _sb != null && (!_sb.IsNull || _sb._rgbBuf != null);
}
}
public override long Length
{
get
{
CheckIfStreamClosed("get_Length");
return _sb.Length;
}
}
public override long Position
{
get
{
CheckIfStreamClosed("get_Position");
return _lPosition;
}
set
{
CheckIfStreamClosed("set_Position");
if (value < 0 || value > _sb.Length)
throw new ArgumentOutOfRangeException(nameof(value));
else
_lPosition = value;
}
}
// --------------------------------------------------------------
// Public methods
// --------------------------------------------------------------
public override long Seek(long offset, SeekOrigin origin)
{
CheckIfStreamClosed();
long lPosition = 0;
switch (origin)
{
case SeekOrigin.Begin:
if (offset < 0 || offset > _sb.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
_lPosition = offset;
break;
case SeekOrigin.Current:
lPosition = _lPosition + offset;
if (lPosition < 0 || lPosition > _sb.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
_lPosition = lPosition;
break;
case SeekOrigin.End:
lPosition = _sb.Length + offset;
if (lPosition < 0 || lPosition > _sb.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
_lPosition = lPosition;
break;
default:
throw ADP.InvalidSeekOrigin(nameof(offset));
}
return _lPosition;
}
// The Read/Write/ReadByte/WriteByte simply delegates to SqlBytes
public override int Read(byte[] buffer, int offset, int count)
{
CheckIfStreamClosed();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
int iBytesRead = (int)_sb.Read(_lPosition, buffer, offset, count);
_lPosition += iBytesRead;
return iBytesRead;
}
public override void Write(byte[] buffer, int offset, int count)
{
CheckIfStreamClosed();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
_sb.Write(_lPosition, buffer, offset, count);
_lPosition += count;
}
public override int ReadByte()
{
CheckIfStreamClosed();
// If at the end of stream, return -1, rather than call SqlBytes.ReadByte,
// which will throw exception. This is the behavior for Stream.
//
if (_lPosition >= _sb.Length)
return -1;
int ret = _sb[_lPosition];
_lPosition++;
return ret;
}
public override void WriteByte(byte value)
{
CheckIfStreamClosed();
_sb[_lPosition] = value;
_lPosition++;
}
public override void SetLength(long value)
{
CheckIfStreamClosed();
_sb.SetLength(value);
if (_lPosition > value)
_lPosition = value;
}
// Flush is a no-op for stream on SqlBytes, because they are all in memory
public override void Flush()
{
if (_sb.FStream())
_sb._stream.Flush();
}
protected override void Dispose(bool disposing)
{
// When m_sb is null, it means the stream has been closed, and
// any opearation in the future should fail.
// This is the only case that m_sb is null.
try
{
_sb = null;
}
finally
{
base.Dispose(disposing);
}
}
// --------------------------------------------------------------
// Private utility functions
// --------------------------------------------------------------
private bool FClosed()
{
return _sb == null;
}
private void CheckIfStreamClosed([CallerMemberName] string methodname = "")
{
if (FClosed())
throw ADP.StreamClosed(methodname);
}
} // class StreamOnSqlBytes
} // namespace System.Data.SqlTypes
| |
namespace Boo.Lang.Parser.Tests
{
using NUnit.Framework;
[TestFixture]
public class ParserRoundtripTestFixture : AbstractParserTestFixture
{
void RunCompilerTestCase(string fname)
{
RunParserTestCase(fname);
}
[Test]
public void and_or_1()
{
RunCompilerTestCase(@"and-or-1.boo");
}
[Test]
public void arrays_1()
{
RunCompilerTestCase(@"arrays-1.boo");
}
[Test]
public void arrays_2()
{
RunCompilerTestCase(@"arrays-2.boo");
}
[Test]
public void arrays_3()
{
RunCompilerTestCase(@"arrays-3.boo");
}
[Test]
public void arrays_4()
{
RunCompilerTestCase(@"arrays-4.boo");
}
[Test]
public void arrays_5()
{
RunCompilerTestCase(@"arrays-5.boo");
}
[Test]
public void arrays_6()
{
RunCompilerTestCase(@"arrays-6.boo");
}
[Test]
public void as_1()
{
RunCompilerTestCase(@"as-1.boo");
}
[Test]
public void assignment_1()
{
RunCompilerTestCase(@"assignment-1.boo");
}
[Test]
public void ast_literal_enum()
{
RunCompilerTestCase(@"ast-literal-enum.boo");
}
[Test]
public void ast_literal_varargs_method()
{
RunCompilerTestCase(@"ast-literal-varargs-method.boo");
}
[Test]
public void ast_literals_1()
{
RunCompilerTestCase(@"ast-literals-1.boo");
}
[Test]
public void ast_literals_10()
{
RunCompilerTestCase(@"ast-literals-10.boo");
}
[Test]
public void ast_literals_11()
{
RunCompilerTestCase(@"ast-literals-11.boo");
}
[Test]
public void ast_literals_2()
{
RunCompilerTestCase(@"ast-literals-2.boo");
}
[Test]
public void ast_literals_3()
{
RunCompilerTestCase(@"ast-literals-3.boo");
}
[Test]
public void ast_literals_4()
{
RunCompilerTestCase(@"ast-literals-4.boo");
}
[Test]
public void ast_literals_5()
{
RunCompilerTestCase(@"ast-literals-5.boo");
}
[Test]
public void ast_literals_6()
{
RunCompilerTestCase(@"ast-literals-6.boo");
}
[Test]
public void ast_literals_7()
{
RunCompilerTestCase(@"ast-literals-7.boo");
}
[Test]
public void ast_literals_8()
{
RunCompilerTestCase(@"ast-literals-8.boo");
}
[Test]
public void ast_literals_9()
{
RunCompilerTestCase(@"ast-literals-9.boo");
}
[Test]
public void ast_literals_if_it_looks_like_a_block_1()
{
RunCompilerTestCase(@"ast-literals-if-it-looks-like-a-block-1.boo");
}
[Test]
public void at_operator()
{
RunCompilerTestCase(@"at-operator.boo");
}
[Test]
public void attributes_1()
{
RunCompilerTestCase(@"attributes-1.boo");
}
[Test]
public void attributes_2()
{
RunCompilerTestCase(@"attributes-2.boo");
}
[Test]
public void bool_literals_1()
{
RunCompilerTestCase(@"bool-literals-1.boo");
}
[Test]
public void callables_1()
{
RunCompilerTestCase(@"callables-1.boo");
}
[Test]
public void callables_2()
{
RunCompilerTestCase(@"callables-2.boo");
}
[Test]
public void callables_with_varags()
{
RunCompilerTestCase(@"callables-with-varags.boo");
}
[Test]
public void cast_1()
{
RunCompilerTestCase(@"cast-1.boo");
}
[Test]
public void char_1()
{
RunCompilerTestCase(@"char-1.boo");
}
[Test]
public void char_2()
{
RunCompilerTestCase(@"char-2.boo");
}
[Test]
public void class_1()
{
RunCompilerTestCase(@"class-1.boo");
}
[Test]
public void class_2()
{
RunCompilerTestCase(@"class-2.boo");
}
[Test]
public void class_3()
{
RunCompilerTestCase(@"class-3.boo");
}
[Test]
public void closures_1()
{
RunCompilerTestCase(@"closures-1.boo");
}
[Test]
public void closures_10()
{
RunCompilerTestCase(@"closures-10.boo");
}
[Test]
public void closures_11()
{
RunCompilerTestCase(@"closures-11.boo");
}
[Test]
public void closures_12()
{
RunCompilerTestCase(@"closures-12.boo");
}
[Test]
public void closures_13()
{
RunCompilerTestCase(@"closures-13.boo");
}
[Test]
public void closures_14()
{
RunCompilerTestCase(@"closures-14.boo");
}
[Test]
public void closures_15()
{
RunCompilerTestCase(@"closures-15.boo");
}
[Test]
public void closures_16()
{
RunCompilerTestCase(@"closures-16.boo");
}
[Test]
public void closures_17()
{
RunCompilerTestCase(@"closures-17.boo");
}
[Test]
public void closures_18()
{
RunCompilerTestCase(@"closures-18.boo");
}
[Test]
public void closures_19()
{
RunCompilerTestCase(@"closures-19.boo");
}
[Test]
public void closures_2()
{
RunCompilerTestCase(@"closures-2.boo");
}
[Test]
public void closures_20()
{
RunCompilerTestCase(@"closures-20.boo");
}
[Test]
public void closures_21()
{
RunCompilerTestCase(@"closures-21.boo");
}
[Test]
public void closures_22()
{
RunCompilerTestCase(@"closures-22.boo");
}
[Test]
public void closures_3()
{
RunCompilerTestCase(@"closures-3.boo");
}
[Test]
public void closures_4()
{
RunCompilerTestCase(@"closures-4.boo");
}
[Test]
public void closures_5()
{
RunCompilerTestCase(@"closures-5.boo");
}
[Test]
public void closures_6()
{
RunCompilerTestCase(@"closures-6.boo");
}
[Test]
public void closures_7()
{
RunCompilerTestCase(@"closures-7.boo");
}
[Test]
public void closures_8()
{
RunCompilerTestCase(@"closures-8.boo");
}
[Test]
public void closures_9()
{
RunCompilerTestCase(@"closures-9.boo");
}
[Test]
public void collection_initializer()
{
RunCompilerTestCase(@"collection-initializer.boo");
}
[Test]
public void comments_1()
{
RunCompilerTestCase(@"comments-1.boo");
}
[Test]
public void comments_2()
{
RunCompilerTestCase(@"comments-2.boo");
}
[Test]
public void comments_3()
{
RunCompilerTestCase(@"comments-3.boo");
}
[Test]
public void comments_4()
{
RunCompilerTestCase(@"comments-4.boo");
}
[Test]
public void conditional_1()
{
RunCompilerTestCase(@"conditional-1.boo");
}
[Test]
public void declarations_1()
{
RunCompilerTestCase(@"declarations-1.boo");
}
[Test]
public void declarations_2()
{
RunCompilerTestCase(@"declarations-2.boo");
}
[Test]
public void declarations_3()
{
RunCompilerTestCase(@"declarations-3.boo");
}
[Test]
public void double_literals_1()
{
RunCompilerTestCase(@"double-literals-1.boo");
}
[Test]
public void dsl_1()
{
RunCompilerTestCase(@"dsl-1.boo");
}
[Test]
public void elif_1()
{
RunCompilerTestCase(@"elif-1.boo");
}
[Test]
public void elif_2()
{
RunCompilerTestCase(@"elif-2.boo");
}
[Test]
public void enumerable_type_shortcut()
{
RunCompilerTestCase(@"enumerable-type-shortcut.boo");
}
[Test]
public void enums_1()
{
RunCompilerTestCase(@"enums-1.boo");
}
[Test]
public void events_1()
{
RunCompilerTestCase(@"events-1.boo");
}
[Test]
public void explode_1()
{
RunCompilerTestCase(@"explode-1.boo");
}
[Test]
public void explode_2()
{
RunCompilerTestCase(@"explode-2.boo");
}
[Test]
public void expressions_1()
{
RunCompilerTestCase(@"expressions-1.boo");
}
[Test]
public void expressions_2()
{
RunCompilerTestCase(@"expressions-2.boo");
}
[Test]
public void expressions_3()
{
RunCompilerTestCase(@"expressions-3.boo");
}
[Test]
public void expressions_4()
{
RunCompilerTestCase(@"expressions-4.boo");
}
[Test]
public void expressions_5()
{
RunCompilerTestCase(@"expressions-5.boo");
}
[Test]
public void extensions_1()
{
RunCompilerTestCase(@"extensions-1.boo");
}
[Test]
public void fields_1()
{
RunCompilerTestCase(@"fields-1.boo");
}
[Test]
public void fields_2()
{
RunCompilerTestCase(@"fields-2.boo");
}
[Test]
public void fields_3()
{
RunCompilerTestCase(@"fields-3.boo");
}
[Test]
public void fields_4()
{
RunCompilerTestCase(@"fields-4.boo");
}
[Test]
public void fields_5()
{
RunCompilerTestCase(@"fields-5.boo");
}
[Test]
public void fields_6()
{
RunCompilerTestCase(@"fields-6.boo");
}
[Test]
public void for_or_1()
{
RunCompilerTestCase(@"for_or-1.boo");
}
[Test]
public void for_or_then_1()
{
RunCompilerTestCase(@"for_or_then-1.boo");
}
[Test]
public void for_then_1()
{
RunCompilerTestCase(@"for_then-1.boo");
}
[Test]
public void generators_1()
{
RunCompilerTestCase(@"generators-1.boo");
}
[Test]
public void generators_2()
{
RunCompilerTestCase(@"generators-2.boo");
}
[Test]
public void generators_3()
{
RunCompilerTestCase(@"generators-3.boo");
}
[Test]
public void generic_method_1()
{
RunCompilerTestCase(@"generic-method-1.boo");
}
[Test]
public void generic_method_2()
{
RunCompilerTestCase(@"generic-method-2.boo");
}
[Test]
public void generic_method_3()
{
RunCompilerTestCase(@"generic-method-3.boo");
}
[Test]
public void generic_parameter_constraints()
{
RunCompilerTestCase(@"generic-parameter-constraints.boo");
}
[Test]
public void generics_1()
{
RunCompilerTestCase(@"generics-1.boo");
}
[Test]
public void generics_2()
{
RunCompilerTestCase(@"generics-2.boo");
}
[Test]
public void generics_3()
{
RunCompilerTestCase(@"generics-3.boo");
}
[Test]
public void generics_4()
{
RunCompilerTestCase(@"generics-4.boo");
}
[Test]
public void generics_5()
{
RunCompilerTestCase(@"generics-5.boo");
}
[Test]
public void getset_1()
{
RunCompilerTestCase(@"getset-1.boo");
}
[Test]
public void goto_1()
{
RunCompilerTestCase(@"goto-1.boo");
}
[Test]
public void goto_2()
{
RunCompilerTestCase(@"goto-2.boo");
}
[Test]
public void hash_1()
{
RunCompilerTestCase(@"hash-1.boo");
}
[Test]
public void hash_initializer()
{
RunCompilerTestCase(@"hash-initializer.boo");
}
[Test]
public void iif_1()
{
RunCompilerTestCase(@"iif-1.boo");
}
[Test]
public void import_1()
{
RunCompilerTestCase(@"import-1.boo");
}
[Test]
public void import_2()
{
RunCompilerTestCase(@"import-2.boo");
}
[Test]
public void in_not_in_1()
{
RunCompilerTestCase(@"in-not-in-1.boo");
}
[Test]
public void in_not_in_2()
{
RunCompilerTestCase(@"in-not-in-2.boo");
}
[Test]
public void in_not_in_3()
{
RunCompilerTestCase(@"in-not-in-3.boo");
}
[Test]
public void inplace_1()
{
RunCompilerTestCase(@"inplace-1.boo");
}
[Test]
public void internal_generic_callable_type_1()
{
RunCompilerTestCase(@"internal-generic-callable-type-1.boo");
}
[Test]
public void internal_generic_type_1()
{
RunCompilerTestCase(@"internal-generic-type-1.boo");
}
[Test]
public void internal_generic_type_2()
{
RunCompilerTestCase(@"internal-generic-type-2.boo");
}
[Test]
public void internal_generic_type_3()
{
RunCompilerTestCase(@"internal-generic-type-3.boo");
}
[Test]
public void internal_generic_type_4()
{
RunCompilerTestCase(@"internal-generic-type-4.boo");
}
[Test]
public void internal_generic_type_5()
{
RunCompilerTestCase(@"internal-generic-type-5.boo");
}
[Test]
public void internal_generic_type_6()
{
RunCompilerTestCase(@"internal-generic-type-6.boo");
}
[Test]
public void interpolation_1()
{
RunCompilerTestCase(@"interpolation-1.boo");
}
[Test]
public void interpolation_2()
{
RunCompilerTestCase(@"interpolation-2.boo");
}
[Test]
public void interpolation_3()
{
RunCompilerTestCase(@"interpolation-3.boo");
}
[Test]
public void interpolation_4()
{
RunCompilerTestCase(@"interpolation-4.boo");
}
[Test]
public void invocation_1()
{
RunCompilerTestCase(@"invocation-1.boo");
}
[Test]
public void isa_1()
{
RunCompilerTestCase(@"isa-1.boo");
}
[Test]
public void keywords_as_members_1()
{
RunCompilerTestCase(@"keywords-as-members-1.boo");
}
[Test]
public void line_continuation_1()
{
RunCompilerTestCase(@"line-continuation-1.boo");
}
[Test]
public void list_1()
{
RunCompilerTestCase(@"list-1.boo");
}
[Test]
public void long_literals_1()
{
RunCompilerTestCase(@"long-literals-1.boo");
}
[Test]
public void macro_doc()
{
RunCompilerTestCase(@"macro-doc.boo");
}
[Test]
public void macros_1()
{
RunCompilerTestCase(@"macros-1.boo");
}
[Test]
public void macros_2()
{
RunCompilerTestCase(@"macros-2.boo");
}
[Test]
public void macros_3()
{
RunCompilerTestCase(@"macros-3.boo");
}
[Test]
public void macros_anywhere_1()
{
RunCompilerTestCase(@"macros-anywhere-1.boo");
}
[Test]
public void method_declaration_in_macro_application()
{
RunCompilerTestCase(@"method-declaration-in-macro-application.boo");
}
[Test]
public void method_declarations_in_nested_macro_application()
{
RunCompilerTestCase(@"method-declarations-in-nested-macro-application.boo");
}
[Test]
public void module_1()
{
RunCompilerTestCase(@"module-1.boo");
}
[Test]
public void module_2()
{
RunCompilerTestCase(@"module-2.boo");
}
[Test]
public void module_3()
{
RunCompilerTestCase(@"module-3.boo");
}
[Test]
public void named_arguments_1()
{
RunCompilerTestCase(@"named-arguments-1.boo");
}
[Test]
public void named_arguments_2()
{
RunCompilerTestCase(@"named-arguments-2.boo");
}
[Test]
public void new_1()
{
RunCompilerTestCase(@"new-1.boo");
}
[Test]
public void not_1()
{
RunCompilerTestCase(@"not-1.boo");
}
[Test]
public void not_2()
{
RunCompilerTestCase(@"not-2.boo");
}
[Test]
public void null_1()
{
RunCompilerTestCase(@"null-1.boo");
}
[Test]
public void omitted_member_target_1()
{
RunCompilerTestCase(@"omitted-member-target-1.boo");
}
[Test]
public void ones_complement_1()
{
RunCompilerTestCase(@"ones-complement-1.boo");
}
[Test]
public void regex_literals_1()
{
RunCompilerTestCase(@"regex-literals-1.boo");
}
[Test]
public void regex_literals_2()
{
RunCompilerTestCase(@"regex-literals-2.boo");
}
[Test]
public void return_1()
{
RunCompilerTestCase(@"return-1.boo");
}
[Test]
public void return_2()
{
RunCompilerTestCase(@"return-2.boo");
}
[Test]
public void self_1()
{
RunCompilerTestCase(@"self-1.boo");
}
[Test]
public void semicolons_1()
{
RunCompilerTestCase(@"semicolons-1.boo");
}
[Test]
public void slicing_1()
{
RunCompilerTestCase(@"slicing-1.boo");
}
[Test]
public void slicing_2()
{
RunCompilerTestCase(@"slicing-2.boo");
}
[Test]
public void splicing_1()
{
RunCompilerTestCase(@"splicing-1.boo");
}
[Test]
public void splicing_class_body()
{
RunCompilerTestCase(@"splicing-class-body.boo");
}
[Test]
public void splicing_enum_body()
{
RunCompilerTestCase(@"splicing-enum-body.boo");
}
[Test]
public void string_literals_1()
{
RunCompilerTestCase(@"string-literals-1.boo");
}
[Test]
public void struct_1()
{
RunCompilerTestCase(@"struct-1.boo");
}
[Test]
public void timespan_literals_1()
{
RunCompilerTestCase(@"timespan-literals-1.boo");
}
[Test]
public void try_1()
{
RunCompilerTestCase(@"try-1.boo");
}
[Test]
public void try_2()
{
RunCompilerTestCase(@"try-2.boo");
}
[Test]
public void type_references_1()
{
RunCompilerTestCase(@"type-references-1.boo");
}
[Test]
public void unless_1()
{
RunCompilerTestCase(@"unless-1.boo");
}
[Test]
public void varargs_1()
{
RunCompilerTestCase(@"varargs-1.boo");
}
[Test]
public void while_or_1()
{
RunCompilerTestCase(@"while_or-1.boo");
}
[Test]
public void while_or_then_1()
{
RunCompilerTestCase(@"while_or_then-1.boo");
}
[Test]
public void while_then_1()
{
RunCompilerTestCase(@"while_then-1.boo");
}
[Test]
public void xor_1()
{
RunCompilerTestCase(@"xor-1.boo");
}
[Test]
public void yield_1()
{
RunCompilerTestCase(@"yield-1.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "parser/roundtrip";
}
}
}
| |
namespace Ioke.Lang.Parser
{
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Ioke.Lang;
using Ioke.Lang.Util;
public class IokeParser
{
internal readonly Runtime runtime;
internal readonly TextReader reader;
internal readonly IokeObject context;
internal readonly IokeObject message;
internal ChainContext top = new ChainContext(null);
internal readonly Dictionary<string, Operators.OpEntry> operatorTable = new SaneDictionary<string, Operators.OpEntry>();
internal readonly Dictionary<string, Operators.OpArity> trinaryOperatorTable = new SaneDictionary<string, Operators.OpArity>();
internal readonly Dictionary<string, Operators.OpEntry> invertedOperatorTable = new SaneDictionary<string, Operators.OpEntry>();
internal readonly ICollection<string> unaryOperators = Operators.DEFAULT_UNARY_OPERATORS;
internal readonly ICollection<string> onlyUnaryOperators = Operators.DEFAULT_ONLY_UNARY_OPERATORS;
public IokeParser(Runtime runtime, TextReader reader, IokeObject context, IokeObject message) {
this.runtime = runtime;
this.reader = reader;
this.context = context;
this.message = message;
Operators.CreateOrGetOpTables(this);
}
public IokeObject ParseFully() {
IokeObject result = ParseMessageChain();
return result;
}
private IokeObject ParseMessageChain() {
top = new ChainContext(top);
while(ParseMessage());
top.PopOperatorsTo(999999);
IokeObject ret = top.Pop();
top = top.parent;
return ret;
}
private IList ParseCommaSeparatedMessageChains() {
ArrayList chain = new SaneArrayList();
IokeObject curr = ParseMessageChain();
while(curr != null) {
chain.Add(curr);
ReadWhiteSpace();
int rr = Peek();
if(rr == ',') {
Read();
curr = ParseMessageChain();
if(curr == null) {
Fail("Expected expression following comma");
}
} else {
if(curr != null && Message.IsTerminator(curr) && Message.GetNext(curr) == null) {
chain.RemoveAt(chain.Count-1);
}
curr = null;
}
}
return chain;
}
private int lineNumber = 1;
private int currentCharacter = -1;
private bool skipLF = false;
private int saved2 = -2;
private int saved = -2;
private int Read() {
if(saved > -2) {
int x = saved;
saved = saved2;
saved2 = -2;
if(skipLF) {
skipLF = false;
if(x == '\n') {
return x;
}
}
currentCharacter++;
switch(x) {
case '\r':
skipLF = true;
goto case '\n';
case '\n': /* Fall through */
lineNumber++;
currentCharacter = 0;
break;
}
return x;
}
int xx = reader.Read();
if(skipLF) {
skipLF = false;
if(xx == '\n') {
return xx;
}
}
currentCharacter++;
switch(xx) {
case '\r':
skipLF = true;
goto case '\n';
case '\n': /* Fall through */
lineNumber++;
currentCharacter = 0;
break;
}
return xx;
}
private int Peek() {
if(saved == -2) {
if(saved2 != -2) {
saved = saved2;
saved2 = -2;
} else {
saved = reader.Read();
}
}
return saved;
}
private int Peek2() {
if(saved == -2) {
saved = reader.Read();
}
if(saved2 == -2) {
saved2 = reader.Read();
}
return saved2;
}
private bool ParseMessage() {
int rr;
while(true) {
rr = Peek();
switch(rr) {
case -1:
Read();
return false;
case ',':
goto case '}';
case ')':
goto case '}';
case ']':
goto case '}';
case '}':
return false;
case '(':
Read();
ParseEmptyMessageSend();
return true;
case '[':
Read();
ParseOpenCloseMessageSend(']', "[]");
return true;
case '{':
Read();
ParseOpenCloseMessageSend('}', "{}");
return true;
case '#':
Read();
switch(Peek()) {
case '{':
ParseSimpleOpenCloseMessageSend('}', "set");
return true;
case '/':
ParseRegexpLiteral('/');
return true;
case '[':
ParseText('[');
return true;
case 'r':
ParseRegexpLiteral('r');
return true;
case '!':
ParseComment();
break;
default:
ParseOperatorChars('#');
return true;
}
break;
case '"':
Read();
ParseText('"');
return true;
case '0':
goto case '9';
case '1':
goto case '9';
case '2':
goto case '9';
case '3':
goto case '9';
case '4':
goto case '9';
case '5':
goto case '9';
case '6':
goto case '9';
case '7':
goto case '9';
case '8':
goto case '9';
case '9':
Read();
ParseNumber(rr);
return true;
case '.':
Read();
if((rr = Peek()) == '.') {
ParseRange();
} else {
ParseTerminator('.');
}
return true;
case ';':
Read();
ParseComment();
break;
case ' ':
goto case '\u000c';
case '\u0009':
goto case '\u000c';
case '\u000b':
goto case '\u000c';
case '\u000c':
Read();
ReadWhiteSpace();
break;
case '\\':
Read();
if((rr = Peek()) == '\n') {
Read();
break;
} else {
Fail("Expected newline after free-floating escape character");
break;
}
case '\r':
goto case '\n';
case '\n':
Read();
ParseTerminator(rr);
return true;
case '+':
goto case '/';
case '-':
goto case '/';
case '*':
goto case '/';
case '%':
goto case '/';
case '<':
goto case '/';
case '>':
goto case '/';
case '!':
goto case '/';
case '?':
goto case '/';
case '~':
goto case '/';
case '&':
goto case '/';
case '|':
goto case '/';
case '^':
goto case '/';
case '$':
goto case '/';
case '=':
goto case '/';
case '@':
goto case '/';
case '\'':
goto case '/';
case '`':
goto case '/';
case '/':
Read();
ParseOperatorChars(rr);
return true;
case ':':
Read();
if(IsLetter(rr = Peek()) || IsIDDigit(rr)) {
ParseRegularMessageSend(':');
} else {
ParseOperatorChars(':');
}
return true;
default:
Read();
ParseRegularMessageSend(rr);
return true;
}
}
}
private void Fail(int l, int c, string message, string expected, string got) {
string file = ((IokeSystem)IokeObject.dataOf(runtime.System)).CurrentFile;
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition,
this.message,
this.context,
"Error",
"Parser",
"Syntax"), this.context).Mimic(this.message, this.context);
condition.SetCell("message", this.message);
condition.SetCell("context", this.context);
condition.SetCell("receiver", this.context);
if(expected != null) {
condition.SetCell("expected", runtime.NewText(expected));
}
if(got != null) {
condition.SetCell("got", runtime.NewText(got));
}
condition.SetCell("file", runtime.NewText(file));
condition.SetCell("line", runtime.NewNumber(l));
condition.SetCell("character", runtime.NewNumber(c));
condition.SetCell("text", runtime.NewText(file + ":" + l + ":" + c + ": " + message));
runtime.ErrorCondition(condition);
}
private void Fail(string message) {
Fail(lineNumber, currentCharacter, message, null, null);
}
private void ParseCharacter(int c) {
int l = lineNumber;
int cc = currentCharacter;
ReadWhiteSpace();
int rr = Read();
if(rr != c) {
Fail(l, cc, "Expected: '" + (char)c + "' got: " + CharDesc(rr), "" + (char)c, CharDesc(rr));
}
}
private bool IsUnary(string name) {
return unaryOperators.Contains(name) && (top.head == null || Message.IsTerminator(top.last));
}
private static int PossibleOperatorPrecedence(string name) {
if(name.Length > 0) {
switch(name[0]) {
case '|':
return 9;
case '^':
return 8;
case '&':
return 7;
case '<':
return 5;
case '>':
return 5;
case '=':
return 6;
case '!':
return 6;
case '?':
return 6;
case '~':
return 6;
case '$':
return 6;
case '+':
return 3;
case '-':
return 3;
case '*':
return 2;
case '/':
return 2;
case '%':
return 2;
}
}
return -1;
}
private void PossibleOperator(IokeObject mx) {
string name = Message.GetName(mx);
if(IsUnary(name) || onlyUnaryOperators.Contains(name)) {
top.Add(mx);
top.Push(-1, mx, Level.Type.UNARY);
return;
}
if(operatorTable.ContainsKey(name)) {
var op = operatorTable[name];
top.PopOperatorsTo(op.precedence);
top.Add(mx);
top.Push(op.precedence, mx, Level.Type.REGULAR);
} else {
if(trinaryOperatorTable.ContainsKey(name)) {
var opa = trinaryOperatorTable[name];
if(opa.arity == 2) {
IokeObject last = top.PrepareAssignmentMessage();
mx.Arguments.Add(last);
top.Add(mx);
top.Push(13, mx, Level.Type.ASSIGNMENT);
} else {
IokeObject last = top.PrepareAssignmentMessage();
mx.Arguments.Add(last);
top.Add(mx);
}
} else {
if(invertedOperatorTable.ContainsKey(name)) {
var op = invertedOperatorTable[name];
top.PopOperatorsTo(op.precedence);
top.Add(mx);
top.Push(op.precedence, mx, Level.Type.INVERTED);
} else {
int possible = PossibleOperatorPrecedence(name);
if(possible != -1) {
top.PopOperatorsTo(possible);
top.Add(mx);
top.Push(possible, mx, Level.Type.REGULAR);
} else {
top.Add(mx);
}
}
}
}
}
private void ParseEmptyMessageSend() {
int l = lineNumber; int cc = currentCharacter-1;
IList args = ParseCommaSeparatedMessageChains();
ParseCharacter(')');
Message m = new Message(runtime, "");
m.Line = l;
m.Position = cc;
IokeObject mx = runtime.CreateMessage(m);
Message.SetArguments(mx, args);
top.Add(mx);
}
private void ParseOpenCloseMessageSend(char end, string name) {
int l = lineNumber; int cc = currentCharacter-1;
int rr = Peek();
int r2 = Peek2();
Message m = new Message(runtime, name);
m.Line = l;
m.Position = cc;
IokeObject mx = runtime.CreateMessage(m);
if(rr == end && r2 == '(') {
Read();
Read();
IList args = ParseCommaSeparatedMessageChains();
ParseCharacter(')');
Message.SetArguments(mx, args);
} else {
IList args = ParseCommaSeparatedMessageChains();
ParseCharacter(end);
Message.SetArguments(mx, args);
}
top.Add(mx);
}
private void ParseSimpleOpenCloseMessageSend(char end, string name) {
int l = lineNumber; int cc = currentCharacter-1;
Read();
IList args = ParseCommaSeparatedMessageChains();
ParseCharacter(end);
Message m = new Message(runtime, name);
m.Line = l;
m.Position = cc;
IokeObject mx = runtime.CreateMessage(m);
Message.SetArguments(mx, args);
top.Add(mx);
}
private void ParseComment() {
int rr;
while((rr = Peek()) != '\n' && rr != '\r' && rr != -1) {
Read();
}
}
private readonly static string[] RANGES = {
"",
".",
"..",
"...",
"....",
".....",
"......",
".......",
"........",
".........",
"..........",
"...........",
"............"
};
private void ParseRange() {
int l = lineNumber; int cc = currentCharacter-1;
int count = 2;
Read();
int rr;
while((rr = Peek()) == '.') {
count++;
Read();
}
string result = null;
if(count < 13) {
result = RANGES[count];
} else {
StringBuilder sb = new StringBuilder();
for(int i = 0; i<count; i++) {
sb.Append('.');
}
result = sb.ToString();
}
Message m = new Message(runtime, result);
m.Line = l;
m.Position = cc;
IokeObject mx = runtime.CreateMessage(m);
if(rr == '(') {
Read();
IList args = ParseCommaSeparatedMessageChains();
ParseCharacter(')');
Message.SetArguments(mx, args);
top.Add(mx);
} else {
PossibleOperator(mx);
}
}
private void ParseTerminator(int indicator) {
int l = lineNumber; int cc = currentCharacter-1;
int rr;
int rr2;
if(indicator == '\r') {
rr = Peek();
if(rr == '\n') {
Read();
}
}
while(true) {
rr = Peek();
rr2 = Peek2();
if((rr == '.' && rr2 != '.') ||
(rr == '\n')) {
Read();
} else if(rr == '\r' && rr2 == '\n') {
Read(); Read();
} else {
break;
}
}
if(!(top.last == null && top.currentLevel.operatorMessage != null)) {
top.PopOperatorsTo(999999);
}
Message m = new Message(runtime, ".", null, true);
m.Line = l;
m.Position = cc;
top.Add(runtime.CreateMessage(m));
}
private void ReadWhiteSpace() {
int rr;
while((rr = Peek()) == ' ' ||
rr == '\u0009' ||
rr == '\u000b' ||
rr == '\u000c') {
Read();
}
}
private void ParseRegexpLiteral(int indicator) {
StringBuilder sb = new StringBuilder();
bool slash = indicator == '/';
int l = lineNumber; int cc = currentCharacter-1;
Read();
if(!slash) {
ParseCharacter('[');
}
int rr;
string name = "internal:createRegexp";
ArrayList args = new SaneArrayList();
while(true) {
switch(rr = Peek()) {
case -1:
Fail("Expected end of regular expression, found EOF");
break;
case '/':
Read();
if(slash) {
args.Add(sb.ToString());
Message m = new Message(runtime, "internal:createRegexp");
m.Line = l;
m.Position = cc;
IokeObject mm = runtime.CreateMessage(m);
if(!name.Equals("internal:createRegexp")) {
Message.SetName(mm, name);
}
Message.SetArguments(mm, args);
sb = new StringBuilder();
while(true) {
switch(rr = Peek()) {
case 'x': goto case 's';
case 'i': goto case 's';
case 'u': goto case 's';
case 'm': goto case 's';
case 's':
Read();
sb.Append((char)rr);
break;
default:
args.Add(sb.ToString());
top.Add(mm);
return;
}
}
} else {
sb.Append((char)rr);
}
break;
case ']':
Read();
if(!slash) {
args.Add(sb.ToString());
Message m = new Message(runtime, "internal:createRegexp");
m.Line = l;
m.Position = cc;
IokeObject mm = runtime.CreateMessage(m);
if(!name.Equals("internal:createRegexp")) {
Message.SetName(mm, name);
}
Message.SetArguments(mm, args);
sb = new StringBuilder();
while(true) {
switch(rr = Peek()) {
case 'x': goto case 's';
case 'i': goto case 's';
case 'u': goto case 's';
case 'm': goto case 's';
case 's':
Read();
sb.Append((char)rr);
break;
default:
args.Add(sb.ToString());
top.Add(mm);
return;
}
}
} else {
sb.Append((char)rr);
}
break;
case '#':
Read();
if((rr = Peek()) == '{') {
Read();
args.Add(sb.ToString());
sb = new StringBuilder();
name = "internal:compositeRegexp";
args.Add(ParseMessageChain());
ReadWhiteSpace();
ParseCharacter('}');
} else {
sb.Append((char)'#');
}
break;
case '\\':
Read();
ParseRegexpEscape(sb);
break;
default:
Read();
sb.Append((char)rr);
break;
}
}
}
private void ParseText(int indicator) {
StringBuilder sb = new StringBuilder();
bool dquote = indicator == '"';
int l = lineNumber; int cc = currentCharacter-1;
if(!dquote) {
Read();
}
int rr;
string name = "internal:createText";
ArrayList args = new SaneArrayList();
while(true) {
switch(rr = Peek()) {
case -1:
Fail("Expected end of text, found EOF");
break;
case '"':
Read();
if(dquote) {
args.Add(sb.ToString());
Message m = new Message(runtime, "internal:createText");
m.Line = l;
m.Position = cc;
IokeObject mm = runtime.CreateMessage(m);
if(!name.Equals("internal:createText")) {
for(int i = 0; i<args.Count; i++) {
object o = args[i];
if(o is string) {
Message mx = new Message(runtime, "internal:createText", o);
mx.Line = l;
mx.Position = cc;
IokeObject mmx = runtime.CreateMessage(mx);
args[i] = mmx;
}
}
Message.SetName(mm, name);
}
Message.SetArguments(mm, args);
top.Add(mm);
return;
} else {
sb.Append((char)rr);
}
break;
case ']':
Read();
if(!dquote) {
args.Add(sb.ToString());
Message m = new Message(runtime, "internal:createText");
m.Line = l;
m.Position = cc;
IokeObject mm = runtime.CreateMessage(m);
if(!name.Equals("internal:createText")) {
for(int i = 0; i<args.Count; i++) {
object o = args[i];
if(o is string) {
Message mx = new Message(runtime, "internal:createText", o);
mx.Line = l;
mx.Position = cc;
IokeObject mmx = runtime.CreateMessage(mx);
args[i] = mmx;
}
}
Message.SetName(mm, name);
}
Message.SetArguments(mm, args);
top.Add(mm);
return;
} else {
sb.Append((char)rr);
}
break;
case '#':
Read();
if((rr = Peek()) == '{') {
Read();
args.Add(sb.ToString());
sb = new StringBuilder();
name = "internal:concatenateText";
args.Add(ParseMessageChain());
ReadWhiteSpace();
ParseCharacter('}');
} else {
sb.Append((char)'#');
}
break;
case '\\':
Read();
ParseDoubleQuoteEscape(sb);
break;
default:
Read();
sb.Append((char)rr);
break;
}
}
}
private void ParseRegexpEscape(StringBuilder sb) {
sb.Append('\\');
int rr = Peek();
switch(rr) {
case 'u':
Read();
sb.Append((char)rr);
for(int i = 0; i < 4; i++) {
rr = Peek();
if((rr >= '0' && rr <= '9') ||
(rr >= 'a' && rr <= 'f') ||
(rr >= 'A' && rr <= 'F')) {
Read();
sb.Append((char)rr);
} else {
Fail("Expected four hexadecimal characters in unicode escape - got: " + CharDesc(rr));
}
}
break;
case '0': goto case '7';
case '1': goto case '7';
case '2': goto case '7';
case '3': goto case '7';
case '4': goto case '7';
case '5': goto case '7';
case '6': goto case '7';
case '7':
Read();
sb.Append((char)rr);
if(rr <= '3') {
rr = Peek();
if(rr >= '0' && rr <= '7') {
Read();
sb.Append((char)rr);
rr = Peek();
if(rr >= '0' && rr <= '7') {
Read();
sb.Append((char)rr);
}
}
} else {
rr = Peek();
if(rr >= '0' && rr <= '7') {
Read();
sb.Append((char)rr);
}
}
break;
case 't': goto case '|';
case 'n': goto case '|';
case 'f': goto case '|';
case 'r': goto case '|';
case '/': goto case '|';
case '\\': goto case '|';
case '\n': goto case '|';
case '#': goto case '|';
case 'A': goto case '|';
case 'd': goto case '|';
case 'D': goto case '|';
case 's': goto case '|';
case 'S': goto case '|';
case 'w': goto case '|';
case 'W': goto case '|';
case 'b': goto case '|';
case 'B': goto case '|';
case 'z': goto case '|';
case 'Z': goto case '|';
case '<': goto case '|';
case '>': goto case '|';
case 'G': goto case '|';
case 'p': goto case '|';
case 'P': goto case '|';
case '{': goto case '|';
case '}': goto case '|';
case '[': goto case '|';
case ']': goto case '|';
case '*': goto case '|';
case '(': goto case '|';
case ')': goto case '|';
case '$': goto case '|';
case '^': goto case '|';
case '+': goto case '|';
case '?': goto case '|';
case '.': goto case '|';
case '|':
Read();
sb.Append((char)rr);
break;
case '\r':
Read();
sb.Append((char)rr);
if((rr = Peek()) == '\n') {
Read();
sb.Append((char)rr);
}
break;
default:
Fail("Undefined regular expression escape character: " + CharDesc(rr));
break;
}
}
private void ParseDoubleQuoteEscape(StringBuilder sb) {
sb.Append('\\');
int rr = Peek();
switch(rr) {
case 'u':
Read();
sb.Append((char)rr);
for(int i = 0; i < 4; i++) {
rr = Peek();
if((rr >= '0' && rr <= '9') ||
(rr >= 'a' && rr <= 'f') ||
(rr >= 'A' && rr <= 'F')) {
Read();
sb.Append((char)rr);
} else {
Fail("Expected four hexadecimal characters in unicode escape - got: " + CharDesc(rr));
}
}
break;
case '0': goto case '7';
case '1': goto case '7';
case '2': goto case '7';
case '3': goto case '7';
case '4': goto case '7';
case '5': goto case '7';
case '6': goto case '7';
case '7':
Read();
sb.Append((char)rr);
if(rr <= '3') {
rr = Peek();
if(rr >= '0' && rr <= '7') {
Read();
sb.Append((char)rr);
rr = Peek();
if(rr >= '0' && rr <= '7') {
Read();
sb.Append((char)rr);
}
}
} else {
rr = Peek();
if(rr >= '0' && rr <= '7') {
Read();
sb.Append((char)rr);
}
}
break;
case 'b': goto case 'e';
case 't': goto case 'e';
case 'n': goto case 'e';
case 'f': goto case 'e';
case 'r': goto case 'e';
case '"': goto case 'e';
case ']': goto case 'e';
case '\\': goto case 'e';
case '\n': goto case 'e';
case '#': goto case 'e';
case 'e':
Read();
sb.Append((char)rr);
break;
case '\r':
Read();
sb.Append((char)rr);
if((rr = Peek()) == '\n') {
Read();
sb.Append((char)rr);
}
break;
default:
Fail("Undefined text escape character: " + CharDesc(rr));
break;
}
}
private void ParseOperatorChars(int indicator) {
int l = lineNumber; int cc = currentCharacter-1;
StringBuilder sb = new StringBuilder();
sb.Append((char)indicator);
int rr;
while(true) {
rr = Peek();
switch(rr) {
case '+': goto case '#';
case '-': goto case '#';
case '*': goto case '#';
case '%': goto case '#';
case '<': goto case '#';
case '>': goto case '#';
case '!': goto case '#';
case '?': goto case '#';
case '~': goto case '#';
case '&': goto case '#';
case '|': goto case '#';
case '^': goto case '#';
case '$': goto case '#';
case '=': goto case '#';
case '@': goto case '#';
case '\'': goto case '#';
case '`': goto case '#';
case ':': goto case '#';
case '#':
Read();
sb.Append((char)rr);
break;
case '/':
if(indicator != '#') {
Read();
sb.Append((char)rr);
break;
}
goto default;
default:
Message m = new Message(runtime, sb.ToString());
m.Line = l;
m.Position = cc;
IokeObject mx = runtime.CreateMessage(m);
if(rr == '(') {
Read();
IList args = ParseCommaSeparatedMessageChains();
ParseCharacter(')');
Message.SetArguments(mx, args);
top.Add(mx);
} else {
PossibleOperator(mx);
}
return;
}
}
}
private void ParseNumber(int indicator) {
int l = lineNumber; int cc = currentCharacter-1;
bool dcimal = false;
StringBuilder sb = new StringBuilder();
sb.Append((char)indicator);
int rr = -1;
if(indicator == '0') {
rr = Peek();
if(rr == 'x' || rr == 'X') {
Read();
sb.Append((char)rr);
rr = Peek();
if((rr >= '0' && rr <= '9') ||
(rr >= 'a' && rr <= 'f') ||
(rr >= 'A' && rr <= 'F')) {
Read();
sb.Append((char)rr);
rr = Peek();
while((rr >= '0' && rr <= '9') ||
(rr >= 'a' && rr <= 'f') ||
(rr >= 'A' && rr <= 'F')) {
Read();
sb.Append((char)rr);
rr = Peek();
}
} else {
Fail("Expected at least one hexadecimal characters in hexadcimal number literal - got: " + CharDesc(rr));
}
} else {
int r2 = Peek2();
if(rr == '.' && (r2 >= '0' && r2 <= '9')) {
dcimal = true;
sb.Append((char)rr);
sb.Append((char)r2);
Read(); Read();
while((rr = Peek()) >= '0' && rr <= '9') {
Read();
sb.Append((char)rr);
}
if(rr == 'e' || rr == 'E') {
Read();
sb.Append((char)rr);
if((rr = Peek()) == '-' || rr == '+') {
Read();
sb.Append((char)rr);
rr = Peek();
}
if(rr >= '0' && rr <= '9') {
Read();
sb.Append((char)rr);
while((rr = Peek()) >= '0' && rr <= '9') {
Read();
sb.Append((char)rr);
}
} else {
Fail("Expected at least one decimal character following exponent specifier in number literal - got: " + CharDesc(rr));
}
}
}
}
} else {
while((rr = Peek()) >= '0' && rr <= '9') {
Read();
sb.Append((char)rr);
}
int r2 = Peek2();
if(rr == '.' && r2 >= '0' && r2 <= '9') {
dcimal = true;
sb.Append((char)rr);
sb.Append((char)r2);
Read(); Read();
while((rr = Peek()) >= '0' && rr <= '9') {
Read();
sb.Append((char)rr);
}
if(rr == 'e' || rr == 'E') {
Read();
sb.Append((char)rr);
if((rr = Peek()) == '-' || rr == '+') {
Read();
sb.Append((char)rr);
rr = Peek();
}
if(rr >= '0' && rr <= '9') {
Read();
sb.Append((char)rr);
while((rr = Peek()) >= '0' && rr <= '9') {
Read();
sb.Append((char)rr);
}
} else {
Fail("Expected at least one decimal character following exponent specifier in number literal - got: " + CharDesc(rr));
}
}
} else if(rr == 'e' || rr == 'E') {
dcimal = true;
Read();
sb.Append((char)rr);
if((rr = Peek()) == '-' || rr == '+') {
Read();
sb.Append((char)rr);
rr = Peek();
}
if(rr >= '0' && rr <= '9') {
Read();
sb.Append((char)rr);
while((rr = Peek()) >= '0' && rr <= '9') {
Read();
sb.Append((char)rr);
}
} else {
Fail("Expected at least one decimal character following exponent specifier in number literal - got: " + CharDesc(rr));
}
}
}
// TODO: add unit specifier here
Message m = dcimal ? new Message(runtime, "internal:createDecimal", sb.ToString()) : new Message(runtime, "internal:createNumber", sb.ToString());
m.Line = l;
m.Position = cc;
top.Add(runtime.CreateMessage(m));
}
private void ParseRegularMessageSend(int indicator) {
int l = lineNumber; int cc = currentCharacter-1;
StringBuilder sb = new StringBuilder();
sb.Append((char)indicator);
int rr = -1;
while(IsLetter(rr = Peek()) || IsIDDigit(rr) || rr == ':' || rr == '!' || rr == '?' || rr == '$') {
Read();
sb.Append((char)rr);
}
Message m = new Message(runtime, sb.ToString());
m.Line = l;
m.Position = cc;
IokeObject mx = runtime.CreateMessage(m);
if(rr == '(') {
Read();
IList args = ParseCommaSeparatedMessageChains();
ParseCharacter(')');
Message.SetArguments(mx, args);
top.Add(mx);
} else {
PossibleOperator(mx);
}
}
private bool IsLetter(int c) {
return ((c>='A' && c<='Z') ||
c=='_' ||
(c>='a' && c<='z') ||
(c>='\u00C0' && c<='\u00D6') ||
(c>='\u00D8' && c<='\u00F6') ||
(c>='\u00F8' && c<='\u1FFF') ||
(c>='\u2200' && c<='\u22FF') ||
(c>='\u27C0' && c<='\u27EF') ||
(c>='\u2980' && c<='\u2AFF') ||
(c>='\u3040' && c<='\u318F') ||
(c>='\u3300' && c<='\u337F') ||
(c>='\u3400' && c<='\u3D2D') ||
(c>='\u4E00' && c<='\u9FFF') ||
(c>='\uF900' && c<='\uFAFF'));
}
private bool IsIDDigit(int c) {
return ((c>='0' && c<='9') ||
(c>='\u0660' && c<='\u0669') ||
(c>='\u06F0' && c<='\u06F9') ||
(c>='\u0966' && c<='\u096F') ||
(c>='\u09E6' && c<='\u09EF') ||
(c>='\u0A66' && c<='\u0A6F') ||
(c>='\u0AE6' && c<='\u0AEF') ||
(c>='\u0B66' && c<='\u0B6F') ||
(c>='\u0BE7' && c<='\u0BEF') ||
(c>='\u0C66' && c<='\u0C6F') ||
(c>='\u0CE6' && c<='\u0CEF') ||
(c>='\u0D66' && c<='\u0D6F') ||
(c>='\u0E50' && c<='\u0E59') ||
(c>='\u0ED0' && c<='\u0ED9') ||
(c>='\u1040' && c<='\u1049'));
}
private static string CharDesc(int c) {
if(c == -1) {
return "EOF";
} else if(c == 9) {
return "TAB";
} else if(c == 10 || c == 13) {
return "EOL";
} else {
return "'" + (char)c + "'";
}
}
}
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.IO;
using System.Drawing.Printing;
using System.Data.OleDb;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
using PCSComMaterials.Plan.DS;
using PCSComProcurement.Purchase.BO;
using PCSComProcurement.Purchase.DS;
using PCSComProduct.Items.DS;
using PCSComUtils.DataAccess;
using PCSComUtils.MasterSetup.DS;
using PCSComUtils.Framework.ReportFrame.BO;
using PCSUtils.Framework.ReportFrame;
using AddNewModeEnum = C1.Win.C1TrueDBGrid.AddNewModeEnum;
using AlignHorzEnum = C1.Win.C1TrueDBGrid.AlignHorzEnum;
using C1DataColumn = C1.Win.C1TrueDBGrid.C1DataColumn;
using C1DisplayColumn = C1.Win.C1TrueDBGrid.C1DisplayColumn;
using PresentationEnum = C1.Win.C1TrueDBGrid.PresentationEnum;
using C1.Win.C1Input;
using C1.Win.C1List;
using C1.C1Report;
using C1.Win.C1Preview;
namespace PCSProcurement.Purchase
{
/// <summary>
/// Summary description for PartOrderSheetMultiVendorReport.
/// </summary>
public class PartOrderSheetMultiVendorReport : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnPrint;
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.Label lblCCN;
private C1.Win.C1List.C1Combo cboCCN;
private System.Windows.Forms.ComboBox cboMonth;
private System.Windows.Forms.Label lblMonth;
private System.Windows.Forms.Label lblYear;
private System.Windows.Forms.ComboBox cboYear;
private System.Windows.Forms.Label lblReportTitle;
private System.Windows.Forms.Button btnVendor;
private System.Windows.Forms.Label lblVendor;
private System.Windows.Forms.TextBox txtVendor;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
#region My variables
const string THIS = "PCSProcurement.Purchase.PartOrderSheetMultiVendorReport";
private const string VENDOR_CUSTOMER_VIEW = "V_VendorCustomer";
private const string VENDOR_VIEW = "V_Vendor";
private const string VENDOR_COLUMN = "Vendor";
const string ZERO_STRING = "0";
const string ISSUE_DATE_FORMAT = "dd-MMM-yyyy";
const string NEXTMONTH_DATE_FORMAT = "MMM-yy";
const string HEADER = "PageHeader";
/// Result Data Table Column name
//const string VENDOR = "Vendor";
const string PARTYID = "PartyID";
const string PARTNO = "Part No.";
const string PARTNAME = "Part Name";
const string CATEGORY = "Category";
const string QUANTITYSET = "QuantitySet";
const string MODEL = "Model";
const string UM = "UM";
const string SCHEDULE_DATE = "ScheduleDate";
const string QUANTITY = "Quantity";
const string ADJUSTMENT = "Adjustment";
const string SUMROWNEXT_O = "SumRowNextO";
const string SUMROWNEXTNEXT_O = "SumRowNextNextO";
const string SUMROWNEXT_A = "SumRowNextA";
const string SUMROWNEXTNEXT_A = "SumRowNextNextA";
const string REPORT_LAYOUT_FILE = "PartOrderSheetMultiVendorReport.xml";
const string REPORT_NAME = "PartOrderSheetReport";
const string REPORTFLD_TITLE = "fldTitle";
const string REPORTFLD_COMPANY = "fldCompany";
const string REPORTFLD_ADDRESS = "fldAddress";
const string REPORTFLD_TEL = "fldTel";
const string REPORTFLD_FAX = "fldFax";
const string REPORTFLD_ISSUE_DATE = "fldIssueDate";
const string REPORTFLD_SUMROW_NEXT = "lblSumRowNext";
const string REPORTFLD_SUMROW_NEXTNEXT = "lblSumRowNextNext";
const string REPORTFLD_ORDER_MONTH = "fldMonth";
const string REPORTFLD_ATTENTION = "fldAttention";
const string REPORTFLD_REVISION = "fldRevision";
const string COL_ORDER_PREFIX = "D";
const string COL_ADJUSTMENT_PREFIX = "A";
#region Constants
/// Result Data Table Column name
const string VENDOR = "Vendor";
const string SUMROWNEXT = "SumRowNext";
const string SUMROWNEXTNEXT = "SumRowNextNext";
const string REPORTFLD_PARAMETER_MONTH = "fldParameterMonth";
const string REPORTFLD_PARAMETER_YEAR = "fldParameterYear";
const string REPORTFLD_PARAMETER_VENDOR = "fldParameterVendor";
const string REPORTFLD_PARAMETER_CCN = "fldParameterCCN";
const string COL_PREFIX = "D";
const string PARAM_DELIMINATE = ": ";
#endregion
private PCSComUtils.Framework.ReportFrame.DS.Sys_PrintConfigurationVO mPrintConfigurationVO;
/// <summary>
/// External properties.
/// PrintConfiguration MenuItem Selected function will set the Sys_PrintConfigurationVO here
/// This form will use this Print Config to print the report
/// </summary>
public PCSComUtils.Framework.ReportFrame.DS.Sys_PrintConfigurationVO PrintConfigurationVO
{
get
{
return mPrintConfigurationVO;
}
set
{
mPrintConfigurationVO = value;
}
}
UtilsBO boUtil = new UtilsBO();
#endregion
public PartOrderSheetMultiVendorReport()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnPrint = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.lblCCN = new System.Windows.Forms.Label();
this.cboCCN = new C1.Win.C1List.C1Combo();
this.cboMonth = new System.Windows.Forms.ComboBox();
this.lblMonth = new System.Windows.Forms.Label();
this.lblYear = new System.Windows.Forms.Label();
this.cboYear = new System.Windows.Forms.ComboBox();
this.btnVendor = new System.Windows.Forms.Button();
this.lblVendor = new System.Windows.Forms.Label();
this.txtVendor = new System.Windows.Forms.TextBox();
this.lblReportTitle = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.cboCCN)).BeginInit();
this.SuspendLayout();
//
// btnPrint
//
this.btnPrint.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnPrint.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnPrint.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnPrint.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnPrint.Location = new System.Drawing.Point(4, 92);
this.btnPrint.Name = "btnPrint";
this.btnPrint.Size = new System.Drawing.Size(60, 23);
this.btnPrint.TabIndex = 9;
this.btnPrint.Text = "&Execute";
this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
//
// btnHelp
//
this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnHelp.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnHelp.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnHelp.Location = new System.Drawing.Point(264, 92);
this.btnHelp.Name = "btnHelp";
this.btnHelp.Size = new System.Drawing.Size(60, 23);
this.btnHelp.TabIndex = 10;
this.btnHelp.Text = "&Help";
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.Location = new System.Drawing.Point(326, 92);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(60, 23);
this.btnClose.TabIndex = 11;
this.btnClose.Text = "&Close";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// lblCCN
//
this.lblCCN.ForeColor = System.Drawing.Color.Maroon;
this.lblCCN.Location = new System.Drawing.Point(264, 6);
this.lblCCN.Name = "lblCCN";
this.lblCCN.Size = new System.Drawing.Size(32, 20);
this.lblCCN.TabIndex = 12;
this.lblCCN.Text = "CCN";
this.lblCCN.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// cboCCN
//
this.cboCCN.AddItemSeparator = ';';
this.cboCCN.Caption = "";
this.cboCCN.CaptionHeight = 17;
this.cboCCN.CharacterCasing = System.Windows.Forms.CharacterCasing.Normal;
this.cboCCN.ColumnCaptionHeight = 17;
this.cboCCN.ColumnFooterHeight = 17;
this.cboCCN.ComboStyle = C1.Win.C1List.ComboStyleEnum.DropdownList;
this.cboCCN.ContentHeight = 15;
this.cboCCN.DeadAreaBackColor = System.Drawing.Color.Empty;
this.cboCCN.EditorBackColor = System.Drawing.SystemColors.Window;
this.cboCCN.EditorFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.cboCCN.EditorForeColor = System.Drawing.SystemColors.WindowText;
this.cboCCN.EditorHeight = 15;
this.cboCCN.FlatStyle = C1.Win.C1List.FlatModeEnum.System;
this.cboCCN.GapHeight = 2;
this.cboCCN.ItemHeight = 15;
this.cboCCN.Location = new System.Drawing.Point(304, 6);
this.cboCCN.MatchEntryTimeout = ((long)(2000));
this.cboCCN.MaxDropDownItems = ((short)(5));
this.cboCCN.MaxLength = 32767;
this.cboCCN.MouseCursor = System.Windows.Forms.Cursors.Default;
this.cboCCN.Name = "cboCCN";
this.cboCCN.RowDivider.Color = System.Drawing.Color.DarkGray;
this.cboCCN.RowDivider.Style = C1.Win.C1List.LineStyleEnum.None;
this.cboCCN.RowSubDividerColor = System.Drawing.Color.DarkGray;
this.cboCCN.Size = new System.Drawing.Size(80, 21);
this.cboCCN.TabIndex = 0;
this.cboCCN.PropBag = "<?xml version=\"1.0\"?><Blob><Styles type=\"C1.Win.C1List.Design.ContextWrapper\"><Da" +
"ta>Group{BackColor:ControlDark;Border:None,,0, 0, 0, 0;AlignVert:Center;}Style2{" +
"}Style5{}Style4{}Style7{}Style6{}EvenRow{BackColor:Aqua;}Selected{ForeColor:High" +
"lightText;BackColor:Highlight;}Style3{}Inactive{ForeColor:InactiveCaptionText;Ba" +
"ckColor:InactiveCaption;}Footer{}Caption{AlignHorz:Center;}Normal{BackColor:Wind" +
"ow;}HighlightRow{ForeColor:HighlightText;BackColor:Highlight;}Style9{AlignHorz:N" +
"ear;}OddRow{}RecordSelector{AlignImage:Center;}Heading{Wrap:True;AlignVert:Cente" +
"r;Border:Raised,,1, 1, 1, 1;ForeColor:ControlText;BackColor:Control;}Style8{}Sty" +
"le10{}Style11{}Style1{}</Data></Styles><Splits><C1.Win.C1List.ListBoxView AllowC" +
"olSelect=\"False\" Name=\"\" CaptionHeight=\"17\" ColumnCaptionHeight=\"17\" ColumnFoote" +
"rHeight=\"17\" VerticalScrollGroup=\"1\" HorizontalScrollGroup=\"1\"><ClientRect>0, 0," +
" 118, 158</ClientRect><VScrollBar><Width>16</Width></VScrollBar><HScrollBar><Hei" +
"ght>16</Height></HScrollBar><CaptionStyle parent=\"Style2\" me=\"Style9\" /><EvenRow" +
"Style parent=\"EvenRow\" me=\"Style7\" /><FooterStyle parent=\"Footer\" me=\"Style3\" />" +
"<GroupStyle parent=\"Group\" me=\"Style11\" /><HeadingStyle parent=\"Heading\" me=\"Sty" +
"le2\" /><HighLightRowStyle parent=\"HighlightRow\" me=\"Style6\" /><InactiveStyle par" +
"ent=\"Inactive\" me=\"Style4\" /><OddRowStyle parent=\"OddRow\" me=\"Style8\" /><RecordS" +
"electorStyle parent=\"RecordSelector\" me=\"Style10\" /><SelectedStyle parent=\"Selec" +
"ted\" me=\"Style5\" /><Style parent=\"Normal\" me=\"Style1\" /></C1.Win.C1List.ListBoxV" +
"iew></Splits><NamedStyles><Style parent=\"\" me=\"Normal\" /><Style parent=\"Normal\" " +
"me=\"Heading\" /><Style parent=\"Heading\" me=\"Footer\" /><Style parent=\"Heading\" me=" +
"\"Caption\" /><Style parent=\"Heading\" me=\"Inactive\" /><Style parent=\"Normal\" me=\"S" +
"elected\" /><Style parent=\"Normal\" me=\"HighlightRow\" /><Style parent=\"Normal\" me=" +
"\"EvenRow\" /><Style parent=\"Normal\" me=\"OddRow\" /><Style parent=\"Heading\" me=\"Rec" +
"ordSelector\" /><Style parent=\"Caption\" me=\"Group\" /></NamedStyles><vertSplits>1<" +
"/vertSplits><horzSplits>1</horzSplits><Layout>Modified</Layout><DefaultRecSelWid" +
"th>16</DefaultRecSelWidth></Blob>";
//
// cboMonth
//
this.cboMonth.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboMonth.ItemHeight = 13;
this.cboMonth.Items.AddRange(new object[] {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"});
this.cboMonth.Location = new System.Drawing.Point(58, 29);
this.cboMonth.Name = "cboMonth";
this.cboMonth.Size = new System.Drawing.Size(82, 21);
this.cboMonth.TabIndex = 2;
//
// lblMonth
//
this.lblMonth.ForeColor = System.Drawing.Color.Maroon;
this.lblMonth.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblMonth.Location = new System.Drawing.Point(4, 27);
this.lblMonth.Name = "lblMonth";
this.lblMonth.Size = new System.Drawing.Size(52, 23);
this.lblMonth.TabIndex = 14;
this.lblMonth.Text = "Month";
this.lblMonth.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblYear
//
this.lblYear.ForeColor = System.Drawing.Color.Maroon;
this.lblYear.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblYear.Location = new System.Drawing.Point(4, 4);
this.lblYear.Name = "lblYear";
this.lblYear.Size = new System.Drawing.Size(52, 23);
this.lblYear.TabIndex = 13;
this.lblYear.Text = "Year";
this.lblYear.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// cboYear
//
this.cboYear.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboYear.ItemHeight = 13;
this.cboYear.Location = new System.Drawing.Point(58, 6);
this.cboYear.Name = "cboYear";
this.cboYear.Size = new System.Drawing.Size(82, 21);
this.cboYear.TabIndex = 1;
//
// btnVendor
//
this.btnVendor.Location = new System.Drawing.Point(216, 52);
this.btnVendor.Name = "btnVendor";
this.btnVendor.Size = new System.Drawing.Size(22, 20);
this.btnVendor.TabIndex = 4;
this.btnVendor.Text = "...";
this.btnVendor.Click += new System.EventHandler(this.btnVendor_Click);
//
// lblVendor
//
this.lblVendor.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblVendor.Location = new System.Drawing.Point(4, 52);
this.lblVendor.Name = "lblVendor";
this.lblVendor.Size = new System.Drawing.Size(52, 20);
this.lblVendor.TabIndex = 15;
this.lblVendor.Text = "Vendor";
this.lblVendor.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// txtVendor
//
this.txtVendor.Location = new System.Drawing.Point(58, 52);
this.txtVendor.Name = "txtVendor";
this.txtVendor.Size = new System.Drawing.Size(156, 20);
this.txtVendor.TabIndex = 3;
this.txtVendor.Text = "";
this.txtVendor.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtVendor_KeyDown);
this.txtVendor.Validating += new System.ComponentModel.CancelEventHandler(this.txtVendor_Validating);
//
// lblReportTitle
//
this.lblReportTitle.ForeColor = System.Drawing.SystemColors.ControlDark;
this.lblReportTitle.Location = new System.Drawing.Point(272, 32);
this.lblReportTitle.Name = "lblReportTitle";
this.lblReportTitle.Size = new System.Drawing.Size(98, 28);
this.lblReportTitle.TabIndex = 18;
this.lblReportTitle.Text = "PART ORDER SHEET";
this.lblReportTitle.Visible = false;
//
// PartOrderSheetMultiVendorReport
//
this.AcceptButton = this.btnPrint;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnClose;
this.ClientSize = new System.Drawing.Size(388, 118);
this.Controls.Add(this.btnVendor);
this.Controls.Add(this.lblVendor);
this.Controls.Add(this.txtVendor);
this.Controls.Add(this.cboYear);
this.Controls.Add(this.lblYear);
this.Controls.Add(this.lblMonth);
this.Controls.Add(this.cboMonth);
this.Controls.Add(this.btnPrint);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.lblCCN);
this.Controls.Add(this.cboCCN);
this.Controls.Add(this.lblReportTitle);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "PartOrderSheetMultiVendorReport";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Part Order Sheet Report";
this.Load += new System.EventHandler(this.PartOrderSheetMultiVendorReport_Load);
((System.ComponentModel.ISupportInitialize)(this.cboCCN)).EndInit();
this.ResumeLayout(false);
}
#endregion
#region FORM UI EVENT HANDLE
/// <summary>
/// thachnn: 14/Nov/2005
/// Form load
/// Check security
/// Make CCN COmbobox
/// Make Year combo box
/// set current selected month and year to current DB Time
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PartOrderSheetMultiVendorReport_Load(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + ".CPOReport_Load()";
try
{
#region Check Security
Security objSecurity = new Security();
this.Name = THIS;
//objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName);
if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
return;
}
#endregion
// inititalize form
UtilsBO boUtils = new UtilsBO();
// Load combo box CCN
FormControlComponents.PutDataIntoC1ComboBox(cboCCN, boUtils.ListCCN().Tables[MST_CCNTable.TABLE_NAME], MST_CCNTable.CODE_FLD, MST_CCNTable.CCNID_FLD, MST_CCNTable.TABLE_NAME);
//cboCCN.SelectedValue = SystemProperty.CCNID;
InitYearCombo();
DateTime dtmServerDate = boUtils.GetDBDate();
// set default month to server month
cboMonth.SelectedIndex = dtmServerDate.Month - 1;
// set selected default to server year
cboYear.SelectedItem = dtmServerDate.Year;
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// /// thachnn: 14/Nov/2005
/// close form
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClose_Click(object sender, System.EventArgs e)
{
this.Close();
}
/// <summary>
/// Open the PartOrderSheet Report
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnPrint_Click(object sender, System.EventArgs e)
{
ShowPartOrderSheetMultiVendorReport(sender, e);
}
/// <summary>
/// Multi select the Vendor
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnVendor_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".TESTbtnVendor_Click()";
try
{
// user must select CCN first
if (cboCCN.SelectedValue == null || cboCCN.SelectedValue == DBNull.Value)
{
PCSMessageBox.Show(ErrorCode.MESSAGE_WOROUTING_SELECT_CCN_FIRST, MessageBoxIcon.Error);
cboCCN.Focus();
return;
}
DataTable dtbData = null;
if (sender is TextBox && sender != null)
dtbData = FormControlComponents.OpenSearchFormForMultiSelectedRow(VENDOR_VIEW, MST_PartyTable.CODE_FLD, txtVendor.Text.Trim(), null, false);
else
dtbData = FormControlComponents.OpenSearchFormForMultiSelectedRow(VENDOR_VIEW, MST_PartyTable.CODE_FLD, txtVendor.Text.Trim(), null, true);
if (dtbData != null && dtbData.Rows.Count > 0)
{
string strVendor_List = string.Empty;
string strVendorCode_List = string.Empty;
foreach (DataRow drowData in dtbData.Rows)
{
strVendor_List += drowData[MST_PartyTable.PARTYID_FLD] + ",";
strVendorCode_List += drowData[MST_PartyTable.CODE_FLD] + ",";
}
txtVendor.Tag = strVendor_List.TrimEnd(',');
txtVendor.Text = strVendorCode_List.TrimEnd(',');
// grdSelectedVendors.DataSource = dtbData;
}
else
{
txtVendor.Text = string.Empty;
txtVendor.Tag = null;
txtVendor.Focus();
txtVendor.SelectAll();
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// open search forms
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtVendor_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
const string METHOD_NAME = THIS + ".txtVendor_KeyDown()";
try
{
if (e.KeyCode == Keys.F4)
{
btnVendor_Click(sender, e);
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR,MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION,MessageBoxIcon.Error);
}
}
}
/// <summary>
/// /// thachnn: 14/Nov/2005
/// OpenSearchForm when leave
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtVendor_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".txtVendor_Validating()";
try
{
if (txtVendor.Modified)
{
if (txtVendor.Text.Trim() == string.Empty)
{
txtVendor.Tag = null;
// grdSelectedVendors.DataSource = null;
// grdSelectedVendors.Refresh();
return;
}
btnVendor_Click(txtVendor,null);
e.Cancel = true;
}
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
#endregion
/// <summary>
/// /// thachnn: 14/Nov/2005
/// Clear all condition information on the form
/// </summary>
private void ClearSearchingCondition()
{
try
{
DateTime dtmServerDate = (new UtilsBO()).GetDBDate();
// set default month to server month
cboMonth.SelectedIndex = dtmServerDate.Month - 1;
// set selected default to server year
cboYear.SelectedItem = dtmServerDate.Year;
txtVendor.Text = string.Empty;
txtVendor.Tag = ZERO_STRING;
cboMonth.Focus();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
/// <summary>
/// /// thachnn: 14/Nov/2005
/// Init Year combo
/// </summary>
private void InitYearCombo()
{
try
{
// year start from 2000 to 2050
for (int i = 2000; i < 2051; i++)
cboYear.Items.Add(i);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// thachnn: 17/11/2005
/// Print the Part Order Sheet Report
/// Using the "PartOrderSheetReport.xml" layout
/// </summary>
private void ShowPartOrderSheetMultiVendorReport(object sender, System.EventArgs e)
{
const string METHOD_NAME = THIS + "ShowPartOrderSheetMultiVendorReport()";
string strAttention = "txtVendorName.Text";
string strRevision = "txtRevision.Text";
try
{
#region PREPARE
string mstrReportDefFolder = Application.StartupPath + "\\" +Constants.REPORT_DEFINITION_STORE_LOCATION;
DataTable dtbResult;
DataTable dtbResultNext;
DataTable dtbResultNextNext;
PCSComUtils.Framework.ReportFrame.BO.C1PrintPreviewDialogBO objBO = new PCSComUtils.Framework.ReportFrame.BO.C1PrintPreviewDialogBO();
int nCCNID;
int nMonth = System.Convert.ToInt32(cboMonth.SelectedItem);
int nYear = System.Convert.ToInt32(cboYear.SelectedItem);
string strVendorID_List = txtVendor.Tag == null? string.Empty : txtVendor.Tag.ToString();
string strCCN = string.Empty;
string strPurchaseOrderMasterCode = string.Empty;
//string strVendor = string.Empty;
string strCategory = string.Empty;
string strProduct = string.Empty;
/// contain array of string: 01 02 03 .. of day of month in the dtbResult, except the missing day
ArrayList arrDueDateHeading = new ArrayList();
/// Build to keep value of pair: 01 --> 01-Mon, ... depend on the real data of dtbResule
NameValueCollection arrDayNumberMapToDayWithDayOfWeek = new NameValueCollection();
/// Build to keep value of pair: 01 --> 01-Mon, ... NOT DEPEND on the real data
NameValueCollection arrFullDayNumberMapToDayWithDayOfWeek = new NameValueCollection();
Cursor = Cursors.WaitCursor;
// check report layout file is exist or not
if (!File.Exists(mstrReportDefFolder + @"\" + REPORT_LAYOUT_FILE))
{
PCSMessageBox.Show(ErrorCode.MESSAGE_REPORT_TEMPLATE_FILE_NOT_FOUND, MessageBoxIcon.Error);
Cursor = Cursors.Default;
return;
}
#endregion
#region GETTING THE PARAMETER
#region Validate data
// user must select CCN first
if (cboCCN.SelectedValue == null || cboCCN.SelectedValue == DBNull.Value)
{
string[] arrParams = {lblCCN.Text};
PCSMessageBox.Show(ErrorCode.MESSAGE_MANDATORY_FIELD_REQUIRED, MessageBoxIcon.Error,arrParams);
cboCCN.Focus();
Cursor = Cursors.Default;
return;
}
// // Check if user does not select PO Number
// if("txtOrderNo.Text".Trim() == string.Empty)
// {
// string[] arrParams = {"lblOrderNo.Text"};
// PCSMessageBox.Show(ErrorCode.MESSAGE_MANDATORY_FIELD_REQUIRED, MessageBoxIcon.Error,arrParams);
// //OLD: txtOrderNo.Focus();
// Cursor = Cursors.Default;
// return;
// }
#endregion
nCCNID = int.Parse(cboCCN.SelectedValue.ToString());
strCCN = boUtil.GetCCNCodeFromID(nCCNID);
//strPurchaseOrderMasterCode = "txtOrderNo.Text".Trim();
// DateTime dtmOrderMonth = DateTime.MinValue;
// /// Order Date will getting like the grid of PO_Delivery Schedule Form
// /// Build the data table like PO_Delivery Schedule Form. getting the first record, schedule date
// try
// {
// PODeliveryScheduleBO objPODeliveryScheduleBO = new PODeliveryScheduleBO();
// //OLD: int nCurrentPurchaseOrderDetail = int.Parse(gridData[gridData.Row,PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD].ToString());
// int nCurrentPurchaseOrderDetail = 1;
//
// DataSet dstTempDeliverySchedule = objPODeliveryScheduleBO.GetDeliverySchedule(nCurrentPurchaseOrderDetail);
// if(dstTempDeliverySchedule != null)
// {
// if(dstTempDeliverySchedule.Tables.Count > 0)
// {
// if(dstTempDeliverySchedule.Tables[0].Rows.Count > 0)
// {
// try
// {
// dtmOrderMonth = (DateTime)dstTempDeliverySchedule.Tables[0].Rows[0][PO_DeliveryScheduleTable.SCHEDULEDATE_FLD];
// }
// catch{}
// }
// }
// }
// }
// catch
// {
// ///if can't get dtmOrderMonth, may be there is error in the other module
// ///we still generate the report with month= 1 and year = 1900, it will be a empty report
// }
// nYear = dtmOrderMonth.Year;
// nMonth = dtmOrderMonth.Month;
//
// // if input null, then we send the int.MinValue to the BO function
// // Not mandatory id field will have int.MinValue if it is not selected
// try
// {
// nVendorID = (int)(txtVendor.Tag);
// strVendor = objBO.GetVendorCodeFromID(nVendorID) + "-" + objBO.GetVendorNameFromID(nVendorID);
// }
// catch
// {
// strVendor = string.Empty;
// }
// try
// {
// nProductID = (int)(txtItem.Tag);
// strProduct = objBO.GetProductCodeFromID(nProductID) + "-" + objBO.GetProductNameFromID(nProductID);
// }
// catch
// {
// strProduct = string.Empty;
// }
// try
// {
// nCategoryID = (int)(txtCategory.Tag);
// strCategory = objBO.GetCategoryCodeFromID(nCategoryID) + "-" + objBO.GetCategoryNameFromID(nCategoryID);
// }
// catch
// {
// strCategory = string.Empty;
// }
#endregion
#region BUILDING THE TABLE (getting from database by BO)
DataSet dstResult = objBO.GetPartOrderSheetMultiVendorReportData(nCCNID, nMonth, nYear, strVendorID_List);
dtbResult = dstResult.Tables[0];
dtbResultNext = dstResult.Tables[1];
dtbResultNextNext = dstResult.Tables[2];
#endregion
#region TRANSFORM ORIGINAL TABLE FOR REPORT
#region BUILD THE FULL DayWithDayOfWeek Pair // full from 1 to 31
DateTime dtmTemp = new DateTime(nYear,nMonth,1);
for(int i = 0 ; i <31 ; i++)
{
DateTime dtm = dtmTemp.AddDays(i);
arrFullDayNumberMapToDayWithDayOfWeek.Add(dtm.Day.ToString("00"), dtm.Day.ToString("00")+"-"+dtm.DayOfWeek.ToString().Substring(0,3) );
}
#endregion
#region GETTING THE DATE HEADING
ArrayList arrDueDate = GetColumnValuesFromTable(dtbResult,SCHEDULE_DATE);
ArrayList arrItems = GetPartyID_PartNoGROUPFromTable(dtbResult,PARTYID, PARTNO);
foreach(DateTime dtm in arrDueDate)
{
string strColumnName = COL_ORDER_PREFIX + dtm.Day.ToString("00");
string strColumnNameA = COL_ADJUSTMENT_PREFIX + dtm.Day.ToString("00");
arrDayNumberMapToDayWithDayOfWeek.Add(dtm.Day.ToString("00"), dtm.Day.ToString("00")+"-"+dtm.DayOfWeek.ToString().Substring(0,3) );
arrDueDateHeading.Add(strColumnName);
arrDueDateHeading.Add(strColumnNameA);
}
#endregion
DataTable dtbTransform = BuildPartOrderSheetTable(arrDueDateHeading);
/// fill data to the dtbTransform
foreach(string strItem in arrItems)
{
// Create DUMMYROW FIRST
DataRow dtrNew = dtbTransform.NewRow();
double dblSumRowNext = 0;
double dblSumRowNextNext = 0;
double dblSumRowNextA = 0;
double dblSumRowNextNextA = 0;
string strFilter = strFilter = string.Format("[{0}]='{1}' AND [{2}]='{3}' " ,
PARTYID, strItem.Split('#')[0] ,
PARTNO,strItem.Split('#')[1]);
string strSort = string.Format("[{0}] ASC, [{1}] ASC", PARTYID, PARTNO);
/// Getting next total for the next, and next next month of order quantity
/// Getting next total for the next, and next next month of adjustment
DataRow[] dtrowsNext = dtbResultNext.Select(strFilter,strSort);
foreach(DataRow dtr in dtrowsNext)
{
try
{
dblSumRowNext += Convert.ToDouble(dtr[QUANTITY]);
}
catch{}
try
{
dblSumRowNextA += Convert.ToDouble(dtr[ADJUSTMENT]);
}
catch{}
}
DataRow[] dtrowsNextNext = dtbResultNextNext.Select(strFilter,strSort);
foreach(DataRow dtr in dtrowsNextNext)
{
try
{
dblSumRowNextNext += Convert.ToDouble(dtr[QUANTITY]);
}
catch{}
try
{
dblSumRowNextNextA += Convert.ToDouble(dtr[ADJUSTMENT]);
}
catch{}
}
DataRow[] dtrows = dtbResult.Select(strFilter,strSort);
foreach(DataRow dtr in dtrows)
{
/// fill data to the dummy row
/// these column is persistance, we always set to the first rows
dtrNew[VENDOR] = dtrows[0][VENDOR];
dtrNew[PARTNO] = dtrows[0][PARTNO];
dtrNew[PARTNAME] = dtrows[0][PARTNAME];
dtrNew[MODEL] = dtrows[0][MODEL];
/// fill the Quantity of the day to the cell (indicate by column Dxx in this dummy rows)
string strDateColumnToFill = COL_ORDER_PREFIX + ((DateTime)dtr[SCHEDULE_DATE]).Day.ToString("00");
dtrNew[strDateColumnToFill] = dtr[QUANTITY];
/// fill the Quantity of the day to the cell (indicate by column Dxx in this dummy rows)
strDateColumnToFill = COL_ADJUSTMENT_PREFIX + ((DateTime)dtr[SCHEDULE_DATE]).Day.ToString("00");
dtrNew[strDateColumnToFill] = dtr[ADJUSTMENT];
/// fill the SumRow of next month and next next month to this dummy rows
/// we calculated these values before
/// Order Delivery quantity
dtrNew[SUMROWNEXT_O] = dblSumRowNext;
dtrNew[SUMROWNEXTNEXT_O] = dblSumRowNextNext;
/// Adjustment Quantity
dtrNew[SUMROWNEXT_A] = dblSumRowNextA;
dtrNew[SUMROWNEXTNEXT_A] = dblSumRowNextNextA;
}
// add to the transform data table
dtbTransform.Rows.Add(dtrNew);
}
#endregion
#region RENDER REPORT
ReportBuilder objRB;
objRB = new ReportBuilder();
try
{
objRB.ReportName = REPORT_NAME;
// string strSort = string.Format("[{0}] ASC, [{1}] ASC, [{2}] ASC,[{3}] ASC,[{4}] ASC,[{5}] ASC,[{6}] ASC " , VENDOR,CATEGORY,PARTNO,PARTNAME,MODEL,UM,QUANTITYSET );
// DataTable dtbToDisplayInReport = new DataTable();
// foreach(DataRow dtr in dtbTransform.Select(string.Empty,strSort))
// {
// dtbToDisplayInReport.ImportRow(dtr);
// }
// objRB.SourceDataTable = dtbToDisplayInReport;
objRB.SourceDataTable = dtbTransform;
}
catch// (Exception ex)
{
/// we can't preview while we don't have any data
return;
}
#region INIT REPORT BUIDER OBJECT
try
{
objRB.ReportDefinitionFolder = mstrReportDefFolder;
objRB.ReportLayoutFile = REPORT_LAYOUT_FILE;
if(objRB.AnalyseLayoutFile() == false)
{
PCSMessageBox.Show(ErrorCode.MESSAGE_REPORT_TEMPLATE_FILE_NOT_FOUND, MessageBoxIcon.Error);
return;
}
//objRB.UseLayoutFile = objRB.AnalyseLayoutFile(); // use layout file if any , auto drawing if not found layout file
objRB.UseLayoutFile = true; // always use layout file
}
catch
{
objRB.UseLayoutFile = false;
PCSMessageBox.Show(ErrorCode.MESSAGE_REPORT_TEMPLATE_FILE_NOT_FOUND,MessageBoxIcon.Error);
}
#endregion
objRB.MakeDataTableForRender();
//grid.DataSource = objRB.RenderDataTable;
// and show it in preview dialog
PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog printPreview = new PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog();
printPreview.FormTitle = lblReportTitle.Text + " " + nMonth.ToString("00") + "-"+ nYear.ToString("0000") ;
objRB.ReportViewer = printPreview.ReportViewer;
objRB.RenderReport();
#region MODIFY THE REPORT LAYOUT
objRB.DrawPredefinedField(REPORTFLD_TITLE, lblReportTitle.Text.Trim());
//objRB.DrawPredefinedField(REPORTFLD_ATTENTION, strAttention.ToUpper());
DateTime dtmOrderMonth = new DateTime(nYear,nMonth,1);
objRB.DrawPredefinedField(REPORTFLD_ORDER_MONTH, dtmOrderMonth.ToString(NEXTMONTH_DATE_FORMAT).ToUpper());
objRB.DrawPredefinedField(REPORTFLD_SUMROW_NEXT, dtmOrderMonth.AddMonths(1).ToString(NEXTMONTH_DATE_FORMAT));
objRB.DrawPredefinedField(REPORTFLD_SUMROW_NEXTNEXT, dtmOrderMonth.AddMonths(2).ToString(NEXTMONTH_DATE_FORMAT));
//get this date time from the Form (TransDate on form)
// OLD: DateTime dtmTransDate = (DateTime)cboOrderDate.Value;
//DateTime dtmTransDate = new DateTime(2006,1,4);
//objRB.DrawPredefinedField(REPORTFLD_ISSUE_DATE, dtmTransDate.ToString(ISSUE_DATE_FORMAT));
//objRB.DrawPredefinedField(REPORTFLD_REVISION, strRevision);
#region COMPANY INFO // header information get from system params
try
{
objRB.DrawPredefinedField(REPORTFLD_COMPANY,SystemProperty.SytemParams.Get(SystemParam.COMPANY_NAME));
}
catch{}
try
{
objRB.DrawPredefinedField(REPORTFLD_ADDRESS,SystemProperty.SytemParams.Get(SystemParam.ADDRESS));
}
catch{}
try
{
objRB.DrawPredefinedField(REPORTFLD_TEL,SystemProperty.SytemParams.Get(SystemParam.TEL));
}
catch{}
try
{
objRB.DrawPredefinedField(REPORTFLD_FAX,SystemProperty.SytemParams.Get(SystemParam.FAX));
}
catch{}
#endregion
#region DRAW Parameters
/*
System.Collections.Specialized.NameValueCollection arrParamAndValue = new System.Collections.Specialized.NameValueCollection();
arrParamAndValue.Add(lblCCN.Text,cboCCN.Text);
arrParamAndValue.Add(lblYear.Text, nYear.ToString());
arrParamAndValue.Add(lblMonth.Text, nMonth.ToString());
arrParamAndValue.Add(lblVendor.Text,txtVendor.Text);
arrParamAndValue.Add(lblVendor.Text,txtVendor.Text);
arrParamAndValue.Add(lblVendor.Text,txtVendor.Text);
arrParamAndValue.Add(lblVendor.Text,txtVendor.Text);
/// anchor the Parameter drawing canvas cordinate to the fldTitle
C1.C1Report.Field fldTitle = objRB.GetFieldByName(REPORTFLD_TITLE);
double dblStartX = fldTitle.Left;
double dblStartY = fldTitle.Top + 1.3*fldTitle.RenderHeight;
objRB.GetSectionByName(HEADER).CanGrow = true;
objRB.DrawParameters( objRB.GetSectionByName(HEADER) ,dblStartX , dblStartY , arrParamAndValue, objRB.Report.Font.Size);
*/
#endregion
#region RENAME THE COLUMN HEADING TEXT
ArrayList arrColumnHeadings = new ArrayList();
for(int i = 0; i <= 31; i++) /// clear the heading text
{
objRB.DrawPredefinedField(COL_ORDER_PREFIX+i.ToString("00")+"Lbl","");
}
for(int i = 0; i <= 31; i++)
{
/// Paint the EMPTY Colummn to
try
{
if(arrDueDateHeading.Contains(COL_ORDER_PREFIX+i.ToString("00")) )
{
string strHeading = arrDayNumberMapToDayWithDayOfWeek[i.ToString("00")].Substring(0,6);
objRB.DrawPredefinedField(COL_ORDER_PREFIX+i.ToString("00")+"Lbl",strHeading);
}
else
{
string strHeading = arrFullDayNumberMapToDayWithDayOfWeek[i.ToString("00")].Substring(0,6);
objRB.DrawPredefinedField(COL_ORDER_PREFIX+i.ToString("00")+"Lbl",strHeading);
/// HACKED: Thachnn: from now we don't paint the empty Column to WhiteSmoke.
/// objRB.Report.Fields[COL_ORDER_PREFIX+i.ToString("00")+"Lbl"].BackColor = Color.WhiteSmoke;
}
}
catch // draw continue, don't care about error value in the parrValuesToFill
{
//break;
}
/// Paint the WEEKEND Colummn to Red on Yealow
try
{
if(objRB.Report.Fields[COL_ORDER_PREFIX+i.ToString("00")+"Lbl"] != null)
{
/// this variable contain sat, sun, mon tue, ...
string strDateName = objRB.GetFieldByName(COL_ORDER_PREFIX+i.ToString("00")+"Lbl").Text.Substring(3,3);
//if(strDateName == "Sat" || strDateName == "Sun")
if(strDateName == "Sun")
{
objRB.Report.Fields[COL_ORDER_PREFIX+i.ToString("00")+"Lbl"].BackColor = Color.Yellow;
objRB.Report.Fields[COL_ORDER_PREFIX+i.ToString("00")+"Lbl"].ForeColor = Color.Red;
}
}
}
catch // draw continue, don't care about error value in the parrValuesToFill
{
//break;
}
/// REMOVE THE DATE STRING (Mon, Tue, ..) as Mr.CuongNT's request, hic hic hic. I add, then I have to remove
/// Rename it to 1 2 3 4 5 6
try
{
objRB.Report.Fields[COL_ORDER_PREFIX+i.ToString("00")+"Lbl"].Text = i.ToString();
objRB.Report.Fields[COL_ORDER_PREFIX+i.ToString("00")+"Lbl"].Font.Bold = false;
}
catch{}
}
#endregion
#endregion
objRB.RefreshReport();
printPreview.Show();
#endregion
}
catch(Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
finally
{
Cursor = Cursors.Default;
}
}
/// <summary>
/// Thachnn : 15/Oct/2005
/// Browse the DataTable, get all value of column with provided named.
/// </summary>
/// <param name="pdtb">DataTable to collect values</param>
/// <param name="pstrColumnName">COlumn Name in pdtb DataTable to collect values from</param>
/// <returns>ArrayList of object, collect from pdtb's column named pstrColumnName. Empty ArrayList if error or not found any row in pdtb.</returns>
private static ArrayList GetColumnValuesFromTable(DataTable pdtb, string pstrColumnName)
{
ArrayList arrRet = new ArrayList();
try
{
foreach (DataRow drow in pdtb.Rows)
{
object objGet = drow[pstrColumnName];
if( !arrRet.Contains(objGet) )
{
arrRet.Add(objGet);
}
}
}
catch
{
arrRet.Clear();
}
return arrRet;
}
/// <summary>
/// Thachnn : 08/Nov/2005
/// Browse the DataTable, get all value of Vendor, Category, PartNo column, insert into ArraysList as VendorValue#CategoryValue#PartNoValue
/// Because Item differ from each other by Vendor, Category and partNo
/// So this triple group will be unique between Items
/// </summary>
/// <history>Thachnn: 28/12/2005: change unique condition. PartNo and Model are Unique for each Item</history>
/// <param name="pdtb">DataTable to collect values</param>
/// <param name="pstrCategoryColName"></param>
/// <param name="pstrPartNoColName"></param>
/// <returns>ArrayList of object, collect CategoryValue#PartNoValue pairs from pdtb. Empty ArrayList if error or not found any row in pdtb.</returns>
private static ArrayList GetPartNo_Model_UM_GROUPFromTable(DataTable pdtb, string pstrPartNoColName, string pstrModel, string pstrUM)
{
ArrayList arrRet = new ArrayList();
try
{
foreach (DataRow drow in pdtb.Rows)
{
object objPartNoGet = drow[pstrPartNoColName];
object objModelGet = drow[pstrModel];
object objUMGet = drow[pstrUM];
string str = objPartNoGet.ToString() +"#"+ objModelGet.ToString() + "#" + objUMGet.ToString() ;
if( !arrRet.Contains(str) )
{
arrRet.Add(str);
}
}
}
catch
{
arrRet.Clear();
}
return arrRet;
}
/// <summary>
/// /// thachnn: 14/Nov/2005
/// Build the crosstab table to render on report
/// contain D01 ---> D31 , A01 ---> A31, and NextMonth SumRow O A, NextNextMonth SumRow O A
/// see Schedule of local parts in month UseCase under PCS/06-Project Design/DesignReport folder.
/// </summary>
/// <remarks>
/// </remarks>
/// <returns>DataTable</returns>
private DataTable BuildPartOrderSheetTable(ArrayList parrScheduleDateHeading)
{
const string strPartOrderSheetTableName = "PartOrderSheetTable";
try
{
//Create table
DataTable dtbRet = new DataTable(strPartOrderSheetTableName);
//Add columns
dtbRet.Columns.Add(PARTYID, typeof(System.String));
dtbRet.Columns.Add(VENDOR, typeof(System.String));
dtbRet.Columns.Add(PARTNO, typeof(System.String));
dtbRet.Columns.Add(PARTNAME, typeof(System.String));
dtbRet.Columns.Add(MODEL, typeof(System.String));
dtbRet.Columns.Add(SUMROWNEXT_O, typeof(System.Double));
dtbRet.Columns.Add(SUMROWNEXTNEXT_O, typeof(System.Double));
dtbRet.Columns.Add(SUMROWNEXT_A, typeof(System.Double));
dtbRet.Columns.Add(SUMROWNEXTNEXT_A, typeof(System.Double));
foreach(string strColumnName in parrScheduleDateHeading)
{
try
{
dtbRet.Columns.Add(strColumnName,typeof(System.Double));
}
catch{}
}
// FILL the null column, if not exist null column (not existed date.) report will gen ###,#0 to the cell
for(int i = 1; i <=31; i++)
{
if(parrScheduleDateHeading.Contains(COL_ORDER_PREFIX + i.ToString("00")) == false )
{
try
{
dtbRet.Columns.Add(COL_ORDER_PREFIX + i.ToString("00"),typeof(System.String));
}
catch{}
}
if(parrScheduleDateHeading.Contains(COL_ADJUSTMENT_PREFIX + i.ToString("00")) == false )
{
try
{
dtbRet.Columns.Add(COL_ADJUSTMENT_PREFIX + i.ToString("00"),typeof(System.String));
}
catch{}
}
}
// dtbRet.Columns.Add("Boolean", typeof(System.Boolean));
// dtbRet.Columns.Add("Int32", typeof(System.Int32));
// dtbRet.Columns.Add("String", typeof(System.String));
// dtbRet.Columns.Add("Double", typeof(System.Double));
// dtbRet.Columns.Add("DateTime", typeof(System.DateTime));
return dtbRet;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
/// <summary>
/// Thachnn : 08/Nov/2005
/// Browse the DataTable, get all value of PartyID-PartNo pair column, insert into ArraysList as PartyIDPartNoValue
/// Because Item differ from each other by PartyID and partNo
/// So this group will be unique between Items of report
/// </summary>
/// <param name="pdtb">DataTable to collect values</param>
/// <param name="pstrPartyIDColName"></param>
/// <param name="pstrPartNoColName"></param>
/// <returns>ArrayList of object, collect PartyID - PartNoValue pairs from pdtb. Empty ArrayList if error or not found any row in pdtb.</returns>
private static ArrayList GetPartyID_PartNoGROUPFromTable(DataTable pdtb , string pstrPartyIDColName, string pstrPartNoColName)
{
ArrayList arrRet = new ArrayList();
try
{
foreach (DataRow drow in pdtb.Rows)
{
object objPartyIDGet = drow[pstrPartyIDColName];
object objPartNoGet = drow[pstrPartNoColName];
string str = objPartyIDGet.ToString().Trim() +"#"+ objPartNoGet.ToString().Trim();
if( !arrRet.Contains(str) )
{
arrRet.Add(str);
}
}
}
catch
{
arrRet.Clear();
}
return arrRet;
}
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Collections;
using System.IO;
using System.Threading;
using System.Reflection;
using System.Runtime.Serialization;
using System.Configuration;
using System.Xml;
using System.Text;
using System.Resources;
using System.Globalization;
using System.Diagnostics;
using PHP.Core.Reflection;
#if SILVERLIGHT
using PHP.CoreCLR;
#else
using System.Web; // ReportError(config, HttpContext.Current.Response.Output, error, id, info, message);
#endif
namespace PHP.Core
{
#region Enumerations
/// <summary>
/// Types of errors caused by PHP class library functions.
/// </summary>
[Flags]
public enum PhpError : int
{
/// <summary>Error.</summary>
Error = 1,
/// <summary>Warning.</summary>
Warning = 2,
/// <summary>Notice.</summary>
Notice = 8,
/// <summary>User error.</summary>
UserError = 256,
/// <summary>User warning.</summary>
UserWarning = 512,
/// <summary>User notice.</summary>
UserNotice = 1024,
/// <summary>Parse error.</summary>
ParseError = 4,
/// <summary>Core error.</summary>
CoreError = 16,
/// <summary>Core warning.</summary>
CoreWarning = 32,
/// <summary>Compile error.</summary>
CompileError = 64,
/// <summary>Compile warning.</summary>
CompileWarning = 128,
/// <summary>Strict notice (PHP 5.0+).</summary>
Strict = 2048,
/// <summary>PHP 5.2+</summary>
RecoverableError = 4096,
/// <summary>Deprecated (PHP 5.3+)</summary>
Deprecated = 8192,
UserDeprecated = 16384,
}
/// <summary>
/// Sets of error types.
/// </summary>
[Flags]
public enum PhpErrorSet : int
{
/// <summary>Empty error set.</summary>
None = 0,
/// <summary>Standard errors used by Core and Class Library.</summary>
Standard = PhpError.Error | PhpError.Warning | PhpError.Notice | PhpError.Deprecated,
/// <summary>User triggered errors.</summary>
User = PhpError.UserError | PhpError.UserWarning | PhpError.UserNotice | PhpError.UserDeprecated,
/// <summary>Core system errors.</summary>
System = PhpError.ParseError | PhpError.CoreError | PhpError.CoreWarning | PhpError.CompileError | PhpError.CompileWarning | PhpError.RecoverableError,
/// <summary>All possible errors except for the strict ones.</summary>
AllButStrict = Standard | User | System,
/// <summary>All possible errors. 30719 in PHP 5.3</summary>
All = AllButStrict | PhpError.Strict,
/// <summary>Errors which can be handled by the user defined routine.</summary>
Handleable = (User | Standard) & ~PhpError.Error,
/// <summary>Errors which causes termination of a running script.</summary>
Fatal = PhpError.Error | PhpError.CompileError | PhpError.CoreError | PhpError.UserError
}
/// <summary>
/// Type of action being performed when PhpException static handlers (Throw, InvalidArgument, ...) are called.
/// </summary>
public enum PhpErrorAction
{
/// <summary>An action specified by the current configuration is taken.</summary>
Default,
/// <summary>An exception is thrown.</summary>
Throw,
/// <summary>Do nothing but setting the flag.</summary>
None
}
#endregion
/// <summary>
/// Represents information about an error got from the stack.
/// </summary>
public struct ErrorStackInfo
{
/// <summary>
/// The name of the source file.
/// </summary>
public string File;
/// <summary>
/// The name of the PHP function which caused an error.
/// </summary>
public string Caller;
/// <summary>
/// Whether a caller is a library function.
/// </summary>
public bool LibraryCaller;
/// <summary>
/// A number of a line in a source file where an error occured.
/// </summary>
public int Line;
/// <summary>
/// A number of a column in a source file where an error occured.
/// </summary>
public int Column;
/// <summary>
/// Initializes <see cref="ErrorStackInfo"/> by given values.
/// </summary>
/// <param name="file">Full path to a source file.</param>
/// <param name="caller">Name of a calling PHP funcion.</param>
/// <param name="line">Line in a source file.</param>
/// <param name="column">Column in a source file.</param>
/// <param name="libraryCaller">Whether a caller is a library function.</param>
public ErrorStackInfo(string file, string caller, int line, int column, bool libraryCaller)
{
File = file;
Caller = caller;
Line = line;
Column = column;
LibraryCaller = libraryCaller;
}
}
/// <summary>
/// Represents exceptions thrown by PHP class library functions.
/// </summary>
[Serializable]
[DebuggerNonUserCode]
public class PhpException : System.Exception
{
#region Frequently reported errors
/// <summary>
/// Invalid argument error.
/// </summary>
/// <param name="argument">The name of the argument being invalid.</param>
public static void InvalidArgument(string argument)
{
Throw(PhpError.Warning, CoreResources.GetString("invalid_argument", argument));
}
/// <summary>
/// Invalid argument error with a description of a reason.
/// </summary>
/// <param name="argument">The name of the argument being invalid.</param>
/// <param name="message">The message - what is wrong with the argument. Must contain "{0}" which is replaced by argument's name.
/// </param>
public static void InvalidArgument(string argument, string message)
{
Throw(PhpError.Warning, String.Format(CoreResources.GetString("invalid_argument_with_message") + message, argument));
}
/// <summary>
/// Argument null error. Thrown when argument can't be null but it is.
/// </summary>
/// <param name="argument">The name of the argument.</param>
public static void ArgumentNull(string argument)
{
Throw(PhpError.Warning, CoreResources.GetString("argument_null", argument));
}
/// <summary>
/// Reference argument null error. Thrown when argument which is passed by reference is null.
/// </summary>
/// <param name="argument">The name of the argument.</param>
public static void ReferenceNull(string argument)
{
Throw(PhpError.Error, CoreResources.GetString("reference_null", argument));
}
/// <summary>
/// Called library function is not supported.
/// </summary>
public static void FunctionNotSupported()
{
Throw(PhpError.Warning, CoreResources.GetString("function_not_supported"));
}
/// <summary>
/// Called library function is not supported.
/// </summary>
/// <param name="function">Not supported function name.</param>
[Emitted]
public static void FunctionNotSupported(string/*!*/function)
{
Debug.Assert(!string.IsNullOrEmpty(function));
Throw(PhpError.Warning, CoreResources.GetString("notsupported_function_called", function));
}
/// <summary>
/// Calles library function is not supported.
/// </summary>
/// <param name="severity">A severity of the error.</param>
public static void FunctionNotSupported(PhpError severity)
{
Throw(severity, CoreResources.GetString("function_not_supported"));
}
///// <summary>
///// Called library function is deprecated.
///// </summary>
//public static void FunctionDeprecated()
//{
// ErrorStackInfo info = PhpStackTrace.TraceErrorFrame(ScriptContext.CurrentContext);
// FunctionDeprecated(info.LibraryCaller ? info.Caller : null);
//}
/// <summary>
/// Called library function is deprecated.
/// </summary>
public static void FunctionDeprecated(string functionName)
{
Throw(PhpError.Deprecated, CoreResources.GetString("function_is_deprecated", functionName));
}
/// <summary>
/// Calls by the Class Library methods which need variables but get a <b>null</b> reference.
/// </summary>
public static void NeedsVariables()
{
Throw(PhpError.Warning, CoreResources.GetString("function_needs_variables"));
}
/// <summary>
/// The value of an argument is not invalid but unsupported.
/// </summary>
/// <param name="argument">The argument which value is unsupported.</param>
/// <param name="value">The value which is unsupported.</param>
public static void ArgumentValueNotSupported(string argument, object value)
{
Throw(PhpError.Warning, CoreResources.GetString("argument_value_not_supported", value, argument));
}
/// <summary>
/// Throw by <see cref="PhpStack"/> when a peeked argument should be passed by reference but it is not.
/// </summary>
/// <param name="index">An index of the argument.</param>
/// <param name="calleeName">A name of the function or method being called. Can be a <B>null</B> reference.</param>
public static void ArgumentNotPassedByRef(int index, string calleeName)
{
if (calleeName != null)
Throw(PhpError.Error, CoreResources.GetString("argument_not_passed_byref_to", index, calleeName));
else
Throw(PhpError.Error, CoreResources.GetString("argument_not_passed_byref", index));
}
/// <summary>
/// Emitted to a user function/method call which has less actual arguments than it's expected to have.
/// </summary>
/// <param name="index">An index of the parameter.</param>
/// <param name="calleeName">A name of the function or method being called. Can be a <B>null</B> reference.</param>
[Emitted]
public static void MissingArgument(int index, string calleeName)
{
if (calleeName != null)
Throw(PhpError.Warning, CoreResources.GetString("missing_argument_for", index, calleeName));
else
Throw(PhpError.Warning, CoreResources.GetString("missing_argument", index));
}
/// <summary>
/// Emitted to a user function/method call which has less actual type arguments than it's expected to have.
/// </summary>
/// <param name="index">An index of the type parameter.</param>
/// <param name="calleeName">A name of the function or method being called. Can be a <B>null</B> reference.</param>
[Emitted]
public static void MissingTypeArgument(int index, string calleeName)
{
if (calleeName != null)
Throw(PhpError.Warning, CoreResources.GetString("missing_type_argument_for", index, calleeName));
else
Throw(PhpError.Warning, CoreResources.GetString("missing_type_argument", index));
}
[Emitted]
public static void MissingArguments(string typeName, string methodName, int actual, int required)
{
if (typeName != null)
{
if (methodName != null)
Throw(PhpError.Warning, CoreResources.GetString("too_few_method_params", typeName, methodName, required, actual));
else
Throw(PhpError.Warning, CoreResources.GetString("too_few_ctor_params", typeName, required, actual));
}
else
Throw(PhpError.Warning, CoreResources.GetString("too_few_function_params", methodName, required, actual));
}
public static void UnsupportedOperandTypes()
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("unsupported_operand_types"));
}
/// <summary>
/// Emitted to a library function call which has invalid actual argument count.
/// </summary>
[Emitted]
public static void InvalidArgumentCount(string typeName, string methodName)
{
if (methodName != null)
{
if (typeName != null)
Throw(PhpError.Warning, CoreResources.GetString("invalid_argument_count_for_method", typeName, methodName));
else
Throw(PhpError.Warning, CoreResources.GetString("invalid_argument_count_for_function", methodName));
}
else
Throw(PhpError.Warning, CoreResources.GetString("invalid_argument_count"));
}
/// <summary>
/// Emitted to the foreach statement if the variable to be enumerated doesn't implement
/// the <see cref="IPhpEnumerable"/> interface.
/// </summary>
[Emitted]
public static void InvalidForeachArgument()
{
Throw(PhpError.Warning, CoreResources.GetString("invalid_foreach_argument"));
}
/// <summary>
/// Emitted to the function call if an argument cannot be implicitly casted.
/// </summary>
/// <param name="argument">The argument which is casted.</param>
/// <param name="targetType">The type to which is casted.</param>
/// <param name="functionName">The name of the function called.</param>
[Emitted]
public static void InvalidImplicitCast(object argument, string targetType, string functionName)
{
Throw(PhpError.Warning, CoreResources.GetString("invalid_implicit_cast",
PhpVariable.GetTypeName(argument),
targetType,
functionName));
}
/// <summary>
/// Emitted to the code on the places where invalid number of breaking levels is used.
/// </summary>
/// <param name="levelCount">The number of levels.</param>
[Emitted]
public static void InvalidBreakLevelCount(int levelCount)
{
Throw(PhpError.Error, CoreResources.GetString("invalid_break_level_count", levelCount));
}
/// <summary>
/// Reported by operators when they found that a undefined variable is acceesed.
/// </summary>
/// <param name="name">The name of the variable.</param>
[Emitted]
public static void UndefinedVariable(string name)
{
Throw(PhpError.Notice, CoreResources.GetString("undefined_variable", name));
}
/// <summary>
/// Emitted instead of the assignment of to the "$this" variable.
/// </summary>
[Emitted]
public static void CannotReassignThis()
{
Throw(PhpError.Error, CoreResources.GetString("cannot_reassign_this"));
}
/// <summary>
/// An argument violates a type hint.
/// </summary>
/// <param name="argName">The name of the argument.</param>
/// <param name="typeName">The name of the hinted type.</param>
[Emitted]
public static void InvalidArgumentType(string argName, string typeName)
{
Throw(PhpError.Error, CoreResources.GetString("invalid_argument_type", argName, typeName));
}
/// <summary>
/// Array operators reports this error if an value of illegal type is used for indexation.
/// </summary>
public static void IllegalOffsetType()
{
Throw(PhpError.Warning, CoreResources.GetString("illegal_offset_type"));
}
/// <summary>
/// Array does not contain given <paramref name="key"/>.
/// </summary>
/// <param name="key">Key which was not found in the array.</param>
public static void UndefinedOffset(object key)
{
Throw(PhpError.Notice, CoreResources.GetString("undefined_offset", key));
}
/// <summary>
/// Emitted to the script's Main() routine. Thrown when an unexpected exception is catched.
/// </summary>
/// <param name="e">The catched exception.</param>
public static void InternalError(Exception e)
{
throw new PhpNetInternalException(e.Message, e);
}
/// <summary>
/// Reports an error when a variable should be PHP array but it is not.
/// </summary>
/// <param name="reference">Whether a reference modifier (=&) is used.</param>
/// <param name="var">The variable which was misused.</param>
/// <exception cref="PhpException"><paramref name="var"/> is <see cref="PhpArray"/> (Warning).</exception>
/// <exception cref="PhpException"><paramref name="var"/> is scalar type (Warning).</exception>
/// <exception cref="PhpException"><paramref name="var"/> is a string (Warning).</exception>
public static void VariableMisusedAsArray(object var, bool reference)
{
Debug.Assert(var != null);
DObject obj;
if ((obj = var as DObject) != null)
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("object_used_as_array", obj.TypeName));
}
else if (PhpVariable.IsString(var))
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString(reference ? "string_item_used_as_reference" : "string_used_as_array"));
}
else
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("scalar_used_as_array", PhpVariable.GetTypeName(var)));
}
}
/// <summary>
/// Reports an error when a variable should be PHP object but it is not.
/// </summary>
/// <param name="reference">Whether a reference modifier (=&) is used.</param>
/// <param name="var">The variable which was misused.</param>
/// <exception cref="PhpException"><paramref name="var"/> is <see cref="PhpArray"/> (Warning).</exception>
/// <exception cref="PhpException"><paramref name="var"/> is scalar type (Warning).</exception>
/// <exception cref="PhpException"><paramref name="var"/> is a string (Warning).</exception>
public static void VariableMisusedAsObject(object var, bool reference)
{
Debug.Assert(var != null);
if (var is PhpArray)
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("array_used_as_object"));
}
else if (PhpVariable.IsString(var))
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString(reference ? "string_item_used_as_reference" : "string_used_as_object"));
}
else
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("scalar_used_as_object", PhpVariable.GetTypeName(var)));
}
}
/// <summary>
/// Thrown when "this" special variable is used out of class.
/// </summary>
[Emitted]
public static void ThisUsedOutOfObjectContext()
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("this_used_out_of_object"));
}
public static void UndeclaredStaticProperty(string className, string fieldName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("undeclared_static_property_accessed", className, fieldName));
}
[Emitted]
public static void StaticPropertyUnset(string className, string fieldName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("static_property_unset", className, fieldName));
}
[Emitted]
public static void UndefinedMethodCalled(string className, string methodName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("undefined_method_called", className, methodName));
}
public static void AbstractMethodCalled(string className, string methodName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("abstract_method_called", className, methodName));
}
public static void ConstantNotAccessible(string className, string constName, string context, bool isProtected)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString(
isProtected ? "protected_constant_accessed" : "private_constant_accessed", className, constName, context));
}
public static void PropertyNotAccessible(string className, string fieldName, string context, bool isProtected)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString(
isProtected ? "protected_property_accessed" : "private_property_accessed", className, fieldName, context));
}
public static void MethodNotAccessible(string className, string methodName, string context, bool isProtected)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString(
isProtected ? "protected_method_called" : "private_method_called", className, methodName, context));
}
public static void CannotInstantiateType(string typeName, bool isInterface)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString(
isInterface ? "interface_instantiated" : "abstract_class_instantiated", typeName));
}
[Emitted]
public static void NoSuitableOverload(string className, string/*!*/ methodName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString(
(className != null) ? "no_suitable_method_overload" : "no_suitable_function_overload",
className, methodName));
}
[Emitted]
public static void PropertyTypeMismatch(string/*!*/ className, string/*!*/ propertyName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("property_type_mismatch",
className, propertyName));
}
#endregion
#region Error handling stuff
/// <summary>
/// Delegate used to catch any thrown PHP exception. Used in compile time to catch PHP runtime exceptions.
/// </summary>
internal static Action<PhpError, string> ThrowCallbackOverride
{
get
{
Action<PhpError, string> info;
ThreadStatic.Properties.TryGetProperty<Action<PhpError, string>>(out info);
return info;
}
set
{
ThreadStatic.Properties.SetProperty<Action<PhpError, string>>(value);
}
}
/// <summary>
/// Reports a PHP error.
/// </summary>
/// <param name="error">The error type</param>
/// <param name="message">The error message.</param>
public static void Throw(PhpError error, string message)
{
if (ThrowCallbackOverride != null)
{
ThrowCallbackOverride(error, message);
return;
}
ErrorStackInfo info = new ErrorStackInfo();
bool info_loaded = false;
// gets the current script context and config:
ScriptContext context = ScriptContext.CurrentContext;
LocalConfiguration config = context.Config;
// determines whether the error will be reported and whether it is handleable:
bool is_error_reported = ((PhpErrorSet)error & config.ErrorControl.ReportErrors) != 0 && !context.ErrorReportingDisabled;
bool is_error_handleable = ((PhpErrorSet)error & PhpErrorSet.Handleable & (PhpErrorSet)config.ErrorControl.UserHandlerErrors) != 0;
bool is_error_fatal = ((PhpErrorSet)error & PhpErrorSet.Fatal) != 0;
bool do_report = true;
// remember last error info
context.LastErrorType = error;
context.LastErrorMessage = message;
context.LastErrorFile = null; // only if we are getting ErrorStackInfo, see PhpStackTrace.TraceErrorFrame
context.LastErrorLine = 0; // only if we are getting ErrorStackInfo, see PhpStackTrace.TraceErrorFrame
// calls a user defined handler if available:
if (is_error_handleable && config.ErrorControl.UserHandler != null)
{
// loads stack info:
Func<ErrorStackInfo> func = () =>
{
if (!info_loaded)
{
info = PhpStackTrace.TraceErrorFrame(context, true);
info_loaded = true;
}
return info;
};
do_report = CallUserErrorHandler(context, error, func, message);
}
// reports error to output and logs:
if (do_report && is_error_reported &&
(config.ErrorControl.DisplayErrors || config.ErrorControl.EnableLogging)) // check if the error will be displayed to avoid stack trace loading
{
// loads stack info:
if (!info_loaded) { info = PhpStackTrace.TraceErrorFrame(context, false); info_loaded = true; }
ReportError(config, context.Output, error, -1, info, message);
}
// Throws an exception if the error is fatal and throwing is enabled.
// PhpError.UserError is also fatal, but can be cancelled by user handler => handler call must precede this line.
// Error displaying must also precede this line because the error should be displayed before an exception is thrown.
if (is_error_fatal && context.ThrowExceptionOnError)
{
// loads stack info:
if (!info_loaded) { info = PhpStackTrace.TraceErrorFrame(context, false); info_loaded = true; }
throw new PhpException(error, message, info);
}
}
/// <summary>
/// Reports an error to log file, event log and to output (as configured).
/// </summary>
private static void ReportError(LocalConfiguration config, TextWriter output, PhpError error, int id,
ErrorStackInfo info, string message)
{
string formatted_message = FormatErrorMessageOutput(config, error, id, info, message);
// logs error if logging is enabled:
if (config.ErrorControl.EnableLogging)
{
#if SILVERLIGHT
throw new NotSupportedException("Logging is not supported on Silverlight. Set EnableLogging to false.");
#else
// adds a message to log file:
if (config.ErrorControl.LogFile != null)
try
{
// <error>: <caller>(): <message> in <file> on line <line>
string caller = (info.Caller != null) ? (info.Caller + "(): ") : null;
string place = (info.Line > 0 && info.Column > 0) ? CoreResources.GetString("error_place", info.File, info.Line, info.Column) : null;
Logger.AppendLine(config.ErrorControl.LogFile, string.Concat(error, ": ", caller, message, place));
}
catch (Exception) { }
// adds a message to event log:
if (config.ErrorControl.SysLog)
try { Logger.AddToEventLog(message); }
catch (Exception) { }
#endif
}
// displays an error message if desired:
if (config.ErrorControl.DisplayErrors)
{
output.Write(config.ErrorControl.ErrorPrependString);
output.Write(formatted_message);
output.Write(config.ErrorControl.ErrorAppendString);
}
}
/// <summary>
/// Calls user error handler.
/// </summary>
/// <returns>Whether to report error by default handler (determined by handler's return value).</returns>
/// <exception cref="ScriptDiedException">Error handler dies.</exception>
private static bool CallUserErrorHandler(ScriptContext context, PhpError error, Func<ErrorStackInfo> info, string message)
{
LocalConfiguration config = context.Config;
try
{
object result = PhpVariable.Dereference(config.ErrorControl.UserHandler.Invoke(new PhpReference[]
{
new PhpReference((int)error),
new PhpReference(message),
new PhpReference(new LazyStackInfo(info, true)),
new PhpReference(new LazyStackInfo(info, false)),
new PhpReference() // global variables list is not supported
}));
// since PHP5 an error is reported by default error handler if user handler returns false:
return result is bool && (bool)result == false;
}
catch (ScriptDiedException)
{
// user handler has cancelled the error via script termination:
throw;
}
catch (PhpUserException)
{
// rethrow user exceptions:
throw;
}
catch (Exception)
{
}
return false;
}
/// <summary>
/// Reports error thrown from inside eval.
/// </summary>
internal static void ThrowByEval(PhpError error, string sourceFile, int line, int column, string message)
{
// obsolete:
// ErrorStackInfo info = new ErrorStackInfo(sourceFile,null,line,column,false);
//
// if (ScriptContext.CurrentContext.Config.ErrorControl.HtmlMessages)
// message = CoreResources.GetString("error_message_html_eval",message,info.Line,info.Column); else
// message = CoreResources.GetString("error_message_plain_eval",message,info.Line,info.Column);
Throw(error, message);
}
/// <summary>
/// Reports error thrown by compiler.
/// </summary>
internal static void ThrowByWebCompiler(PhpError error, int id, string sourceFile, int line, int column, string message)
{
ErrorStackInfo info = new ErrorStackInfo(sourceFile, null, line, column, false);
// gets the current script context and config:
LocalConfiguration config = Configuration.Local;
#if !SILVERLIGHT
ReportError(config, HttpContext.Current.Response.Output, error, id, info, message);
#else
ReportError(config, new StreamWriter(ScriptContext.CurrentContext.OutputStream), error, id, info, message);
#endif
if (((PhpErrorSet)error & PhpErrorSet.Fatal) != 0)
throw new PhpException(error, message, info);
}
/// <summary>
/// Get the error type text, to be displayed on output.
/// </summary>
/// <param name="error"></param>
/// <param name="id"></param>
/// <returns>Error text.</returns>
internal static string PhpErrorText(PhpError error, int id)
{
if (id > 0)
{
return String.Format("{0} ({1})", error, id);
}
else
{
switch (error)
{
// errors with spaces in the name
case PhpError.Strict:
return "Strict Standards";
// user errors reported as normal errors (without "User")
case PhpError.UserNotice:
return PhpError.Notice.ToString();
case PhpError.UserError:
return PhpError.Error.ToString();
case PhpError.UserWarning:
return PhpError.Warning.ToString();
// error string as it is
default:
return error.ToString();
}
}
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="config"></param>
/// <returns>Returns caller name with () or null. Formatted for the current output capabilities.</returns>
internal static string FormatErrorCallerName(ErrorStackInfo info, LocalConfiguration config)
{
if (info.Caller == null)
return null;
if (config.ErrorControl.HtmlMessages && config.ErrorControl.DocRefRoot != null && info.LibraryCaller)
{ // able to display HTML
return String.Format("<a href='{0}/function.{1}{2}'>{3}()</a>",
config.ErrorControl.DocRefRoot,
info.Caller.Replace('_', '-').ToLower(),
config.ErrorControl.DocRefExtension,
info.Caller);
}
else
{
return info.Caller + "()";
}
}
/// <summary>
/// Modifies the error message and caller display text, depends on error type.
/// In case of different PHP behavior.
/// </summary>
/// <param name="error">error type.</param>
/// <param name="message">Error message, in default without any change.</param>
/// <param name="caller">Caller text, in default will be modified to "foo(): ".</param>
internal static void FormatErrorMessageText(PhpError error, ref string message, ref string caller)
{
switch (error)
{
case PhpError.Deprecated:
case PhpError.UserNotice:
caller = null; // the caller is not displayed in PHP
return;
default:
if (caller != null)
caller += ": ";
return;
}
}
/// <summary>
/// Formats error message.
/// </summary>
/// <param name="config">A configuration.</param>
/// <param name="error">A type of the error.</param>
/// <param name="id">Error id or -1.</param>
/// <param name="info">A stack information about the error.</param>
/// <param name="message">A message.</param>
/// <returns>A formatted plain text or HTML message depending on settings in <paramref name="config"/>.</returns>
/// <exception cref="ArgumentNullException"><paramren name="config"/> is a <B>null</B> reference.</exception>
public static string FormatErrorMessageOutput(LocalConfiguration config, PhpError error, int id, ErrorStackInfo info, string message)
{
if (config == null)
throw new ArgumentNullException("config");
string error_str = PhpErrorText(error, id); // the error type (Warning, Error, ...)
bool show_place = info.Line > 0 && info.Column > 0; // we are able to report error position
string caller = FormatErrorCallerName(info, config); // current function name "foo()" or null
// change the message or caller, based on the error type
FormatErrorMessageText(error, ref message, ref caller);
// error message
string ErrorFormatString =
config.ErrorControl.HtmlMessages ?
(show_place ? CoreResources.error_message_html_debug : CoreResources.error_message_html) :
(show_place ? CoreResources.error_message_plain_debug : CoreResources.error_message_plain);
if (show_place)
return string.Format(ErrorFormatString,
error_str, caller, message, info.File, info.Line, info.Column);
else
return string.Format(ErrorFormatString,
error_str, caller, message);
}
/// <summary>
/// Converts exception message (ending by dot) to error message (not ending by a dot).
/// </summary>
/// <param name="exceptionMessage">The exception message.</param>
/// <returns>The error message.</returns>
/// <exception cref="ArgumentNullException"><paramref name="exceptionMessage"/> is a <B>null</B> reference.</exception>
public static string ToErrorMessage(string exceptionMessage)
{
if (exceptionMessage == null) throw new ArgumentNullException("exceptionMessage");
return exceptionMessage.TrimEnd(new char[] { '.' });
}
#endregion
#region Exception handling stuff
/// <summary>
/// Exception constructor.
/// </summary>
internal PhpException()
{
}
/// <summary>
/// Exception constructor.
/// </summary>
/// <param name="error">The type of PHP error.</param>
/// <param name="message">The error message.</param>
/// <param name="info">Information about an error gained from a stack.</param>
private PhpException(PhpError error, string message, ErrorStackInfo info)
: base(message)
{
this.info = info;
this.error = error;
}
/// <summary>
/// Error seriousness.
/// </summary>
public PhpError Error { get { return error; } }
private PhpError error;
/// <summary>
/// Error debug info (caller, source file, line and column).
/// </summary>
public ErrorStackInfo DebugInfo { get { return info; } }
private ErrorStackInfo info;
/// <summary>
/// Converts the exception to a string message.
/// </summary>
/// <returns>The formatted message.</returns>
public override string ToString()
{
return FormatErrorMessageOutput(ScriptContext.CurrentContext.Config, error, -1, info, Message);
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the PhpException class with serialized data. This constructor is used
/// when an exception is thrown in a remotely called method. Such an exceptions needs to be serialized,
/// transferred back to the caller and then rethrown using this constructor.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data about the exception
/// being thrown.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or
/// destination.</param>
protected PhpException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.error = (PhpError)info.GetValue("error", typeof(PhpError));
this.info = new ErrorStackInfo(
(string)info.GetString("file"),
(string)info.GetString("caller"),
(int)info.GetInt32("line"),
(int)info.GetInt32("column"),
(bool)info.GetBoolean("libraryCaller"));
}
/// <summary>
/// Sets the SerializationInfo with information about the exception. This method is called when a skeleton
/// catches PhpException thrown in a remotely called method.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or
/// destination.</param>
[System.Security.SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("error", error);
info.AddValue("caller", this.info.Caller);
info.AddValue("file", this.info.File);
info.AddValue("line", this.info.Line);
info.AddValue("column", this.info.Column);
}
#endif
#endregion
}
internal class LazyStackInfo : IPhpVariable
{
private PhpReference value;
private Func<ErrorStackInfo> info;
private readonly bool file;
private PhpReference Value
{
get
{
if (value == null)
value = file ? new PhpReference(info().File) : new PhpReference(info().Line);
return value;
}
}
public LazyStackInfo(Func<ErrorStackInfo> info, bool file)
{
this.info = info;
this.file = file;
}
public PhpTypeCode GetTypeCode()
{
return Value.GetTypeCode();
}
public double ToDouble()
{
return Value.ToDouble();
}
public int ToInteger()
{
return Value.ToInteger();
}
public long ToLongInteger()
{
return Value.ToLongInteger();
}
public bool ToBoolean()
{
return Value.ToBoolean();
}
public PhpBytes ToPhpBytes()
{
return Value.ToPhpBytes();
}
public Convert.NumberInfo ToNumber(out int intValue, out long longValue, out double doubleValue)
{
return Value.ToNumber(out intValue, out longValue, out doubleValue);
}
public string ToString(bool throwOnError, out bool success)
{
return ((IPhpConvertible)Value).ToString(throwOnError, out success);
}
public void Print(TextWriter output)
{
Value.Print(output);
}
public void Dump(TextWriter output)
{
Value.Dump(output);
}
public void Export(TextWriter output)
{
Value.Export(output);
}
public object DeepCopy()
{
return Value.DeepCopy();
}
public object Copy(CopyReason reason)
{
return this;
}
public int CompareTo(object obj)
{
return Value.CompareTo(obj);
}
public int CompareTo(object obj, IComparer comparer)
{
return Value.CompareTo(obj, comparer);
}
public bool IsEmpty()
{
return Value.IsEmpty();
}
public bool IsScalar()
{
return Value.IsScalar();
}
public string GetTypeName()
{
return Value.GetTypeName();
}
public override string ToString()
{
if (Value.Value == null)
return string.Empty;
return Value.Value.ToString();
}
}
internal static class ErrorSeverityHelper
{
public static PhpError ToPhpCompileError(this ErrorSeverity severity)
{
return (severity.Value == ErrorSeverity.Values.Warning)
? PhpError.CompileWarning
: PhpError.CompileError;
}
}
// TODO:
internal sealed class EvalErrorSink : ErrorSink
{
private readonly int firstLineColumnDisplacement;
public EvalErrorSink(int firstLineColumnDisplacement, WarningGroups disabledGroups, int[]/*!*/ disabledWarnings)
: base(disabledGroups, disabledWarnings)
{
this.firstLineColumnDisplacement = firstLineColumnDisplacement;
}
protected override bool Add(int id, string message, ErrorSeverity severity, int group, string/*!*/ fullPath,
ErrorPosition pos)
{
Debug.Assert(fullPath != null);
// first line column adjustment:
if (pos.FirstLine == 1) pos.FirstColumn += firstLineColumnDisplacement;
Debug.WriteLine("!!!3", message);
PhpException.ThrowByEval(severity.ToPhpCompileError(), fullPath, pos.FirstLine, pos.FirstColumn, message);
return true;
}
}
internal sealed class WebErrorSink : ErrorSink
{
public WebErrorSink(WarningGroups disabledGroups, int[]/*!*/ disabledWarnings)
: base(disabledGroups, disabledWarnings)
{
}
protected override bool Add(int id, string message, ErrorSeverity severity, int group, string/*!*/ fullPath,
ErrorPosition pos)
{
Debug.Assert(fullPath != null);
PhpException.ThrowByWebCompiler(severity.ToPhpCompileError(), id, fullPath, pos.FirstLine, pos.FirstColumn, message);
return true;
}
}
/// <summary>
/// Thrown when data are not found found in call context or are not valid.
/// </summary>
[Serializable]
public class InvalidCallContextDataException : ApplicationException
{
internal InvalidCallContextDataException(string slot)
: base(CoreResources.GetString("invalid_call_context_data", slot)) { }
}
/// <summary>
/// Thrown by exit/die language constructs to cause immediate termination of a script being executed.
/// </summary>
[Serializable]
public class ScriptDiedException : ApplicationException
{
internal ScriptDiedException(object status)
{
this.status = status;
}
internal ScriptDiedException() : this(255) { }
public object Status { get { return status; } set { status = value; } }
private object status;
#region Serializable
#if !SILVERLIGHT
public ScriptDiedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
this.Status = info.GetValue("Status", typeof(object));
}
}
[System.Security.SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
if (info != null)
{
info.AddValue("Status", Status);
}
}
#endif
#endregion
}
/// <summary>
/// Thrown when user attempts to create two types with same name in one assembly.
/// </summary>
internal class DuplicateTypeNames : ApplicationException
{
public DuplicateTypeNames(string name)
{
this.name = name;
}
public readonly string name;
}
/// <summary>
/// Thrown when an unexpected exception is thrown during a script execution.
/// </summary>
[Serializable]
public class PhpNetInternalException : ApplicationException
{
internal PhpNetInternalException(string message, Exception inner) : base(message, inner) { }
#if !SILVERLIGHT
protected PhpNetInternalException(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
/// <summary>
/// Exception details. Contains also details of <see cref="Exception.InnerException"/> to pass this into event logs.
/// </summary>
public override string Message
{
get
{
StringBuilder result = new StringBuilder(base.Message);
//for (var ex = this.InnerException; ex != null; ex = ex.InnerException)
var ex = this.InnerException;
if (ex != null)
{
result.AppendLine();
result.AppendFormat("InnerException: {0}\nat {1}\n", ex.Message, ex.StackTrace);
}
return result.ToString();
}
}
}
/// <summary>
/// Holder for an instance of <see cref="Library.SPL.Exception"/>.
/// For internal purposes only.
/// </summary>
public class PhpUserException : ApplicationException
{
public readonly Library.SPL.Exception UserException;
public PhpUserException(Library.SPL.Exception inner)
: base(Convert.ObjectToString(inner.getMessage(ScriptContext.CurrentContext)))
{
UserException = inner;
}
}
/// <summary>
/// An implementation of a method doesn't behave correctly.
/// </summary>
public class InvalidMethodImplementationException : ApplicationException
{
public InvalidMethodImplementationException(string methodName)
: base(CoreResources.GetString("invalid_method_implementation", methodName))
{ }
}
}
| |
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Routeguide
{
class Program
{
/// <summary>
/// Sample client code that makes gRPC calls to the server.
/// </summary>
public class RouteGuideClient
{
readonly RouteGuide.RouteGuideClient client;
public RouteGuideClient(RouteGuide.RouteGuideClient client)
{
this.client = client;
}
/// <summary>
/// Blocking unary call example. Calls GetFeature and prints the response.
/// </summary>
public void GetFeature(int lat, int lon)
{
try
{
Log("*** GetFeature: lat={0} lon={1}", lat, lon);
Point request = new Point { Latitude = lat, Longitude = lon };
Feature feature = client.GetFeature(request);
if (feature.Exists())
{
Log("Found feature called \"{0}\" at {1}, {2}",
feature.Name, feature.Location.GetLatitude(), feature.Location.GetLongitude());
}
else
{
Log("Found no feature at {0}, {1}",
feature.Location.GetLatitude(), feature.Location.GetLongitude());
}
}
catch (RpcException e)
{
Log("RPC failed " + e);
throw;
}
}
/// <summary>
/// Server-streaming example. Calls listFeatures with a rectangle of interest. Prints each response feature as it arrives.
/// </summary>
public async Task ListFeatures(int lowLat, int lowLon, int hiLat, int hiLon)
{
try
{
Log("*** ListFeatures: lowLat={0} lowLon={1} hiLat={2} hiLon={3}", lowLat, lowLon, hiLat,
hiLon);
Rectangle request = new Rectangle
{
Lo = new Point { Latitude = lowLat, Longitude = lowLon },
Hi = new Point { Latitude = hiLat, Longitude = hiLon }
};
using (var call = client.ListFeatures(request))
{
var responseStream = call.ResponseStream;
StringBuilder responseLog = new StringBuilder("Result: ");
while (await responseStream.MoveNext())
{
Feature feature = responseStream.Current;
responseLog.Append(feature.ToString());
}
Log(responseLog.ToString());
}
}
catch (RpcException e)
{
Log("RPC failed " + e);
throw;
}
}
/// <summary>
/// Client-streaming example. Sends numPoints randomly chosen points from features
/// with a variable delay in between. Prints the statistics when they are sent from the server.
/// </summary>
public async Task RecordRoute(List<Feature> features, int numPoints)
{
try
{
Log("*** RecordRoute");
using (var call = client.RecordRoute())
{
// Send numPoints points randomly selected from the features list.
StringBuilder numMsg = new StringBuilder();
Random rand = new Random();
for (int i = 0; i < numPoints; ++i)
{
int index = rand.Next(features.Count);
Point point = features[index].Location;
Log("Visiting point {0}, {1}", point.GetLatitude(), point.GetLongitude());
await call.RequestStream.WriteAsync(point);
// A bit of delay before sending the next one.
await Task.Delay(rand.Next(1000) + 500);
}
await call.RequestStream.CompleteAsync();
RouteSummary summary = await call.ResponseAsync;
Log("Finished trip with {0} points. Passed {1} features. "
+ "Travelled {2} meters. It took {3} seconds.", summary.PointCount,
summary.FeatureCount, summary.Distance, summary.ElapsedTime);
Log("Finished RecordRoute");
}
}
catch (RpcException e)
{
Log("RPC failed", e);
throw;
}
}
/// <summary>
/// Bi-directional streaming example. Send some chat messages, and print any
/// chat messages that are sent from the server.
/// </summary>
public async Task RouteChat()
{
try
{
Log("*** RouteChat");
var requests = new List<RouteNote>
{
NewNote("First message", 0, 0),
NewNote("Second message", 0, 1),
NewNote("Third message", 1, 0),
NewNote("Fourth message", 0, 0)
};
using (var call = client.RouteChat())
{
var responseReaderTask = Task.Run(async () =>
{
while (await call.ResponseStream.MoveNext())
{
var note = call.ResponseStream.Current;
Log("Got message \"{0}\" at {1}, {2}", note.Message,
note.Location.Latitude, note.Location.Longitude);
}
});
foreach (RouteNote request in requests)
{
Log("Sending message \"{0}\" at {1}, {2}", request.Message,
request.Location.Latitude, request.Location.Longitude);
await call.RequestStream.WriteAsync(request);
}
await call.RequestStream.CompleteAsync();
await responseReaderTask;
Log("Finished RouteChat");
}
}
catch (RpcException e)
{
Log("RPC failed", e);
throw;
}
}
private void Log(string s, params object[] args)
{
Console.WriteLine(string.Format(s, args));
}
private void Log(string s)
{
Console.WriteLine(s);
}
private RouteNote NewNote(string message, int lat, int lon)
{
return new RouteNote
{
Message = message,
Location = new Point { Latitude = lat, Longitude = lon }
};
}
}
static void Main(string[] args)
{
var channel = new Channel("127.0.0.1:50052", ChannelCredentials.Insecure);
var client = new RouteGuideClient(new RouteGuide.RouteGuideClient(channel));
// Looking for a valid feature
client.GetFeature(409146138, -746188906);
// Feature missing.
client.GetFeature(0, 0);
// Looking for features between 40, -75 and 42, -73.
client.ListFeatures(400000000, -750000000, 420000000, -730000000).Wait();
// Record a few randomly selected points from the features file.
client.RecordRoute(RouteGuideUtil.ParseFeatures(RouteGuideUtil.DefaultFeaturesFile), 10).Wait();
// Send and receive some notes.
client.RouteChat().Wait();
channel.ShutdownAsync().Wait();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
| |
using System.Web.Security;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Diagnostics;
using System.Web;
using System.Globalization;
/*
-- Please, send me an email (andriniaina@gmail.com) if you have done some improvements or bug corrections to this file
CREATE TABLE Roles
(
Rolename Varchar (255) NOT NULL,
ApplicationName varchar (255) NOT NULL
)
CREATE TABLE UsersInRoles
(
Username Varchar (255) NOT NULL,
Rolename Varchar (255) NOT NULL,
ApplicationName Text (255) NOT NULL
)
ALTER TABLE `usersinroles` ADD INDEX ( `Username` , `Rolename` , `ApplicationName` ) ;
ALTER TABLE `roles` ADD INDEX ( `Rolename` , `ApplicationName` ) ;
*/
namespace AuditoriaParlamentar.Classes
{
public sealed class MySqlRoleProvider : RoleProvider
{
//
// Global connection string, generic exception message, event log info.
//
private string rolesTable = "roles";
private string usersInRolesTable = "usersinroles";
private string eventSource = "MySqlRoleProvider";
private string eventLog = "Application";
private string exceptionMessage = "An exception occurred. Please check the Event Log.";
private ConnectionStringSettings pConnectionStringSettings;
private string connectionString;
//
// If false, exceptions are thrown to the caller. If true,
// exceptions are written to the event log.
//
private bool pWriteExceptionsToEventLog = false;
public bool WriteExceptionsToEventLog
{
get { return pWriteExceptionsToEventLog; }
set { pWriteExceptionsToEventLog = value; }
}
//
// System.Configuration.Provider.ProviderBase.Initialize Method
//
public override void Initialize(string name, NameValueCollection config)
{
//
// Initialize values from web.config.
//
if (config == null)
throw new ArgumentNullException("config");
if (name == null || name.Length == 0)
name = "MySqlRoleProvider";
if (String.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "Sample MySql Role provider");
}
// Initialize the abstract base class.
base.Initialize(name, config);
if (config["applicationName"] == null || config["applicationName"].Trim() == "")
{
pApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
}
else
{
pApplicationName = config["applicationName"];
}
if (config["writeExceptionsToEventLog"] != null)
{
if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
{
pWriteExceptionsToEventLog = true;
}
}
//
// Initialize MySqlConnection.
//
pConnectionStringSettings = ConfigurationManager.
ConnectionStrings[config["connectionStringName"]];
if (pConnectionStringSettings == null || pConnectionStringSettings.ConnectionString.Trim() == "")
{
throw new ProviderException("Connection string cannot be blank.");
}
connectionString = pConnectionStringSettings.ConnectionString;
}
//
// System.Web.Security.RoleProvider properties.
//
private string pApplicationName;
public override string ApplicationName
{
get { return pApplicationName; }
set { pApplicationName = value; }
}
//
// System.Web.Security.RoleProvider methods.
//
//
// RoleProvider.AddUsersToRoles
//
public override void AddUsersToRoles(string[] usernames, string[] rolenames)
{
foreach (string rolename in rolenames)
{
if (!RoleExists(rolename))
{
throw new ProviderException("Role name not found.");
}
}
foreach (string username in usernames)
{
if (username.IndexOf(',') > 0)
{
throw new ArgumentException("User names cannot contain commas.");
}
foreach (string rolename in rolenames)
{
if (IsUserInRole(username, rolename))
{
throw new ProviderException("User is already in role.");
}
}
}
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("INSERT INTO `" + usersInRolesTable + "`" +
" (Username, Rolename, ApplicationName) " +
" Values(?Username, ?Rolename, ?ApplicationName)", conn);
MySqlParameter userParm = cmd.Parameters.Add("?Username", MySqlDbType.VarChar, 255);
MySqlParameter roleParm = cmd.Parameters.Add("?Rolename", MySqlDbType.VarChar, 255);
cmd.Parameters.Add("?ApplicationName", MySqlDbType.VarChar, 255).Value = ApplicationName;
MySqlTransaction tran = null;
try
{
conn.Open();
tran = conn.BeginTransaction();
cmd.Transaction = tran;
foreach (string username in usernames)
{
foreach (string rolename in rolenames)
{
userParm.Value = username;
roleParm.Value = rolename;
cmd.ExecuteNonQuery();
}
}
tran.Commit();
}
catch (MySqlException e)
{
try
{
tran.Rollback();
}
catch { }
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "AddUsersToRoles");
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
}
//
// RoleProvider.CreateRole
//
public override void CreateRole(string rolename)
{
if (rolename.IndexOf(',') > 0)
{
throw new ArgumentException("Role names cannot contain commas.");
}
if (RoleExists(rolename))
{
throw new ProviderException("Role name already exists.");
}
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("INSERT INTO `" + rolesTable + "`" +
" (Rolename, ApplicationName) " +
" Values(?Rolename, ?ApplicationName)", conn);
cmd.Parameters.Add("?Rolename", MySqlDbType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("?ApplicationName", MySqlDbType.VarChar, 255).Value = ApplicationName;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (MySqlException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "CreateRole");
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
}
//
// RoleProvider.DeleteRole
//
public override bool DeleteRole(string rolename, bool throwOnPopulatedRole)
{
if (!RoleExists(rolename))
{
throw new ProviderException("Role does not exist.");
}
if (throwOnPopulatedRole && GetUsersInRole(rolename).Length > 0)
{
throw new ProviderException("Cannot delete a populated role.");
}
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("DELETE FROM `" + rolesTable + "`" +
" WHERE Rolename = ?Rolename AND ApplicationName = ?ApplicationName", conn);
cmd.Parameters.Add("?Rolename", MySqlDbType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("?ApplicationName", MySqlDbType.VarChar, 255).Value = ApplicationName;
MySqlCommand cmd2 = new MySqlCommand("DELETE FROM `" + usersInRolesTable + "`" +
" WHERE Rolename = ?Rolename AND ApplicationName = ?ApplicationName", conn);
cmd2.Parameters.Add("?Rolename", MySqlDbType.VarChar, 255).Value = rolename;
cmd2.Parameters.Add("?ApplicationName", MySqlDbType.VarChar, 255).Value = ApplicationName;
MySqlTransaction tran = null;
try
{
conn.Open();
tran = conn.BeginTransaction();
cmd.Transaction = tran;
cmd2.Transaction = tran;
cmd2.ExecuteNonQuery();
cmd.ExecuteNonQuery();
tran.Commit();
}
catch (MySqlException e)
{
try
{
tran.Rollback();
}
catch { }
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "DeleteRole");
return false;
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
return true;
}
//
// RoleProvider.GetAllRoles
//
public override string[] GetAllRoles()
{
string tmpRoleNames = "";
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("SELECT Rolename FROM `" + rolesTable + "`" +
" WHERE ApplicationName = ?ApplicationName", conn);
cmd.Parameters.Add("?ApplicationName", MySqlDbType.VarChar, 255).Value = ApplicationName;
MySqlDataReader reader = null;
try
{
conn.Open();
using(reader = cmd.ExecuteReader())
{
while (reader.Read())
{
tmpRoleNames += reader.GetString(0) + ",";
}
reader.Close();
}
}
catch (MySqlException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "GetAllRoles");
}
else
{
throw e;
}
}
finally
{
if (reader != null) { reader.Close(); }
conn.Close();
}
if (tmpRoleNames.Length > 0)
{
// Remove trailing comma.
tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
return tmpRoleNames.Split(',');
}
return new string[0];
}
//
// RoleProvider.GetRolesForUser
//
public override string[] GetRolesForUser(string username)
{
string tmpRoleNames = "";
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("SELECT Rolename FROM `" + usersInRolesTable + "`" +
" WHERE Username = ?Username AND ApplicationName = ?ApplicationName", conn);
cmd.Parameters.Add("?Username", MySqlDbType.VarChar, 255).Value = username;
cmd.Parameters.Add("?ApplicationName", MySqlDbType.VarChar, 255).Value = ApplicationName;
MySqlDataReader reader = null;
try
{
conn.Open();
using(reader = cmd.ExecuteReader())
{
while (reader.Read())
{
tmpRoleNames += reader.GetString(0) + ",";
}
reader.Close();
}
}
catch (MySqlException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "GetRolesForUser");
}
else
{
throw e;
}
}
finally
{
if (reader != null) { reader.Close(); }
conn.Close();
}
if (tmpRoleNames.Length > 0)
{
// Remove trailing comma.
tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
return tmpRoleNames.Split(',');
}
return new string[0];
}
//
// RoleProvider.GetUsersInRole
//
public override string[] GetUsersInRole(string rolename)
{
string tmpUserNames = "";
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("SELECT Username FROM `" + usersInRolesTable + "`" +
" WHERE Rolename = ?Rolename AND ApplicationName = ?ApplicationName", conn);
cmd.Parameters.Add("?Rolename", MySqlDbType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("?ApplicationName", MySqlDbType.VarChar, 255).Value = ApplicationName;
MySqlDataReader reader = null;
try
{
conn.Open();
using(reader = cmd.ExecuteReader())
{
while (reader.Read())
{
tmpUserNames += reader.GetString(0) + ",";
}
reader.Close();
}
}
catch (MySqlException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "GetUsersInRole");
}
else
{
throw e;
}
}
finally
{
if (reader != null) { reader.Close(); }
conn.Close();
}
if (tmpUserNames.Length > 0)
{
// Remove trailing comma.
tmpUserNames = tmpUserNames.Substring(0, tmpUserNames.Length - 1);
return tmpUserNames.Split(',');
}
return new string[0];
}
//
// RoleProvider.IsUserInRole
//
public override bool IsUserInRole(string username, string rolename)
{
bool userIsInRole = false;
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM `" + usersInRolesTable + "`" +
" WHERE Username = ?Username AND Rolename = ?Rolename AND ApplicationName = ?ApplicationName", conn);
cmd.Parameters.Add("?Username", MySqlDbType.VarChar, 255).Value = username;
cmd.Parameters.Add("?Rolename", MySqlDbType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("?ApplicationName", MySqlDbType.VarChar, 255).Value = ApplicationName;
try
{
conn.Open();
long numRecs = Convert.ToInt64(cmd.ExecuteScalar());
if (numRecs > 0)
{
userIsInRole = true;
}
}
catch (MySqlException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "IsUserInRole");
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
return userIsInRole;
}
//
// RoleProvider.RemoveUsersFromRoles
//
public override void RemoveUsersFromRoles(string[] usernames, string[] rolenames)
{
foreach (string rolename in rolenames)
{
if (!RoleExists(rolename))
{
throw new ProviderException("Role name not found.");
}
}
foreach (string username in usernames)
{
foreach (string rolename in rolenames)
{
if (!IsUserInRole(username, rolename))
{
throw new ProviderException("User is not in role.");
}
}
}
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("DELETE FROM `" + usersInRolesTable + "`" +
" WHERE Username = ?Username AND Rolename = ?Rolename AND ApplicationName = ?ApplicationName", conn);
MySqlParameter userParm = cmd.Parameters.Add("?Username", MySqlDbType.VarChar, 255);
MySqlParameter roleParm = cmd.Parameters.Add("?Rolename", MySqlDbType.VarChar, 255);
cmd.Parameters.Add("?ApplicationName", MySqlDbType.VarChar, 255).Value = ApplicationName;
MySqlTransaction tran = null;
try
{
conn.Open();
tran = conn.BeginTransaction();
cmd.Transaction = tran;
foreach (string username in usernames)
{
foreach (string rolename in rolenames)
{
userParm.Value = username;
roleParm.Value = rolename;
cmd.ExecuteNonQuery();
}
}
tran.Commit();
}
catch (MySqlException e)
{
try
{
tran.Rollback();
}
catch { }
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "RemoveUsersFromRoles");
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
}
//
// RoleProvider.RoleExists
//
public override bool RoleExists(string rolename)
{
bool exists = false;
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM `" + rolesTable + "`" +
" WHERE Rolename = ?Rolename AND ApplicationName = ?ApplicationName", conn);
cmd.Parameters.Add("?Rolename", MySqlDbType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("?ApplicationName", MySqlDbType.VarChar, 255).Value = ApplicationName;
try
{
conn.Open();
long numRecs = Convert.ToInt64(cmd.ExecuteScalar());
if (numRecs > 0)
{
exists = true;
}
}
catch (MySqlException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "RoleExists");
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
return exists;
}
//
// RoleProvider.FindUsersInRole
//
public override string[] FindUsersInRole(string rolename, string usernameToMatch)
{
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("SELECT Username FROM `" + usersInRolesTable + "` " +
"WHERE Username LIKE ?UsernameSearch AND Rolename = ?Rolename AND ApplicationName = ?ApplicationName", conn);
cmd.Parameters.Add("?UsernameSearch", MySqlDbType.VarChar, 255).Value = usernameToMatch;
cmd.Parameters.Add("?RoleName", MySqlDbType.VarChar, 255).Value = rolename;
cmd.Parameters.Add("?ApplicationName", MySqlDbType.VarChar, 255).Value = pApplicationName;
string tmpUserNames = "";
MySqlDataReader reader = null;
try
{
conn.Open();
using(reader = cmd.ExecuteReader())
{
while (reader.Read())
{
tmpUserNames += reader.GetString(0) + ",";
}
reader.Close();
}
}
catch (MySqlException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "FindUsersInRole");
}
else
{
throw e;
}
}
finally
{
if (reader != null) { reader.Close(); }
conn.Close();
}
if (tmpUserNames.Length > 0)
{
// Remove trailing comma.
tmpUserNames = tmpUserNames.Substring(0, tmpUserNames.Length - 1);
return tmpUserNames.Split(',');
}
return new string[0];
}
//
// WriteToEventLog
// A helper function that writes exception detail to the event log. Exceptions
// are written to the event log as a security measure to avoid private database
// details from being returned to the browser. If a method does not return a status
// or boolean indicating the action succeeded or failed, a generic exception is also
// thrown by the caller.
//
private void WriteToEventLog(MySqlException e, string action)
{
EventLog log = new EventLog();
log.Source = eventSource;
log.Log = eventLog;
string message = exceptionMessage + "\n\n";
message += "Action: " + action + "\n\n";
message += "Exception: " + e.ToString();
log.WriteEntry(message);
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Report Anomaly Event Store
///<para>SObject Name: ReportAnomalyEventStore</para>
///<para>Custom Object: False</para>
///</summary>
public class SfReportAnomalyEventStore : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ReportAnomalyEventStore"; }
}
///<summary>
/// Report Anomaly Event Store ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Event Name
/// <para>Name: ReportAnomalyEventNumber</para>
/// <para>SF Type: string</para>
/// <para>AutoNumber field</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "reportAnomalyEventNumber")]
[Updateable(false), Createable(false)]
public string ReportAnomalyEventNumber { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Last Viewed Date
/// <para>Name: LastViewedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastViewedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastViewedDate { get; set; }
///<summary>
/// Last Referenced Date
/// <para>Name: LastReferencedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastReferencedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastReferencedDate { get; set; }
///<summary>
/// Event ID
/// <para>Name: EventIdentifier</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "eventIdentifier")]
[Updateable(false), Createable(false)]
public string EventIdentifier { get; set; }
///<summary>
/// User ID
/// <para>Name: UserId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "userId")]
[Updateable(false), Createable(false)]
public string UserId { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: User</para>
///</summary>
[JsonProperty(PropertyName = "user")]
[Updateable(false), Createable(false)]
public SfUser User { get; set; }
///<summary>
/// Username
/// <para>Name: Username</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "username")]
[Updateable(false), Createable(false)]
public string Username { get; set; }
///<summary>
/// Event Date
/// <para>Name: EventDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "eventDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? EventDate { get; set; }
///<summary>
/// Session Key
/// <para>Name: SessionKey</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "sessionKey")]
[Updateable(false), Createable(false)]
public string SessionKey { get; set; }
///<summary>
/// Login Key
/// <para>Name: LoginKey</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "loginKey")]
[Updateable(false), Createable(false)]
public string LoginKey { get; set; }
///<summary>
/// Source IP Address
/// <para>Name: SourceIp</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "sourceIp")]
[Updateable(false), Createable(false)]
public string SourceIp { get; set; }
///<summary>
/// Transaction Security Policy ID
/// <para>Name: PolicyId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "policyId")]
[Updateable(false), Createable(false)]
public string PolicyId { get; set; }
///<summary>
/// ReferenceTo: TransactionSecurityPolicy
/// <para>RelationshipName: Policy</para>
///</summary>
[JsonProperty(PropertyName = "policy")]
[Updateable(false), Createable(false)]
public SfTransactionSecurityPolicy Policy { get; set; }
///<summary>
/// Policy Outcome
/// <para>Name: PolicyOutcome</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "policyOutcome")]
[Updateable(false), Createable(false)]
public string PolicyOutcome { get; set; }
///<summary>
/// Evaluation Time
/// <para>Name: EvaluationTime</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "evaluationTime")]
[Updateable(false), Createable(false)]
public double? EvaluationTime { get; set; }
///<summary>
/// Report ID
/// <para>Name: Report</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "report")]
[Updateable(false), Createable(false)]
public string Report { get; set; }
///<summary>
/// Score
/// <para>Name: Score</para>
/// <para>SF Type: double</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "score")]
[Updateable(false), Createable(false)]
public double? Score { get; set; }
///<summary>
/// Summary
/// <para>Name: Summary</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "summary")]
[Updateable(false), Createable(false)]
public string Summary { get; set; }
///<summary>
/// Event Data
/// <para>Name: SecurityEventData</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "securityEventData")]
[Updateable(false), Createable(false)]
public string SecurityEventData { get; set; }
}
}
| |
//
// HigMessageDialog.cs
//
// Authors:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace Hyena.Widgets
{
public class HigMessageDialog : Gtk.Dialog
{
private Gtk.Image image;
private Gtk.VBox inner_vbox;
private Gtk.VBox label_vbox;
private Gtk.Label message_label;
public HigMessageDialog(Gtk.Window parent,
Gtk.DialogFlags flags,
Gtk.MessageType type,
Gtk.ButtonsType buttons,
string header,
string msg)
: base()
{
HasSeparator = false;
BorderWidth = 5;
Resizable = false;
Title = "";
SkipTaskbarHint = true;
VBox.Spacing = 12;
ActionArea.Layout = Gtk.ButtonBoxStyle.End;
Gtk.HBox hbox = new Gtk.HBox (false, 12);
hbox.BorderWidth = 5;
hbox.Show ();
VBox.PackStart (hbox, false, false, 0);
image = null;
switch (type) {
case Gtk.MessageType.Error:
image = new Gtk.Image (Gtk.Stock.DialogError, Gtk.IconSize.Dialog);
break;
case Gtk.MessageType.Question:
image = new Gtk.Image (Gtk.Stock.DialogQuestion, Gtk.IconSize.Dialog);
break;
case Gtk.MessageType.Info:
image = new Gtk.Image (Gtk.Stock.DialogInfo, Gtk.IconSize.Dialog);
break;
case Gtk.MessageType.Warning:
image = new Gtk.Image (Gtk.Stock.DialogWarning, Gtk.IconSize.Dialog);
break;
}
image.Yalign = 0.1f;
image.Show ();
hbox.PackStart (image, false, false, 0);
inner_vbox = new Gtk.VBox (false, 12);
inner_vbox.Show ();
hbox.PackStart (inner_vbox, true, true, 0);
label_vbox = new Gtk.VBox (false, 0);
label_vbox.Show ();
inner_vbox.PackStart (label_vbox, true, true, 0);
string title = String.Format ("<span weight='bold' size='larger'>{0}" +
"</span>\n",
GLib.Markup.EscapeText (header));
Gtk.Label label;
label = new Gtk.Label (title);
label.UseMarkup = true;
label.Justify = Gtk.Justification.Left;
label.LineWrap = true;
label.SetAlignment (0.0f, 0.5f);
label.Show ();
label_vbox.PackStart (label, false, false, 0);
message_label = label = new Gtk.Label ();
label.Text = msg;
label.Justify = Gtk.Justification.Left;
label.LineWrap = true;
label.SetAlignment (0.0f, 0.5f);
label.Show ();
label_vbox.PackStart (label, false, false, 0);
switch (buttons) {
case Gtk.ButtonsType.None:
break;
case Gtk.ButtonsType.Ok:
AddButton (Gtk.Stock.Ok, Gtk.ResponseType.Ok, true);
break;
case Gtk.ButtonsType.Close:
AddButton (Gtk.Stock.Close, Gtk.ResponseType.Close, true);
break;
case Gtk.ButtonsType.Cancel:
AddButton (Gtk.Stock.Cancel, Gtk.ResponseType.Cancel, true);
break;
case Gtk.ButtonsType.YesNo:
AddButton (Gtk.Stock.No, Gtk.ResponseType.No, false);
AddButton (Gtk.Stock.Yes, Gtk.ResponseType.Yes, true);
break;
case Gtk.ButtonsType.OkCancel:
AddButton (Gtk.Stock.Cancel, Gtk.ResponseType.Cancel, false);
AddButton (Gtk.Stock.Ok, Gtk.ResponseType.Ok, true);
break;
}
if (parent != null)
TransientFor = parent;
if ((int) (flags & Gtk.DialogFlags.Modal) != 0)
Modal = true;
if ((int) (flags & Gtk.DialogFlags.DestroyWithParent) != 0)
DestroyWithParent = true;
}
// constructor for a HIG confirmation alert with two buttons
public HigMessageDialog (Gtk.Window parent,
Gtk.DialogFlags flags,
Gtk.MessageType type,
string header,
string msg,
string ok_caption)
: this (parent, flags, type, Gtk.ButtonsType.Cancel, header, msg)
{
AddButton (ok_caption, Gtk.ResponseType.Ok, false);
}
public Gtk.Button AddCustomButton (string message, Gtk.ResponseType response, bool isDefault)
{
Gtk.Button button = new Gtk.Button ();
button.Label = message;
button.CanDefault = true;
button.Show ();
AddButton (button, response, isDefault);
return button;
}
public void AddButton (string stock_id, Gtk.ResponseType response, bool isDefault)
{
Gtk.Button button = new Gtk.Button (stock_id);
button.CanDefault = true;
button.Show ();
AddButton (button, response, isDefault);
}
private void AddButton (Gtk.Button button, Gtk.ResponseType response, bool isDefault)
{
AddActionWidget (button, response);
if (isDefault) {
Default = button;
DefaultResponse = response;
button.GrabDefault ();
}
}
//run and destroy a standard dialog
public static Gtk.ResponseType RunHigMessageDialog(Gtk.Window parent,
Gtk.DialogFlags flags,
Gtk.MessageType type,
Gtk.ButtonsType buttons,
string header,
string msg)
{
HigMessageDialog hmd = new HigMessageDialog(parent, flags, type, buttons, header, msg);
try {
return (Gtk.ResponseType)hmd.Run();
} finally {
hmd.Destroy();
}
}
//Run and destroy a standard confirmation dialog
public static Gtk.ResponseType RunHigConfirmation(Gtk.Window parent,
Gtk.DialogFlags flags,
Gtk.MessageType type,
string header,
string msg,
string ok_caption)
{
HigMessageDialog hmd = new HigMessageDialog(parent, flags, type, header, msg, ok_caption);
try {
return (Gtk.ResponseType)hmd.Run();
} finally {
hmd.Destroy();
}
}
public Gdk.Pixbuf Image {
set {
image.Pixbuf = value;
}
get {
return image.Pixbuf;
}
}
public Gtk.Label MessageLabel {
get { return message_label; }
}
public Gtk.VBox LabelVBox {
get { return inner_vbox; }
}
}
}
| |
using System;
using SilentOrbit.Code;
namespace SilentOrbit.ProtocolBuffers
{
class MessageSerializer
{
readonly CodeWriter cw;
readonly Options options;
readonly FieldSerializer fieldSerializer;
public MessageSerializer(CodeWriter cw, Options options)
{
this.cw = cw;
this.options = options;
this.fieldSerializer = new FieldSerializer(cw, options);
}
public void GenerateClassSerializer(ProtoMessage m)
{
if (options.NoGenerateImported && m.IsImported)
{
Console.Error.WriteLine("Skipping imported " + m.FullProtoName);
return;
}
if (m.OptionExternal || m.OptionType == "interface")
{
//Don't make partial class of external classes or interfaces
//Make separate static class for them
cw.Bracket(m.OptionAccess + " static class " + m.SerializerType);
}
else
{
if (options.SerializableAttributes)
{
cw.Attribute("System.Serializable");
}
cw.Bracket(m.OptionAccess + " partial " + m.OptionType + " " + m.SerializerType);
}
GenerateReader(m);
GenerateWriter(m);
foreach (ProtoMessage sub in m.Messages.Values)
{
cw.WriteLine();
GenerateClassSerializer(sub);
}
cw.EndBracket();
cw.WriteLine();
return;
}
void GenerateReader(ProtoMessage m)
{
#region Helper Deserialize Methods
string refstr = (m.OptionType == "struct") ? "ref " : "";
if (m.OptionType != "interface")
{
cw.Summary("Helper: create a new instance to deserializing into");
cw.Bracket(m.OptionAccess + " static " + m.CsType + " Deserialize(Stream stream)");
cw.WriteLine("var instance = new " + m.CsType + "();");
cw.WriteLine("Deserialize(stream, " + refstr + "instance);");
cw.WriteLine("return instance;");
cw.EndBracketSpace();
cw.Summary("Helper: create a new instance to deserializing into");
cw.Bracket(m.OptionAccess + " static " + m.CsType + " DeserializeLengthDelimited(Stream stream)");
cw.WriteLine("var instance = new " + m.CsType + "();");
cw.WriteLine("DeserializeLengthDelimited(stream, " + refstr + "instance);");
cw.WriteLine("return instance;");
cw.EndBracketSpace();
cw.Summary("Helper: create a new instance to deserializing into");
cw.Bracket(m.OptionAccess + " static " + m.CsType + " DeserializeLength(Stream stream, int length)");
cw.WriteLine("var instance = new " + m.CsType + "();");
cw.WriteLine("DeserializeLength(stream, length, " + refstr + "instance);");
cw.WriteLine("return instance;");
cw.EndBracketSpace();
cw.Summary("Helper: put the buffer into a MemoryStream and create a new instance to deserializing into");
cw.Bracket(m.OptionAccess + " static " + m.CsType + " Deserialize(byte[] buffer)");
cw.WriteLine("var instance = new " + m.CsType + "();");
cw.WriteLine("using (var ms = new MemoryStream(buffer))");
cw.WriteIndent("Deserialize(ms, " + refstr + "instance);");
cw.WriteLine("return instance;");
cw.EndBracketSpace();
}
cw.Summary("Helper: put the buffer into a MemoryStream before deserializing");
cw.Bracket(m.OptionAccess + " static " + m.FullCsType + " Deserialize(byte[] buffer, " + refstr + m.FullCsType + " instance)");
cw.WriteLine("using (var ms = new MemoryStream(buffer))");
cw.WriteIndent("Deserialize(ms, " + refstr + "instance);");
cw.WriteLine("return instance;");
cw.EndBracketSpace();
#endregion Helper Deserialize Methods
string[] methods = new string[]
{
"Deserialize", //Default old one
"DeserializeLengthDelimited", //Start by reading length prefix and stay within that limit
"DeserializeLength", //Read at most length bytes given by argument
};
//Main Deserialize
foreach (string method in methods)
{
if (method == "Deserialize")
{
cw.Summary("Takes the remaining content of the stream and deserialze it into the instance.");
cw.Bracket(m.OptionAccess + " static " + m.FullCsType + " " + method + "(Stream stream, " + refstr + m.FullCsType + " instance)");
}
else if (method == "DeserializeLengthDelimited")
{
cw.Summary("Read the VarInt length prefix and the given number of bytes from the stream and deserialze it into the instance.");
cw.Bracket(m.OptionAccess + " static " + m.FullCsType + " " + method + "(Stream stream, " + refstr + m.FullCsType + " instance)");
}
else if (method == "DeserializeLength")
{
cw.Summary("Read the given number of bytes from the stream and deserialze it into the instance.");
cw.Bracket(m.OptionAccess + " static " + m.FullCsType + " " + method + "(Stream stream, int length, " + refstr + m.FullCsType + " instance)");
}
else
{
throw new NotImplementedException();
}
if (m.IsUsingBinaryWriter)
{
cw.WriteLine("var br = new BinaryReader(stream);");
}
//Prepare List<> and default values
foreach (Field f in m.Fields.Values)
{
if (f.OptionDeprecated)
{
cw.WritePragma("warning disable 612");
}
if (f.Rule == FieldRule.Repeated)
{
if (f.OptionReadOnly == false)
{
//Initialize lists of the custom DateTime or TimeSpan type.
string csType = f.ProtoType.FullCsType;
if (f.OptionCodeType != null)
{
csType = f.OptionCodeType;
}
cw.WriteLine("if (instance." + f.CsName + " == null)");
cw.WriteIndent("instance." + f.CsName + " = new List<" + csType + ">();");
}
}
else if (f.OptionDefault != null)
{
cw.WriteLine("instance." + f.CsName + " = " + f.FormatDefaultForTypeAssignment() + ";");
}
else if ((f.Rule == FieldRule.Optional) && !options.Nullable)
{
if (f.ProtoType is ProtoEnum pe)
{
//the default value is the first value listed in the enum's type definition
foreach (var kvp in pe.Enums)
{
cw.WriteLine("instance." + f.CsName + " = " + pe.FullCsType + "." + kvp.Name + ";");
break;
}
}
}
if (f.OptionDeprecated)
{
cw.WritePragma("warning restore 612");
}
}
if (method == "DeserializeLengthDelimited")
{
//Important to read stream position after we have read the length field
cw.WriteLine("long limit = " + ProtocolParser.Base + ".ReadUInt32(stream);");
cw.WriteLine("limit += stream.Position;");
}
if (method == "DeserializeLength")
{
//Important to read stream position after we have read the length field
cw.WriteLine("long limit = stream.Position + length;");
}
cw.WhileBracket("true");
if (method == "DeserializeLengthDelimited" || method == "DeserializeLength")
{
cw.IfBracket("stream.Position >= limit");
cw.WriteLine("if (stream.Position == limit)");
cw.WriteIndent("break;");
cw.WriteLine("else");
cw.WriteIndent("throw new global::SilentOrbit.ProtocolBuffers.ProtocolBufferException(\"Read past max limit\");");
cw.EndBracket();
}
cw.WriteLine("int keyByte = stream.ReadByte();");
cw.WriteLine("if (keyByte == -1)");
if (method == "Deserialize")
{
cw.WriteIndent("break;");
}
else
{
cw.WriteIndent("throw new System.IO.EndOfStreamException();");
}
//Determine if we need the lowID optimization
bool hasLowID = false;
foreach (Field f in m.Fields.Values)
{
if (f.ID < 16)
{
hasLowID = true;
break;
}
}
if (hasLowID)
{
cw.Comment("Optimized reading of known fields with field ID < 16");
cw.Switch("keyByte");
foreach (Field f in m.Fields.Values)
{
if (f.ID >= 16)
{
continue;
}
if (f.OptionDeprecated)
{
cw.WritePragma("warning disable 612");
}
cw.Dedent();
cw.Comment("Field " + f.ID + " " + f.WireType);
cw.Indent();
cw.Case((f.ID << 3) | (int)f.WireType);
if (fieldSerializer.FieldReader(f))
{
cw.WriteLine("continue;");
}
if (f.OptionDeprecated)
{
cw.WritePragma("warning restore 612");
}
}
cw.SwitchEnd();
cw.WriteLine();
}
cw.WriteLine("var key = " + ProtocolParser.Base + ".ReadKey((byte)keyByte, stream);");
cw.WriteLine();
cw.Comment("Reading field ID > 16 and unknown field ID/wire type combinations");
cw.Switch("key.Field");
cw.Case(0);
cw.WriteLine("throw new global::SilentOrbit.ProtocolBuffers.ProtocolBufferException(\"Invalid field id: 0, something went wrong in the stream\");");
foreach (Field f in m.Fields.Values)
{
if (f.ID < 16)
{
continue;
}
cw.Case(f.ID);
//Makes sure we got the right wire type
cw.WriteLine("if(key.WireType != global::SilentOrbit.ProtocolBuffers.Wire." + f.WireType + ")");
cw.WriteIndent("break;"); //This can be changed to throw an exception for unknown formats.
if (f.OptionDeprecated)
{
cw.WritePragma("warning disable 612");
}
if (fieldSerializer.FieldReader(f))
{
cw.WriteLine("continue;");
}
if (f.OptionDeprecated)
{
cw.WritePragma("warning restore 612");
}
}
cw.CaseDefault();
if (m.OptionPreserveUnknown)
{
cw.WriteLine("if (instance.PreservedFields == null)");
cw.WriteIndent("instance.PreservedFields = new List<global::SilentOrbit.ProtocolBuffers.KeyValue>();");
cw.WriteLine("instance.PreservedFields.Add(new global::SilentOrbit.ProtocolBuffers.KeyValue(key, " + ProtocolParser.Base + ".ReadValueBytes(stream, key)));");
}
else
{
cw.WriteLine(ProtocolParser.Base + ".SkipKey(stream, key);");
}
cw.WriteLine("break;");
cw.SwitchEnd();
cw.EndBracket();
cw.WriteLine();
if (m.OptionTriggers)
{
cw.WriteLine("instance.AfterDeserialize();");
}
cw.WriteLine("return instance;");
cw.EndBracket();
cw.WriteLine();
}
return;
}
/// <summary>
/// Generates code for writing a class/message
/// </summary>
void GenerateWriter(ProtoMessage m)
{
string stack = "global::SilentOrbit.ProtocolBuffers.ProtocolParser.Stack";
if (options.ExperimentalStack != null)
{
cw.WriteLine("[ThreadStatic]");
cw.WriteLine("static global::SilentOrbit.ProtocolBuffers.MemoryStreamStack stack = new " + options.ExperimentalStack + "();");
stack = "stack";
}
cw.Summary("Serialize the instance into the stream");
cw.Bracket(m.OptionAccess + " static void Serialize(Stream stream, " + m.CsType + " instance)");
if (m.OptionTriggers)
{
cw.WriteLine("instance.BeforeSerialize();");
cw.WriteLine();
}
if (m.IsUsingBinaryWriter)
{
cw.WriteLine("var bw = new BinaryWriter(stream);");
}
//Shared memorystream for all fields
cw.WriteLine("var msField = " + stack + ".Pop();");
foreach (Field f in m.Fields.Values)
{
if (f.OptionDeprecated)
{
cw.WritePragma("warning disable 612");
}
fieldSerializer.FieldWriter(f);
if (f.OptionDeprecated)
{
cw.WritePragma("warning restore 612");
}
}
cw.WriteLine(stack + ".Push(msField);");
if (m.OptionPreserveUnknown)
{
cw.IfBracket("instance.PreservedFields != null");
cw.ForeachBracket("var kv in instance.PreservedFields");
cw.WriteLine("global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteKey(stream, kv.Key);");
cw.WriteLine("stream.Write(kv.Value, 0, kv.Value.Length);");
cw.EndBracket();
cw.EndBracket();
}
cw.EndBracket();
cw.WriteLine();
cw.Summary("Helper: Serialize into a MemoryStream and return its byte array");
cw.Bracket(m.OptionAccess + " static byte[] SerializeToBytes(" + m.CsType + " instance)");
cw.Using("var ms = new MemoryStream()");
cw.WriteLine("Serialize(ms, instance);");
cw.WriteLine("return ms.ToArray();");
cw.EndBracket();
cw.EndBracket();
cw.Summary("Helper: Serialize with a varint length prefix");
cw.Bracket(m.OptionAccess + " static void SerializeLengthDelimited(Stream stream, " + m.CsType + " instance)");
cw.WriteLine("var data = SerializeToBytes(instance);");
cw.WriteLine("global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, (uint)data.Length);");
cw.WriteLine("stream.Write(data, 0, data.Length);");
cw.EndBracket();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Text;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Text.Analyzers.IdentifiersShouldBeSpelledCorrectlyAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Text.Analyzers.UnitTests
{
public class IdentifiersShouldBeSpelledCorrectlyTests
{
public enum DictionaryType
{
Xml,
Dic,
}
public static IEnumerable<object[]> MisspelledMembers
=> new[]
{
new object[] { CreateTypeWithConstructor("Clazz", constructorName: "{|#0:Clazz|}", isStatic: false), "Clazz", "Clazz.Clazz()" },
new object[] { CreateTypeWithConstructor("Clazz", constructorName: "{|#0:Clazz|}", isStatic: true), "Clazz", "Clazz.Clazz()" },
new object[] { CreateTypeWithField("Program", "{|#0:_fild|}"), "fild", "Program._fild" },
new object[] { CreateTypeWithEvent("Program", "{|#0:Evt|}"), "Evt", "Program.Evt" },
new object[] { CreateTypeWithProperty("Program", "{|#0:Naem|}"), "Naem", "Program.Naem" },
new object[] { CreateTypeWithMethod("Program", "{|#0:SomeMathod|}"), "Mathod", "Program.SomeMathod()" },
};
public static IEnumerable<object[]> UnmeaningfulMembers
=> new[]
{
new object[] { CreateTypeWithConstructor("A", constructorName: "{|#0:A|}", isStatic: false), "A" },
new object[] { CreateTypeWithConstructor("B", constructorName: "{|#0:B|}", isStatic: false), "B" },
new object[] { CreateTypeWithField("Program", "{|#0:_c|}"), "c" },
new object[] { CreateTypeWithEvent("Program", "{|#0:D|}"), "D" },
new object[] { CreateTypeWithProperty("Program", "{|#0:E|}"), "E" },
new object[] { CreateTypeWithMethod("Program", "{|#0:F|}"), "F" },
};
public static IEnumerable<object[]> MisspelledMemberParameters
=> new[]
{
new object[] { CreateTypeWithConstructor("Program", parameter: "int {|#0:yourNaem|}", isStatic: false), "Naem", "yourNaem", "Program.Program(int)" },
new object[] { CreateTypeWithMethod("Program", "Method", "int {|#0:yourNaem|}"), "Naem", "yourNaem", "Program.Method(int)" },
new object[] { CreateTypeWithIndexer("Program", "int {|#0:yourNaem|}"), "Naem", "yourNaem", "Program.this[int]" },
};
[Theory]
[InlineData("namespace Bar { }")]
[InlineData("class Program { }")]
[InlineData("class Program { void Member() { } }")]
[InlineData("class Program { int _variable = 1; }")]
[InlineData("class Program { void Member(string name) { } }")]
[InlineData("class Program { delegate int GetNumber(string name); }")]
[InlineData("class Program<TResource> { }")]
public async Task NoMisspellings_Verify_NoDiagnostics(string source)
{
await VerifyCSharpAsync(source);
}
[Fact]
public async Task MisspellingAllowedByGlobalXmlDictionary_Verify_NoDiagnostics()
{
var source = "class Clazz { }";
var dictionary = CreateXmlDictionary(new[] { "clazz" });
await VerifyCSharpAsync(source, dictionary);
}
[Fact]
public async Task MisspellingAllowedByGlobalDicDictionary_Verify_NoDiagnostics()
{
var source = "class Clazz { }";
var dictionary = CreateDicDictionary(new[] { "clazz" });
await VerifyCSharpAsync(source, dictionary);
}
[Fact]
public async Task MisspellingsAllowedByMultipleGlobalDictionaries_Verify_NoDiagnostics()
{
var source = @"class Clazz { const string Naem = ""foo""; }";
var xmlDictionary = CreateXmlDictionary(new[] { "clazz" });
var dicDictionary = CreateDicDictionary(new[] { "naem" });
await VerifyCSharpAsync(source, new[] { xmlDictionary, dicDictionary });
}
[Fact]
public async Task CorrectWordDisallowedByGlobalXmlDictionary_Verify_EmitsDiagnostic()
{
var source = "class {|#0:Program|} { }";
var dictionary = CreateXmlDictionary(null, new[] { "program" });
await VerifyCSharpAsync(
source,
dictionary,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeRule)
.WithLocation(0)
.WithArguments("Program", "Program"));
}
[Fact]
public async Task MisspellingAllowedByProjectDictionary_Verify_NoDiagnostics()
{
var source = "class Clazz {}";
var dictionary = CreateDicDictionary(new[] { "clazz" });
await VerifyCSharpAsync(source, dictionary);
}
[Fact]
public async Task MisspellingAllowedByDifferentProjectDictionary_Verify_EmitsDiagnostic()
{
var source = "class {|#0:Clazz|} {}";
var dictionary = CreateDicDictionary(new[] { "clazz" });
var test = new VerifyCS.Test
{
TestState =
{
Sources = { source },
AdditionalProjects =
{
["OtherProject"] =
{
AdditionalFiles = { dictionary }
},
},
AdditionalProjectReferences = { "OtherProject" }
},
ExpectedDiagnostics =
{
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeRule)
.WithLocation(0)
.WithArguments("Clazz", "Clazz")
}
};
await test.RunAsync();
}
[Fact]
public async Task AssemblyMisspelled_Verify_EmitsDiagnostic()
{
var source = "{|#0:class Program {}|}";
var test = new VerifyCS.Test
{
TestState =
{
Sources = { source },
},
SolutionTransforms =
{
(solution, projectId) => RenameProjectAssembly(solution, projectId),
},
ExpectedDiagnostics =
{
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.AssemblyRule)
.WithLocation(0)
.WithArguments("Assambly", "MyAssambly")
}
};
await test.RunAsync();
static Solution RenameProjectAssembly(Solution solution, ProjectId projectId)
{
return solution.WithProjectAssemblyName(projectId, "MyAssambly");
}
}
[Fact]
public async Task AssemblyUnmeaningful_Verify_EmitsDiagnostic()
{
var source = "{|#0:class Program {}|}";
var test = new VerifyCS.Test
{
TestState =
{
Sources = { source },
},
SolutionTransforms =
{
(solution, projectId) => RenameProjectAssembly(solution, projectId),
},
ExpectedDiagnostics =
{
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.AssemblyMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments("A")
}
};
await test.RunAsync();
static Solution RenameProjectAssembly(Solution solution, ProjectId projectId)
{
return solution.WithProjectAssemblyName(projectId, "A");
}
}
[Fact]
public async Task NamespaceMisspelled_Verify_EmitsDiagnostic()
{
var source = "namespace Tests.{|#0:MyNarmspace|} {}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.NamespaceRule)
.WithLocation(0)
.WithArguments("Narmspace", "Tests.MyNarmspace"));
}
[Fact]
public async Task NamespaceUnmeaningful_Verify_EmitsDiagnostic()
{
var source = "namespace Tests.{|#0:A|} {}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.NamespaceMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments("A"));
}
[Theory]
[InlineData("namespace MyNamespace { class {|#0:MyClazz|} {} }", "Clazz", "MyNamespace.MyClazz")]
[InlineData("namespace MyNamespace { struct {|#0:MyStroct|} {} }", "Stroct", "MyNamespace.MyStroct")]
[InlineData("namespace MyNamespace { enum {|#0:MyEnim|} {} }", "Enim", "MyNamespace.MyEnim")]
[InlineData("namespace MyNamespace { interface {|#0:IMyFase|} {} }", "Fase", "MyNamespace.IMyFase")]
[InlineData("namespace MyNamespace { delegate int {|#0:MyDelegete|}(); }", "Delegete", "MyNamespace.MyDelegete")]
public async Task TypeMisspelled_Verify_EmitsDiagnostic(string source, string misspelling, string typeName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeRule)
.WithLocation(0)
.WithArguments(misspelling, typeName));
}
[Theory]
[InlineData("class {|#0:A|} {}", "A")]
[InlineData("struct {|#0:B|} {}", "B")]
[InlineData("enum {|#0:C|} {}", "C")]
[InlineData("interface {|#0:ID|} {}", "D")]
[InlineData("delegate int {|#0:E|}();", "E")]
public async Task TypeUnmeaningful_Verify_EmitsDiagnostic(string source, string typeName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments(typeName));
}
[Theory]
[MemberData(nameof(MisspelledMembers))]
public async Task MemberMisspelled_Verify_EmitsDiagnostic(string source, string misspelling, string memberName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberRule)
.WithLocation(0)
.WithArguments(misspelling, memberName));
}
[Fact]
public async Task MemberOverrideMisspelled_Verify_EmitsDiagnosticOnlyAtDefinition()
{
var source = @"
abstract class Parent
{
protected abstract string {|#0:Naem|} { get; }
public abstract int {|#1:Mathod|}();
}
class Child : Parent
{
protected override string Naem => ""child"";
public override int Mathod() => 0;
}
class Grandchild : Child
{
protected override string Naem => ""grandchild"";
public override int Mathod() => 1;
}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberRule)
.WithLocation(0)
.WithArguments("Naem", "Parent.Naem"),
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberRule)
.WithLocation(1)
.WithArguments("Mathod", "Parent.Mathod()"));
}
[Theory]
[MemberData(nameof(UnmeaningfulMembers))]
public async Task MemberUnmeaningful_Verify_EmitsDiagnostic(string source, string memberName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments(memberName));
}
[Fact]
public async Task VariableMisspelled_Verify_EmitsDiagnostic()
{
var source = @"
class Program
{
public Program()
{
var {|#0:myVoriable|} = 5;
}
}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.VariableRule)
.WithLocation(0)
.WithArguments("Voriable", "myVoriable"));
}
[Theory]
[MemberData(nameof(MisspelledMemberParameters))]
public async Task MemberParameterMisspelled_Verify_EmitsDiagnostic(string source, string misspelling, string parameterName, string memberName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterRule)
.WithLocation(0)
.WithArguments(memberName, misspelling, parameterName));
}
[Fact]
public async Task MemberParameterUnmeaningful_Verify_EmitsDiagnostic()
{
var source = @"
class Program
{
public void Method(string {|#0:a|})
{
}
public string this[int {|#1:i|}] => null;
}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments("Program.Method(string)", "a"),
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterMoreMeaningfulNameRule)
.WithLocation(1)
.WithArguments("Program.this[int]", "i"));
}
[Fact]
public async Task DelegateParameterMisspelled_Verify_EmitsDiagnostic()
{
var source = "delegate void MyDelegate(string {|#0:firstNaem|});";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.DelegateParameterRule)
.WithLocation(0)
.WithArguments("MyDelegate", "Naem", "firstNaem"));
}
[Fact]
public async Task DelegateParameterUnmeaningful_Verify_EmitsDiagnostic()
{
var source = "delegate void MyDelegate(string {|#0:a|});";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.DelegateParameterMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments("MyDelegate", "a"));
}
[Theory]
[InlineData("class MyClass<TCorrect, {|#0:TWroong|}> { }", "MyClass<TCorrect, TWroong>", "Wroong", "TWroong")]
[InlineData("struct MyStructure<{|#0:TWroong|}> { }", "MyStructure<TWroong>", "Wroong", "TWroong")]
[InlineData("interface IInterface<{|#0:TWroong|}> { }", "IInterface<TWroong>", "Wroong", "TWroong")]
[InlineData("delegate int MyDelegate<{|#0:TWroong|}>();", "MyDelegate<TWroong>", "Wroong", "TWroong")]
public async Task TypeTypeParameterMisspelled_Verify_EmitsDiagnostic(string source, string typeName, string misspelling, string typeParameterName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeTypeParameterRule)
.WithLocation(0)
.WithArguments(typeName, misspelling, typeParameterName));
}
[Theory]
[InlineData("class MyClass<{|#0:A|}> { }", "MyClass<A>", "A")]
[InlineData("struct MyStructure<{|#0:B|}> { }", "MyStructure<B>", "B")]
[InlineData("interface IInterface<{|#0:C|}> { }", "IInterface<C>", "C")]
[InlineData("delegate int MyDelegate<{|#0:D|}>();", "MyDelegate<D>", "D")]
public async Task TypeTypeParameterUnmeaningful_Verify_EmitsDiagnostic(string source, string typeName, string typeParameterName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeTypeParameterMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments(typeName, typeParameterName));
}
[Fact]
public async Task MethodTypeParameterMisspelled_Verify_EmitsDiagnostic()
{
var source = @"
class Program
{
void Method<{|#0:TTipe|}>(TTipe item)
{
}
}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MethodTypeParameterRule)
.WithLocation(0)
.WithArguments("Program.Method<TTipe>(TTipe)", "Tipe", "TTipe"));
}
[Fact]
public async Task MethodTypeParameterUnmeaningful_Verify_EmitsDiagnostic()
{
var source = @"
class Program
{
void Method<{|#0:TA|}>(TA parameter)
{
}
}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MethodTypeParameterMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments("Program.Method<TA>(TA)", "TA"));
}
[Fact]
public async Task MisspellingContainsOnlyCapitalizedLetters_Verify_NoDiagnostics()
{
var source = "class FCCA { }";
await VerifyCSharpAsync(source);
}
[Theory]
[InlineData("0x0")]
[InlineData("0xDEADBEEF")]
public async Task MisspellingStartsWithADigit_Verify_NoDiagnostics(string misspelling)
{
var source = $"enum Name {{ My{misspelling} }}";
await VerifyCSharpAsync(source);
}
[Fact]
public async Task MalformedXmlDictionary_Verify_EmitsDiagnostic()
{
var contents = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Dictionary>
<Words>
<Recognized>
<Word>okay</Word>
<word>bad</Word> <!-- xml tags are case-sensitive -->
</Recognized>
</Words>
</Dictionary>";
var dictionary = ("CodeAnalysisDictionary.xml", contents);
await VerifyCSharpAsync(
"class Program {}",
dictionary,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.FileParseRule)
// Ignore diagnostic message comparison because the actual message
// includes localized content from an exception's message
.WithMessage(null));
}
private Task VerifyCSharpAsync(string source, params DiagnosticResult[] expected)
=> VerifyCSharpAsync(source, Array.Empty<(string Path, string Text)>(), expected);
private Task VerifyCSharpAsync(string source, (string Path, string Text) additionalText, params DiagnosticResult[] expected)
=> VerifyCSharpAsync(source, new[] { additionalText }, expected);
private async Task VerifyCSharpAsync(string source, (string Path, string Text)[] additionalTexts, params DiagnosticResult[] expected)
{
var csharpTest = new VerifyCS.Test
{
TestCode = source,
TestState =
{
AdditionalFilesFactories = { () => additionalTexts.Select(x => (x.Path, SourceText.From(x.Text))) }
},
TestBehaviors = TestBehaviors.SkipSuppressionCheck,
};
csharpTest.ExpectedDiagnostics.AddRange(expected);
await csharpTest.RunAsync();
}
private static (string Path, string Text) CreateXmlDictionary(IEnumerable<string> recognizedWords, IEnumerable<string> unrecognizedWords = null)
=> CreateXmlDictionary("CodeAnalysisDictionary.xml", recognizedWords, unrecognizedWords);
private static (string Path, string Text) CreateXmlDictionary(string filename, IEnumerable<string> recognizedWords, IEnumerable<string> unrecognizedWords = null)
{
var contents = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<Dictionary>
<Words>
<Recognized>{CreateXml(recognizedWords)}</Recognized>
<Unrecognized>{CreateXml(unrecognizedWords)}</Unrecognized>
</Words>
</Dictionary>";
return (filename, contents);
static string CreateXml(IEnumerable<string> words) =>
string.Join(Environment.NewLine, words?.Select(x => $"<Word>{x}</Word>") ?? Enumerable.Empty<string>());
}
private static (string Path, string Text) CreateDicDictionary(IEnumerable<string> recognizedWords)
{
var contents = string.Join(Environment.NewLine, recognizedWords);
return ("CustomDictionary.dic", contents);
}
private static string CreateTypeWithConstructor(string typeName, string constructorName = "", string parameter = "", bool isStatic = false)
{
if (string.IsNullOrEmpty(constructorName))
{
constructorName = typeName;
}
return $@"
#pragma warning disable {IdentifiersShouldBeSpelledCorrectlyAnalyzer.RuleId}
class {typeName}
#pragma warning restore {IdentifiersShouldBeSpelledCorrectlyAnalyzer.RuleId}
{{
{(isStatic ? "static " : string.Empty)}{constructorName}({parameter}) {{ }}
}}";
}
private static string CreateTypeWithMethod(string typeName, string methodName, string parameter = "")
=> $"class {typeName} {{ void {methodName}({parameter}) {{ }} }}";
private static string CreateTypeWithIndexer(string typeName, string parameter)
=> $"class {typeName} {{ int this[{parameter}] => 0; }}";
private static string CreateTypeWithProperty(string typeName, string propertyName)
=> $"class {typeName} {{ string {propertyName} {{ get; }} }}";
private static string CreateTypeWithField(string typeName, string fieldName)
=> $"class {typeName} {{ private string {fieldName}; }}";
private static string CreateTypeWithEvent(string typeName, string eventName)
=> $@"using System;
class {typeName} {{ event EventHandler<string> {eventName}; }}";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.