context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.Expressions { /// <summary> /// Expressions - Node Sets /// </summary> public static partial class NodeSetsTests { /// <summary> /// Expected: Selects all paraA and paraB element children of the context node. /// child::paraA | child::paraB /// </summary> [Fact] public static void NodeSetsTest181() { var xml = "xp001.xml"; var startingNodePath = "/Doc"; var testExpression = @"child::Title | child::Chap"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Title", Name = "Title", HasNameTable = true, Value = "XPath test" }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Chap", Name = "Chap", HasNameTable = true, Value = "\n XPath test\n First paragraph Nested Paragraph End of first paragraph \n Second paragraph \n " }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Chap", Name = "Chap", HasNameTable = true, Value = "\n XPath test\n Direct content\n " }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects all paraA, paraB and paraC element children of the context node. /// child::paraA | child::paraB | child::paraC /// </summary> [Fact] public static void NodeSetsTest182() { var xml = "xp001.xml"; var startingNodePath = "/Doc"; var testExpression = @"child::Title | child::Chap | child::Summary"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Title", Name = "Title", HasNameTable = true, Value = "XPath test" }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Summary", Name = "Summary", HasNameTable = true, Value = "This shall test XPath test" }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Chap", Name = "Chap", HasNameTable = true, Value = "\n XPath test\n First paragraph Nested Paragraph End of first paragraph \n Second paragraph \n " }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Chap", Name = "Chap", HasNameTable = true, Value = "\n XPath test\n Direct content\n " }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects all para element children and the parent of the context node. /// self::para | child::para /// </summary> [Fact] public static void NodeSetsTest183() { var xml = "xp001.xml"; var startingNodePath = "/Doc"; var testExpression = @"self::Doc | child::Chap"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Doc", Name = "Doc", HasNameTable = true, Value = "\n XPath test\n This shall test XPath test\n \n XPath test\n First paragraph Nested Paragraph End of first paragraph \n Second paragraph \n \n \n XPath test\n Direct content\n \n" }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Chap", Name = "Chap", HasNameTable = true, Value = "\n XPath test\n First paragraph Nested Paragraph End of first paragraph \n Second paragraph \n " }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Chap", Name = "Chap", HasNameTable = true, Value = "\n XPath test\n Direct content\n " }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects all paraB element descendants of the paraA element children of the context node. /// paraA//paraB /// </summary> [Fact] public static void NodeSetsTest184() { var xml = "xp001.xml"; var startingNodePath = "/Doc"; var testExpression = @"Chap//Para"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Para", Name = "Para", HasNameTable = true, Value = "First paragraph Nested Paragraph End of first paragraph " }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Para", Name = "Para", HasNameTable = true, Value = " Nested Paragraph " }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Para", Name = "Para", HasNameTable = true, Value = "Second paragraph " }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects all paraB element descendants of the paraA element children in the document. /// //paraA//paraB /// </summary> [Fact] public static void NodeSetsTest185() { var xml = "xp001.xml"; var startingNodePath = "/Doc"; var testExpression = @"//Doc//Para"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Para", Name = "Para", HasNameTable = true, Value = "First paragraph Nested Paragraph End of first paragraph " }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Para", Name = "Para", HasNameTable = true, Value = " Nested Paragraph " }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Para", Name = "Para", HasNameTable = true, Value = "Second paragraph " }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects all paraB element nodes with paraA parents that are children of the context node. /// paraA/paraB /// </summary> [Fact] public static void NodeSetsTest186() { var xml = "xp001.xml"; var startingNodePath = "/Doc"; var testExpression = @"Chap/Para"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Para", Name = "Para", HasNameTable = true, Value = "First paragraph Nested Paragraph End of first paragraph " }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Para", Name = "Para", HasNameTable = true, Value = "Second paragraph " }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects all paraB element nodes with paraA parents that are children of the document root. /// /paraA/paraB /// </summary> [Fact] public static void NodeSetsTest187() { var xml = "xp001.xml"; var startingNodePath = "/Doc"; var testExpression = @"/Doc/Chap"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Chap", Name = "Chap", HasNameTable = true, Value = "\n XPath test\n First paragraph Nested Paragraph End of first paragraph \n Second paragraph \n " }, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Chap", Name = "Chap", HasNameTable = true, Value = "\n XPath test\n Direct content\n " }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects all bar element nodes with para/bar children. /// para/bar[para/bar] (Use location path as expression against context) /// </summary> [Fact] public static void NodeSetsTest188() { var xml = "xp001.xml"; var startingNodePath = "/Doc"; var testExpression = @"Chap/Para[Para/Origin]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Element, HasChildren = true, LocalName = "Para", Name = "Para", HasNameTable = true, Value = "First paragraph Nested Paragraph End of first paragraph " }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } } }
// 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.ComponentModel.Composition.Factories; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.UnitTesting; using Xunit; namespace System.ComponentModel.Composition { [Export] public class TypeCatalogTestsExporter { } // This is a glorious do nothing ReflectionContext public class TypeCatalogTestsReflectionContext : ReflectionContext { public override Assembly MapAssembly(Assembly assembly) { return assembly; } public override TypeInfo MapType(TypeInfo type) { return type; } } public class TypeCatalogTests { private static void Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull(Func<ReflectionContext, TypeCatalog> catalogCreator) { Assert.Throws<ArgumentNullException>("reflectionContext", () => { var catalog = catalogCreator(null); }); } private static void Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull(Func<ICompositionElement, TypeCatalog> catalogCreator) { Assert.Throws<ArgumentNullException>("definitionOrigin", () => { var catalog = catalogCreator(null); }); } [Fact] public void Constructor1_ReflectOnlyTypes_ShouldThrowArgumentNull() { TypeCatalogTests.Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull((rc) => { return new TypeCatalog(new Type[0], rc); }); } [Fact] public void Constructor3_NullDefinitionOriginArgument_ShouldThrowArgumentNull() { TypeCatalogTests.Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull((dO) => { return new TypeCatalog(new Type[0], dO); }); } [Fact] public void Constructor4_NullReflectionContextArgument_ShouldThrowArgumentNull() { TypeCatalogTests.Constructor_NullReflectionContextArgument_ShouldThrowArgumentNull((rc) => { return new TypeCatalog(new Type[0], rc, new TypeCatalog(new Type[0])); }); } [Fact] public void Constructor4_NullDefinitionOriginArgument_ShouldThrowArgumentNull() { TypeCatalogTests.Constructor_NullDefinitionOriginArgument_ShouldThrowArgumentNull((dO) => { return new TypeCatalog(new Type[0], new TypeCatalogTestsReflectionContext(), dO); }); } [Fact] public void Constructor2_NullAsTypesArgument_ShouldThrowArgumentNull() { Assert.Throws<ArgumentNullException>("types", () => { new TypeCatalog((Type[])null); }); } [Fact] public void Constructor3_NullAsTypesArgument_ShouldThrowArgumentNull() { Assert.Throws<ArgumentNullException>("types", () => { new TypeCatalog((IEnumerable<Type>)null); }); } [Fact] public void Constructor2_ArrayWithNullAsTypesArgument_ShouldThrowArgument() { Assert.Throws<ArgumentException>("types", () => { new TypeCatalog(new Type[] { null }); }); } [Fact] public void Constructor3_ArrayWithNullAsTypesArgument_ShouldThrowArgument() { Assert.Throws<ArgumentException>("types", () => { new TypeCatalog((IEnumerable<Type>)new Type[] { null }); }); } [Fact] public void Constructor2_EmptyEnumerableAsTypesArgument_ShouldSetPartsPropertyToEmptyEnumerable() { var catalog = new TypeCatalog(Enumerable.Empty<Type>()); Assert.Empty(catalog.Parts); } [Fact] public void Constructor3_EmptyArrayAsTypesArgument_ShouldSetPartsPropertyToEmpty() { var catalog = new TypeCatalog(new Type[0]); Assert.Empty(catalog.Parts); } [Fact] public void Constructor2_ArrayAsTypesArgument_ShouldNotAllowModificationAfterConstruction() { var types = new Type[] { PartFactory.GetAttributedExporterType() }; var catalog = new TypeCatalog(types); types[0] = null; Assert.NotNull(catalog.Parts.First()); } [Fact] public void Constructor3_ArrayAsTypesArgument_ShouldNotAllowModificationAfterConstruction() { var types = new Type[] { PartFactory.GetAttributedExporterType() }; var catalog = new TypeCatalog((IEnumerable<Type>)types); types[0] = null; Assert.NotNull(catalog.Parts.First()); } [Fact] public void Constructor2_ShouldSetOriginToNull() { var catalog = (ICompositionElement)new TypeCatalog(PartFactory.GetAttributedExporterType()); Assert.Null(catalog.Origin); } [Fact] public void Constructor3_ShouldSetOriginToNull() { var catalog = (ICompositionElement)new TypeCatalog((IEnumerable<Type>)new Type[] { PartFactory.GetAttributedExporterType() }); Assert.Null(catalog.Origin); } [Fact] public void DisplayName_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateTypeCatalog(); catalog.Dispose(); var displayName = ((ICompositionElement)catalog).DisplayName; } [Fact] public void Origin_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateTypeCatalog(); catalog.Dispose(); var origin = ((ICompositionElement)catalog).Origin; } [Fact] public void Parts_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateTypeCatalog(); catalog.Dispose(); ExceptionAssert.ThrowsDisposed(catalog, () => { var parts = catalog.Parts; }); } [Fact] public void ToString_WhenCatalogDisposed_ShouldNotThrow() { var catalog = CreateTypeCatalog(); catalog.Dispose(); catalog.ToString(); } [Fact] public void GetExports_WhenCatalogDisposed_ShouldThrowObjectDisposed() { var catalog = CreateTypeCatalog(); catalog.Dispose(); var definition = ImportDefinitionFactory.Create(); ExceptionAssert.ThrowsDisposed(catalog, () => { catalog.GetExports(definition); }); } [Fact] public void GetExports_NullAsConstraintArgument_ShouldThrowArgumentNull() { var catalog = CreateTypeCatalog(); Assert.Throws<ArgumentNullException>("definition", () => { catalog.GetExports((ImportDefinition)null); }); } [Fact] public void Dispose_ShouldNotThrow() { using (var catalog = CreateTypeCatalog()) { } } [Fact] public void Dispose_CanBeCalledMultipleTimes() { var catalog = CreateTypeCatalog(); catalog.Dispose(); catalog.Dispose(); catalog.Dispose(); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void Parts() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); Assert.NotNull(catalog.Parts); Assert.True(catalog.Parts.Count() > 0); } [Fact] public void Parts_ShouldSetDefinitionOriginToCatalogItself() { var catalog = CreateTypeCatalog(); Assert.True(catalog.Parts.Count() > 0); foreach (ICompositionElement definition in catalog.Parts) { Assert.Same(catalog, definition.Origin); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void ICompositionElementDisplayName_SingleTypeAsTypesArgument_ShouldIncludeCatalogTypeNameAndTypeFullName() { var expectations = Expectations.GetAttributedTypes(); foreach (var e in expectations) { var catalog = (ICompositionElement)CreateTypeCatalog(e); string expected = string.Format(SR.TypeCatalog_DisplayNameFormat, typeof(TypeCatalog).Name, AttributedModelServices.GetTypeIdentity(e)); Assert.Equal(expected, catalog.DisplayName); } } [Fact] public void ICompositionElementDisplayName_ValueAsTypesArgument_ShouldIncludeCatalogTypeNameAndTypeFullNames() { var expectations = new ExpectationCollection<Type[], string>(); expectations.Add(new Type[] { typeof(Type) }, GetDisplayName(false, typeof(TypeCatalog))); expectations.Add(new Type[] { typeof(ExportValueTypeSingleton) }, GetDisplayName(false, typeof(TypeCatalog), typeof(ExportValueTypeSingleton))); expectations.Add(new Type[] { typeof(ExportValueTypeSingleton), typeof(ExportValueTypeSingleton) }, GetDisplayName(false, typeof(TypeCatalog), typeof(ExportValueTypeSingleton), typeof(ExportValueTypeSingleton))); expectations.Add(new Type[] { typeof(ExportValueTypeSingleton), typeof(string), typeof(ExportValueTypeSingleton) }, GetDisplayName(false, typeof(TypeCatalog), typeof(ExportValueTypeSingleton), typeof(ExportValueTypeSingleton))); expectations.Add(new Type[] { typeof(ExportValueTypeSingleton), typeof(ExportValueTypeFactory) }, GetDisplayName(false, typeof(TypeCatalog), typeof(ExportValueTypeSingleton), typeof(ExportValueTypeFactory))); expectations.Add(new Type[] { typeof(ExportValueTypeSingleton), typeof(ExportValueTypeFactory), typeof(CallbackExecuteCodeDuringCompose) }, GetDisplayName(true, typeof(TypeCatalog), typeof(ExportValueTypeSingleton), typeof(ExportValueTypeFactory))); foreach (var e in expectations) { var catalog = (ICompositionElement)CreateTypeCatalog(e.Input); Assert.Equal(e.Output, catalog.DisplayName); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void ICompositionElementDisplayName_ShouldIncludeDerivedCatalogTypeNameAndTypeFullNames() { var expectations = Expectations.GetAttributedTypes(); foreach (var e in expectations) { var catalog = (ICompositionElement)new DerivedTypeCatalog(e); string expected = string.Format(SR.TypeCatalog_DisplayNameFormat, typeof(DerivedTypeCatalog).Name, AttributedModelServices.GetTypeIdentity(e)); Assert.Equal(expected, catalog.DisplayName); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void ToString_ShouldReturnICompositionElementDisplayName() { var expectations = Expectations.GetAttributedTypes(); foreach (var e in expectations) { var catalog = (ICompositionElement)CreateTypeCatalog(e); Assert.Equal(catalog.DisplayName, catalog.ToString()); } } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void GetExports() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); Expression<Func<ExportDefinition, bool>> constraint = (ExportDefinition exportDefinition) => exportDefinition.ContractName == AttributedModelServices.GetContractName(typeof(MyExport)); IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> matchingExports = catalog.GetExports(constraint); Assert.NotNull(matchingExports); Assert.True(matchingExports.Count() >= 0); IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> expectedMatchingExports = catalog.Parts .SelectMany(part => part.ExportDefinitions, (part, export) => new Tuple<ComposablePartDefinition, ExportDefinition>(part, export)) .Where(partAndExport => partAndExport.Item2.ContractName == AttributedModelServices.GetContractName(typeof(MyExport))); Assert.True(matchingExports.SequenceEqual(expectedMatchingExports)); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void TwoTypesWithSameSimpleName() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); NotSoUniqueName unique1 = container.GetExportedValue<NotSoUniqueName>(); Assert.NotNull(unique1); Assert.Equal(23, unique1.MyIntProperty); NotSoUniqueName2.NotSoUniqueName nestedUnique = container.GetExportedValue<NotSoUniqueName2.NotSoUniqueName>(); Assert.NotNull(nestedUnique); Assert.Equal("MyStringProperty", nestedUnique.MyStringProperty); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void GettingFunctionExports() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); ImportDefaultFunctions import = container.GetExportedValue<ImportDefaultFunctions>("ImportDefaultFunctions"); import.VerifyIsBound(); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void AnExportOfAnInstanceThatFailsToCompose() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); // Rejection causes the part in the catalog whose imports cannot be // satisfied to be ignored, resulting in a cardinality mismatch instead of a // composition exception ExceptionAssert.Throws<ImportCardinalityMismatchException>(() => { container.GetExportedValue<string>("ExportMyString"); }); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void SharedPartCreation() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); CompositionBatch batch = new CompositionBatch(); batch.AddPart(new Int32Exporter(41)); container.Compose(batch); var sharedPart1 = container.GetExportedValue<MySharedPartExport>(); Assert.Equal(41, sharedPart1.Value); var sharedPart2 = container.GetExportedValue<MySharedPartExport>(); Assert.Equal(41, sharedPart2.Value); Assert.Equal(sharedPart1, sharedPart2); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void NonSharedPartCreation() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); CompositionBatch batch = new CompositionBatch(); batch.AddPart(new Int32Exporter(41)); container.Compose(batch); var nonSharedPart1 = container.GetExportedValue<MyNonSharedPartExport>(); Assert.Equal(41, nonSharedPart1.Value); var nonSharedPart2 = container.GetExportedValue<MyNonSharedPartExport>(); Assert.Equal(41, nonSharedPart2.Value); Assert.NotEqual(nonSharedPart1, nonSharedPart2); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void RecursiveNonSharedPartCreation() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotGetExportedValue, () => { container.GetExportedValue<DirectCycleNonSharedPart>(); }); CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotGetExportedValue, () => { container.GetExportedValue<CycleNonSharedPart>(); }); CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotGetExportedValue, () => { container.GetExportedValue<CycleNonSharedPart1>(); }); CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotGetExportedValue, () => { container.GetExportedValue<CycleNonSharedPart2>(); }); CompositionAssert.ThrowsError(ErrorId.ImportEngine_PartCannotGetExportedValue, () => { container.GetExportedValue<CycleWithSharedPartAndNonSharedPart>(); }); Assert.NotNull(container.GetExportedValue<CycleSharedPart>()); Assert.NotNull(container.GetExportedValue<CycleSharedPart1>()); Assert.NotNull(container.GetExportedValue<CycleSharedPart2>()); Assert.NotNull(container.GetExportedValue<NoCycleNonSharedPart>()); } [Fact] [ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. public void TryToDiscoverExportWithGenericParameter() { var catalog = new TypeCatalog(Assembly.GetExecutingAssembly().GetTypes()); var container = new CompositionContainer(catalog); // Should find a type that inherits from an export Assert.NotNull(container.GetExportedValueOrDefault<object>(AttributedModelServices.GetContractName(typeof(ExportWhichInheritsFromGeneric)))); // This should be exported because it is inherited by ExportWhichInheritsFromGeneric Assert.NotNull(container.GetExportedValueOrDefault<object>(AttributedModelServices.GetContractName(typeof(ExportWithGenericParameter<string>)))); } private string GetDisplayName(bool useEllipses, Type catalogType, params Type[] types) { return string.Format(CultureInfo.CurrentCulture, SR.TypeCatalog_DisplayNameFormat, catalogType.Name, this.GetTypesDisplay(useEllipses, types)); } private string GetTypesDisplay(bool useEllipses, Type[] types) { int count = types.Length; if (count == 0) { return SR.TypeCatalog_Empty; } StringBuilder builder = new StringBuilder(); foreach (Type type in types) { if (builder.Length > 0) { builder.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); builder.Append(" "); } builder.Append(type.FullName); } if (useEllipses) { // Add an elipse to indicate that there // are more types than actually listed builder.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator); builder.Append(" ..."); } return builder.ToString(); } private TypeCatalog CreateTypeCatalog() { var type = PartFactory.GetAttributedExporterType(); return CreateTypeCatalog(type); } private TypeCatalog CreateTypeCatalog(params Type[] types) { return new TypeCatalog(types); } private class DerivedTypeCatalog : TypeCatalog { public DerivedTypeCatalog(params Type[] types) : base(types) { } } } }
namespace java.security { [global::MonoJavaBridge.JavaClass(typeof(global::java.security.KeyStoreSpi_))] public abstract partial class KeyStoreSpi : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static KeyStoreSpi() { InitJNI(); } protected KeyStoreSpi(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _engineGetKey14810; public abstract global::java.security.Key engineGetKey(java.lang.String arg0, char[] arg1); internal static global::MonoJavaBridge.MethodId _engineGetCertificateChain14811; public abstract global::java.security.cert.Certificate[] engineGetCertificateChain(java.lang.String arg0); internal static global::MonoJavaBridge.MethodId _engineGetCertificate14812; public abstract global::java.security.cert.Certificate engineGetCertificate(java.lang.String arg0); internal static global::MonoJavaBridge.MethodId _engineGetCreationDate14813; public abstract global::java.util.Date engineGetCreationDate(java.lang.String arg0); internal static global::MonoJavaBridge.MethodId _engineSetKeyEntry14814; public abstract void engineSetKeyEntry(java.lang.String arg0, java.security.Key arg1, char[] arg2, java.security.cert.Certificate[] arg3); internal static global::MonoJavaBridge.MethodId _engineSetKeyEntry14815; public abstract void engineSetKeyEntry(java.lang.String arg0, byte[] arg1, java.security.cert.Certificate[] arg2); internal static global::MonoJavaBridge.MethodId _engineSetCertificateEntry14816; public abstract void engineSetCertificateEntry(java.lang.String arg0, java.security.cert.Certificate arg1); internal static global::MonoJavaBridge.MethodId _engineDeleteEntry14817; public abstract void engineDeleteEntry(java.lang.String arg0); internal static global::MonoJavaBridge.MethodId _engineAliases14818; public abstract global::java.util.Enumeration engineAliases(); internal static global::MonoJavaBridge.MethodId _engineContainsAlias14819; public abstract bool engineContainsAlias(java.lang.String arg0); internal static global::MonoJavaBridge.MethodId _engineSize14820; public abstract int engineSize(); internal static global::MonoJavaBridge.MethodId _engineIsKeyEntry14821; public abstract bool engineIsKeyEntry(java.lang.String arg0); internal static global::MonoJavaBridge.MethodId _engineIsCertificateEntry14822; public abstract bool engineIsCertificateEntry(java.lang.String arg0); internal static global::MonoJavaBridge.MethodId _engineGetCertificateAlias14823; public abstract global::java.lang.String engineGetCertificateAlias(java.security.cert.Certificate arg0); internal static global::MonoJavaBridge.MethodId _engineStore14824; public abstract void engineStore(java.io.OutputStream arg0, char[] arg1); internal static global::MonoJavaBridge.MethodId _engineStore14825; public virtual void engineStore(java.security.KeyStore.LoadStoreParameter arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi._engineStore14825, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi.staticClass, global::java.security.KeyStoreSpi._engineStore14825, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _engineLoad14826; public abstract void engineLoad(java.io.InputStream arg0, char[] arg1); internal static global::MonoJavaBridge.MethodId _engineLoad14827; public virtual void engineLoad(java.security.KeyStore.LoadStoreParameter arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi._engineLoad14827, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi.staticClass, global::java.security.KeyStoreSpi._engineLoad14827, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _engineGetEntry14828; public virtual global::java.security.KeyStore.Entry engineGetEntry(java.lang.String arg0, java.security.KeyStore.ProtectionParameter arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.KeyStore.Entry>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi._engineGetEntry14828, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.security.KeyStore.Entry; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.KeyStore.Entry>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi.staticClass, global::java.security.KeyStoreSpi._engineGetEntry14828, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.security.KeyStore.Entry; } internal static global::MonoJavaBridge.MethodId _engineSetEntry14829; public virtual void engineSetEntry(java.lang.String arg0, java.security.KeyStore.Entry arg1, java.security.KeyStore.ProtectionParameter arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi._engineSetEntry14829, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi.staticClass, global::java.security.KeyStoreSpi._engineSetEntry14829, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _engineEntryInstanceOf14830; public virtual bool engineEntryInstanceOf(java.lang.String arg0, java.lang.Class arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.security.KeyStoreSpi._engineEntryInstanceOf14830, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.security.KeyStoreSpi.staticClass, global::java.security.KeyStoreSpi._engineEntryInstanceOf14830, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _KeyStoreSpi14831; public KeyStoreSpi() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.security.KeyStoreSpi.staticClass, global::java.security.KeyStoreSpi._KeyStoreSpi14831); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.security.KeyStoreSpi.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/security/KeyStoreSpi")); global::java.security.KeyStoreSpi._engineGetKey14810 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineGetKey", "(Ljava/lang/String;[C)Ljava/security/Key;"); global::java.security.KeyStoreSpi._engineGetCertificateChain14811 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineGetCertificateChain", "(Ljava/lang/String;)[Ljava/security/cert/Certificate;"); global::java.security.KeyStoreSpi._engineGetCertificate14812 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineGetCertificate", "(Ljava/lang/String;)Ljava/security/cert/Certificate;"); global::java.security.KeyStoreSpi._engineGetCreationDate14813 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineGetCreationDate", "(Ljava/lang/String;)Ljava/util/Date;"); global::java.security.KeyStoreSpi._engineSetKeyEntry14814 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineSetKeyEntry", "(Ljava/lang/String;Ljava/security/Key;[C[Ljava/security/cert/Certificate;)V"); global::java.security.KeyStoreSpi._engineSetKeyEntry14815 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineSetKeyEntry", "(Ljava/lang/String;[B[Ljava/security/cert/Certificate;)V"); global::java.security.KeyStoreSpi._engineSetCertificateEntry14816 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineSetCertificateEntry", "(Ljava/lang/String;Ljava/security/cert/Certificate;)V"); global::java.security.KeyStoreSpi._engineDeleteEntry14817 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineDeleteEntry", "(Ljava/lang/String;)V"); global::java.security.KeyStoreSpi._engineAliases14818 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineAliases", "()Ljava/util/Enumeration;"); global::java.security.KeyStoreSpi._engineContainsAlias14819 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineContainsAlias", "(Ljava/lang/String;)Z"); global::java.security.KeyStoreSpi._engineSize14820 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineSize", "()I"); global::java.security.KeyStoreSpi._engineIsKeyEntry14821 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineIsKeyEntry", "(Ljava/lang/String;)Z"); global::java.security.KeyStoreSpi._engineIsCertificateEntry14822 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineIsCertificateEntry", "(Ljava/lang/String;)Z"); global::java.security.KeyStoreSpi._engineGetCertificateAlias14823 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineGetCertificateAlias", "(Ljava/security/cert/Certificate;)Ljava/lang/String;"); global::java.security.KeyStoreSpi._engineStore14824 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineStore", "(Ljava/io/OutputStream;[C)V"); global::java.security.KeyStoreSpi._engineStore14825 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineStore", "(Ljava/security/KeyStore$LoadStoreParameter;)V"); global::java.security.KeyStoreSpi._engineLoad14826 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineLoad", "(Ljava/io/InputStream;[C)V"); global::java.security.KeyStoreSpi._engineLoad14827 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineLoad", "(Ljava/security/KeyStore$LoadStoreParameter;)V"); global::java.security.KeyStoreSpi._engineGetEntry14828 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineGetEntry", "(Ljava/lang/String;Ljava/security/KeyStore$ProtectionParameter;)Ljava/security/KeyStore$Entry;"); global::java.security.KeyStoreSpi._engineSetEntry14829 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineSetEntry", "(Ljava/lang/String;Ljava/security/KeyStore$Entry;Ljava/security/KeyStore$ProtectionParameter;)V"); global::java.security.KeyStoreSpi._engineEntryInstanceOf14830 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "engineEntryInstanceOf", "(Ljava/lang/String;Ljava/lang/Class;)Z"); global::java.security.KeyStoreSpi._KeyStoreSpi14831 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.security.KeyStoreSpi))] public sealed partial class KeyStoreSpi_ : java.security.KeyStoreSpi { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static KeyStoreSpi_() { InitJNI(); } internal KeyStoreSpi_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _engineGetKey14832; public override global::java.security.Key engineGetKey(java.lang.String arg0, char[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.Key>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineGetKey14832, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.security.Key; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.security.Key>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineGetKey14832, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.security.Key; } internal static global::MonoJavaBridge.MethodId _engineGetCertificateChain14833; public override global::java.security.cert.Certificate[] engineGetCertificateChain(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.security.cert.Certificate>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineGetCertificateChain14833, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.security.cert.Certificate[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.security.cert.Certificate>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineGetCertificateChain14833, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.security.cert.Certificate[]; } internal static global::MonoJavaBridge.MethodId _engineGetCertificate14834; public override global::java.security.cert.Certificate engineGetCertificate(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineGetCertificate14834, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.security.cert.Certificate; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineGetCertificate14834, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.security.cert.Certificate; } internal static global::MonoJavaBridge.MethodId _engineGetCreationDate14835; public override global::java.util.Date engineGetCreationDate(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineGetCreationDate14835, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.Date; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineGetCreationDate14835, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.Date; } internal static global::MonoJavaBridge.MethodId _engineSetKeyEntry14836; public override void engineSetKeyEntry(java.lang.String arg0, java.security.Key arg1, char[] arg2, java.security.cert.Certificate[] arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineSetKeyEntry14836, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineSetKeyEntry14836, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _engineSetKeyEntry14837; public override void engineSetKeyEntry(java.lang.String arg0, byte[] arg1, java.security.cert.Certificate[] arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineSetKeyEntry14837, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineSetKeyEntry14837, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _engineSetCertificateEntry14838; public override void engineSetCertificateEntry(java.lang.String arg0, java.security.cert.Certificate arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineSetCertificateEntry14838, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineSetCertificateEntry14838, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _engineDeleteEntry14839; public override void engineDeleteEntry(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineDeleteEntry14839, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineDeleteEntry14839, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _engineAliases14840; public override global::java.util.Enumeration engineAliases() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Enumeration>(@__env.CallObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineAliases14840)) as java.util.Enumeration; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Enumeration>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineAliases14840)) as java.util.Enumeration; } internal static global::MonoJavaBridge.MethodId _engineContainsAlias14841; public override bool engineContainsAlias(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineContainsAlias14841, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineContainsAlias14841, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _engineSize14842; public override int engineSize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineSize14842); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineSize14842); } internal static global::MonoJavaBridge.MethodId _engineIsKeyEntry14843; public override bool engineIsKeyEntry(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineIsKeyEntry14843, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineIsKeyEntry14843, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _engineIsCertificateEntry14844; public override bool engineIsCertificateEntry(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineIsCertificateEntry14844, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineIsCertificateEntry14844, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _engineGetCertificateAlias14845; public override global::java.lang.String engineGetCertificateAlias(java.security.cert.Certificate arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineGetCertificateAlias14845, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineGetCertificateAlias14845, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _engineStore14846; public override void engineStore(java.io.OutputStream arg0, char[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineStore14846, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineStore14846, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _engineLoad14847; public override void engineLoad(java.io.InputStream arg0, char[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_._engineLoad14847, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.security.KeyStoreSpi_.staticClass, global::java.security.KeyStoreSpi_._engineLoad14847, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.security.KeyStoreSpi_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/security/KeyStoreSpi")); global::java.security.KeyStoreSpi_._engineGetKey14832 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineGetKey", "(Ljava/lang/String;[C)Ljava/security/Key;"); global::java.security.KeyStoreSpi_._engineGetCertificateChain14833 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineGetCertificateChain", "(Ljava/lang/String;)[Ljava/security/cert/Certificate;"); global::java.security.KeyStoreSpi_._engineGetCertificate14834 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineGetCertificate", "(Ljava/lang/String;)Ljava/security/cert/Certificate;"); global::java.security.KeyStoreSpi_._engineGetCreationDate14835 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineGetCreationDate", "(Ljava/lang/String;)Ljava/util/Date;"); global::java.security.KeyStoreSpi_._engineSetKeyEntry14836 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineSetKeyEntry", "(Ljava/lang/String;Ljava/security/Key;[C[Ljava/security/cert/Certificate;)V"); global::java.security.KeyStoreSpi_._engineSetKeyEntry14837 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineSetKeyEntry", "(Ljava/lang/String;[B[Ljava/security/cert/Certificate;)V"); global::java.security.KeyStoreSpi_._engineSetCertificateEntry14838 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineSetCertificateEntry", "(Ljava/lang/String;Ljava/security/cert/Certificate;)V"); global::java.security.KeyStoreSpi_._engineDeleteEntry14839 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineDeleteEntry", "(Ljava/lang/String;)V"); global::java.security.KeyStoreSpi_._engineAliases14840 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineAliases", "()Ljava/util/Enumeration;"); global::java.security.KeyStoreSpi_._engineContainsAlias14841 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineContainsAlias", "(Ljava/lang/String;)Z"); global::java.security.KeyStoreSpi_._engineSize14842 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineSize", "()I"); global::java.security.KeyStoreSpi_._engineIsKeyEntry14843 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineIsKeyEntry", "(Ljava/lang/String;)Z"); global::java.security.KeyStoreSpi_._engineIsCertificateEntry14844 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineIsCertificateEntry", "(Ljava/lang/String;)Z"); global::java.security.KeyStoreSpi_._engineGetCertificateAlias14845 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineGetCertificateAlias", "(Ljava/security/cert/Certificate;)Ljava/lang/String;"); global::java.security.KeyStoreSpi_._engineStore14846 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineStore", "(Ljava/io/OutputStream;[C)V"); global::java.security.KeyStoreSpi_._engineLoad14847 = @__env.GetMethodIDNoThrow(global::java.security.KeyStoreSpi_.staticClass, "engineLoad", "(Ljava/io/InputStream;[C)V"); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedLicensesClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetLicenseRequest request = new GetLicenseRequest { License = "license75798771", Project = "projectaa6ff846", }; License expectedResponse = new License { Id = 11672635353343658936UL, LicenseCode = 9852583981640995008UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Transferable = false, CreationTimestamp = "creation_timestamp235e59a1", ResourceRequirements = new LicenseResourceRequirements(), ChargesUseFee = true, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); License response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetLicenseRequest request = new GetLicenseRequest { License = "license75798771", Project = "projectaa6ff846", }; License expectedResponse = new License { Id = 11672635353343658936UL, LicenseCode = 9852583981640995008UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Transferable = false, CreationTimestamp = "creation_timestamp235e59a1", ResourceRequirements = new LicenseResourceRequirements(), ChargesUseFee = true, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<License>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); License responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); License responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetLicenseRequest request = new GetLicenseRequest { License = "license75798771", Project = "projectaa6ff846", }; License expectedResponse = new License { Id = 11672635353343658936UL, LicenseCode = 9852583981640995008UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Transferable = false, CreationTimestamp = "creation_timestamp235e59a1", ResourceRequirements = new LicenseResourceRequirements(), ChargesUseFee = true, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); License response = client.Get(request.Project, request.License); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetLicenseRequest request = new GetLicenseRequest { License = "license75798771", Project = "projectaa6ff846", }; License expectedResponse = new License { Id = 11672635353343658936UL, LicenseCode = 9852583981640995008UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Transferable = false, CreationTimestamp = "creation_timestamp235e59a1", ResourceRequirements = new LicenseResourceRequirements(), ChargesUseFee = true, Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<License>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); License responseCallSettings = await client.GetAsync(request.Project, request.License, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); License responseCancellationToken = await client.GetAsync(request.Project, request.License, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyLicenseRequest request = new GetIamPolicyLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyLicenseRequest request = new GetIamPolicyLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyLicenseRequest request = new GetIamPolicyLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request.Project, request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyLicenseRequest request = new GetIamPolicyLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyLicenseRequest request = new SetIamPolicyLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyLicenseRequest request = new SetIamPolicyLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyLicenseRequest request = new SetIamPolicyLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request.Project, request.Resource, request.GlobalSetPolicyRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyLicenseRequest request = new SetIamPolicyLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", GlobalSetPolicyRequestResource = new GlobalSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Resource, request.GlobalSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Resource, request.GlobalSetPolicyRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsLicenseRequest request = new TestIamPermissionsLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsLicenseRequest request = new TestIamPermissionsLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsLicenseRequest request = new TestIamPermissionsLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<Licenses.LicensesClient> mockGrpcClient = new moq::Mock<Licenses.LicensesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsLicenseRequest request = new TestIamPermissionsLicenseRequest { Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); LicensesClient client = new LicensesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
//------------------------------------------------------------------------------ // <copyright file="SqlConnectionFactory.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.SqlClient { using System; using System.Data.Common; using System.Data.ProviderBase; using System.Collections.Specialized; using System.Configuration; using System.Diagnostics; using System.IO; using System.Runtime.Versioning; using Microsoft.SqlServer.Server; sealed internal class SqlConnectionFactory : DbConnectionFactory { private SqlConnectionFactory() : base(SqlPerformanceCounters.SingletonInstance) {} public static readonly SqlConnectionFactory SingletonInstance = new SqlConnectionFactory(); private const string _metaDataXml = "MetaDataXml"; override public DbProviderFactory ProviderFactory { get { return SqlClientFactory.Instance; } } override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) { return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection, userOptions: null); } override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) { SqlConnectionString opt = (SqlConnectionString)options; SqlConnectionPoolKey key = (SqlConnectionPoolKey) poolKey; SqlInternalConnection result = null; SessionData recoverySessionData = null; SqlConnectionString userOpt = null; if (userOptions != null) { userOpt = (SqlConnectionString)userOptions; } else if (owningConnection != null) { userOpt = (SqlConnectionString)(((SqlConnection)owningConnection).UserConnectionOptions); } if (owningConnection != null) { recoverySessionData = ((SqlConnection)owningConnection)._recoverySessionData; } if (opt.ContextConnection) { result = GetContextConnection(opt, poolGroupProviderInfo); } else { bool redirectedUserInstance = false; DbConnectionPoolIdentity identity = null; // Pass DbConnectionPoolIdentity to SqlInternalConnectionTds if using integrated security. // Used by notifications. if (opt.IntegratedSecurity) { if (pool != null) { identity = pool.Identity; } else { identity = DbConnectionPoolIdentity.GetCurrent(); } } // FOLLOWING IF BLOCK IS ENTIRELY FOR SSE USER INSTANCES // If "user instance=true" is in the connection string, we're using SSE user instances if (opt.UserInstance) { // opt.DataSource is used to create the SSE connection redirectedUserInstance = true; string instanceName; if ( (null == pool) || (null != pool && pool.Count <= 0) ) { // Non-pooled or pooled and no connections in the pool. SqlInternalConnectionTds sseConnection = null; try { // What about a failure - throw? YES! // SqlConnectionString sseopt = new SqlConnectionString(opt, opt.DataSource, true /* user instance=true */, false /* set Enlist = false */); sseConnection = new SqlInternalConnectionTds(identity, sseopt, key.Credential, null, "", null, false); // NOTE: Retrieve <UserInstanceName> here. This user instance name will be used below to connect to the Sql Express User Instance. instanceName = sseConnection.InstanceName; if (!instanceName.StartsWith("\\\\.\\", StringComparison.Ordinal)) { throw SQL.NonLocalSSEInstance(); } if (null != pool) { // Pooled connection - cache result SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo) pool.ProviderInfo; // No lock since we are already in creation mutex providerInfo.InstanceName = instanceName; } } finally { if (null != sseConnection) { sseConnection.Dispose(); } } } else { // Cached info from pool. SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo) pool.ProviderInfo; // No lock since we are already in creation mutex instanceName = providerInfo.InstanceName; } // NOTE: Here connection option opt is cloned to set 'instanceName=<UserInstanceName>' that was // retrieved from the previous SSE connection. For this UserInstance connection 'Enlist=True'. // options immutable - stored in global hash - don't modify opt = new SqlConnectionString(opt, instanceName, false /* user instance=false */, null /* do not modify the Enlist value */); poolGroupProviderInfo = null; // null so we do not pass to constructor below... } result = new SqlInternalConnectionTds(identity, opt, key.Credential, poolGroupProviderInfo, "", null, redirectedUserInstance, userOpt, recoverySessionData); } return result; } protected override DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous) { Debug.Assert(!ADP.IsEmpty(connectionString), "empty connectionString"); SqlConnectionString result = new SqlConnectionString(connectionString); return result; } override internal DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions){ DbConnectionPoolProviderInfo providerInfo = null; if (((SqlConnectionString) connectionOptions).UserInstance) { providerInfo = new SqlConnectionPoolProviderInfo(); } return providerInfo; } override protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions( DbConnectionOptions connectionOptions ) { SqlConnectionString opt = (SqlConnectionString)connectionOptions; DbConnectionPoolGroupOptions poolingOptions = null; if (!opt.ContextConnection && opt.Pooling) { // never pool context connections. int connectionTimeout = opt.ConnectTimeout; if ((0 < connectionTimeout) && (connectionTimeout < Int32.MaxValue/1000)) connectionTimeout *= 1000; else if (connectionTimeout >= Int32.MaxValue/1000) connectionTimeout = Int32.MaxValue; poolingOptions = new DbConnectionPoolGroupOptions( opt.IntegratedSecurity, opt.MinPoolSize, opt.MaxPoolSize, connectionTimeout, opt.LoadBalanceTimeout, opt.Enlist); } return poolingOptions; } // SxS (VSDD 545786): metadata files are opened from <.NetRuntimeFolder>\CONFIG\<metadatafilename.xml> // this operation is safe in SxS because the file is opened in read-only mode and each NDP runtime accesses its own copy of the metadata // under the runtime folder. [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] override protected DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory){ Debug.Assert (internalConnection != null, "internalConnection may not be null."); cacheMetaDataFactory = false; if (internalConnection is SqlInternalConnectionSmi) { throw SQL.NotAvailableOnContextConnection(); } NameValueCollection settings = (NameValueCollection)PrivilegedConfigurationManager.GetSection("system.data.sqlclient"); Stream XMLStream =null; if (settings != null){ string [] values = settings.GetValues(_metaDataXml); if (values != null) { XMLStream = ADP.GetXmlStreamFromValues(values, _metaDataXml); } } // if the xml was not obtained from machine.config use the embedded XML resource if (XMLStream == null){ XMLStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("System.Data.SqlClient.SqlMetaData.xml"); cacheMetaDataFactory = true; } Debug.Assert (XMLStream != null,"XMLstream may not be null."); return new SqlMetaDataFactory (XMLStream, internalConnection.ServerVersion, internalConnection.ServerVersion); //internalConnection.ServerVersionNormalized); } override internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo (DbConnectionOptions connectionOptions) { return new SqlConnectionPoolGroupProviderInfo((SqlConnectionString)connectionOptions); } internal static SqlConnectionString FindSqlConnectionOptions(SqlConnectionPoolKey key) { SqlConnectionString connectionOptions = (SqlConnectionString )SingletonInstance.FindConnectionOptions(key); if (null == connectionOptions) { connectionOptions = new SqlConnectionString(key.ConnectionString); } if (connectionOptions.IsEmpty) { throw ADP.NoConnectionString(); } return connectionOptions; } private SqlInternalConnectionSmi GetContextConnection(SqlConnectionString options, object providerInfo) { SmiContext smiContext = SmiContextFactory.Instance.GetCurrentContext(); SqlInternalConnectionSmi result = (SqlInternalConnectionSmi)smiContext.GetContextValue((int)SmiContextFactory.ContextKey.Connection); // context connections are automatically re-useable if they exist unless they've been doomed. if (null == result || result.IsConnectionDoomed) { if (null != result) { result.Dispose(); // A doomed connection is a messy thing. Dispose of it promptly in nearest receptacle. } result = new SqlInternalConnectionSmi(options, smiContext); smiContext.SetContextValue((int)SmiContextFactory.ContextKey.Connection, result); } result.Activate(); return result; } override internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection) { SqlConnection c = (connection as SqlConnection); if (null != c) { return c.PoolGroup; } return null; } override internal DbConnectionInternal GetInnerConnection(DbConnection connection) { SqlConnection c = (connection as SqlConnection); if (null != c) { return c.InnerConnection; } return null; } override protected int GetObjectId(DbConnection connection) { SqlConnection c = (connection as SqlConnection); if (null != c) { return c.ObjectID; } return 0; } override internal void PermissionDemand(DbConnection outerConnection) { SqlConnection c = (outerConnection as SqlConnection); if (null != c) { c.PermissionDemand(); } } override internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup) { SqlConnection c = (outerConnection as SqlConnection); if (null != c) { c.PoolGroup = poolGroup; } } override internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to) { SqlConnection c = (owningObject as SqlConnection); if (null != c) { c.SetInnerConnectionEvent(to); } } override internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from) { SqlConnection c = (owningObject as SqlConnection); if (null != c) { return c.SetInnerConnectionFrom(to, from); } return false; } override internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to) { SqlConnection c = (owningObject as SqlConnection); if (null != c) { c.SetInnerConnectionTo(to); } } } sealed internal class SqlPerformanceCounters : DbConnectionPoolCounters { private const string CategoryName = ".NET Data Provider for SqlServer"; private const string CategoryHelp = "Counters for System.Data.SqlClient"; public static readonly SqlPerformanceCounters SingletonInstance = new SqlPerformanceCounters(); [System.Diagnostics.PerformanceCounterPermissionAttribute(System.Security.Permissions.SecurityAction.Assert, PermissionAccess=PerformanceCounterPermissionAccess.Write, MachineName=".", CategoryName=CategoryName)] private SqlPerformanceCounters() : base (CategoryName, CategoryHelp) { } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERLevel; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G03_Continent_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="G03_Continent_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="G02_Continent"/> collection. /// </remarks> [Serializable] public partial class G03_Continent_ReChild : BusinessBase<G03_Continent_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name"); /// <summary> /// Gets or sets the SubContinents Child Name. /// </summary> /// <value>The SubContinents Child Name.</value> public string Continent_Child_Name { get { return GetProperty(Continent_Child_NameProperty); } set { SetProperty(Continent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G03_Continent_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="G03_Continent_ReChild"/> object.</returns> internal static G03_Continent_ReChild NewG03_Continent_ReChild() { return DataPortal.CreateChild<G03_Continent_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="G03_Continent_ReChild"/> object, based on given parameters. /// </summary> /// <param name="continent_ID2">The Continent_ID2 parameter of the G03_Continent_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="G03_Continent_ReChild"/> object.</returns> internal static G03_Continent_ReChild GetG03_Continent_ReChild(int continent_ID2) { return DataPortal.FetchChild<G03_Continent_ReChild>(continent_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G03_Continent_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G03_Continent_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G03_Continent_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G03_Continent_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="continent_ID2">The Continent ID2.</param> protected void Child_Fetch(int continent_ID2) { var args = new DataPortalHookArgs(continent_ID2); OnFetchPre(args); using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var dal = dalManager.GetProvider<IG03_Continent_ReChildDal>(); var data = dal.Fetch(continent_ID2); Fetch(data); } OnFetchPost(args); // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="G03_Continent_ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_Child_NameProperty, dr.GetString("Continent_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="G03_Continent_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G02_Continent parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IG03_Continent_ReChildDal>(); using (BypassPropertyChecks) { dal.Insert( parent.Continent_ID, Continent_Child_Name ); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="G03_Continent_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(G02_Continent parent) { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IG03_Continent_ReChildDal>(); using (BypassPropertyChecks) { dal.Update( parent.Continent_ID, Continent_Child_Name ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="G03_Continent_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(G02_Continent parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IG03_Continent_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Continent_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace UnityEditor.XCodeEditorChartboost { using Debug = UnityEngine.Debug; public class PBXFileReference : PBXObject { protected const string PATH_KEY = "path"; protected const string NAME_KEY = "name"; protected const string SOURCETREE_KEY = "sourceTree"; protected const string EXPLICIT_FILE_TYPE_KEY = "explicitFileType"; protected const string LASTKNOWN_FILE_TYPE_KEY = "lastKnownFileType"; protected const string ENCODING_KEY = "fileEncoding"; public string buildPhase; public readonly Dictionary<TreeEnum, string> trees = new Dictionary<TreeEnum, string> { { TreeEnum.ABSOLUTE, "<absolute>" }, { TreeEnum.GROUP, "<group>" }, { TreeEnum.BUILT_PRODUCTS_DIR, "BUILT_PRODUCTS_DIR" }, { TreeEnum.DEVELOPER_DIR, "DEVELOPER_DIR" }, { TreeEnum.SDKROOT, "SDKROOT" }, { TreeEnum.SOURCE_ROOT, "SOURCE_ROOT" } }; public static readonly Dictionary<string, string> typeNames = new Dictionary<string, string> { { ".a", "archive.ar" }, { ".app", "wrapper.application" }, { ".s", "sourcecode.asm" }, { ".c", "sourcecode.c.c" }, { ".cpp", "sourcecode.cpp.cpp" }, { ".framework", "wrapper.framework" }, { ".h", "sourcecode.c.h" }, { ".icns", "image.icns" }, { ".m", "sourcecode.c.objc" }, { ".mm", "sourcecode.cpp.objcpp" }, { ".nib", "wrapper.nib" }, { ".plist", "text.plist.xml" }, { ".png", "image.png" }, { ".rtf", "text.rtf" }, { ".tiff", "image.tiff" }, { ".txt", "text" }, { ".xcodeproj", "wrapper.pb-project" }, { ".xib", "file.xib" }, { ".strings", "text.plist.strings" }, { ".bundle", "wrapper.plug-in" }, { ".dylib", "compiled.mach-o.dylib" } }; public static readonly Dictionary<string, string> typePhases = new Dictionary<string, string> { { ".a", "PBXFrameworksBuildPhase" }, { ".app", null }, { ".s", "PBXSourcesBuildPhase" }, { ".c", "PBXSourcesBuildPhase" }, { ".cpp", "PBXSourcesBuildPhase" }, { ".framework", "PBXFrameworksBuildPhase" }, { ".h", null }, { ".icns", "PBXResourcesBuildPhase" }, { ".m", "PBXSourcesBuildPhase" }, { ".mm", "PBXSourcesBuildPhase" }, { ".nib", "PBXResourcesBuildPhase" }, { ".plist", "PBXResourcesBuildPhase" }, { ".png", "PBXResourcesBuildPhase" }, { ".rtf", "PBXResourcesBuildPhase" }, { ".tiff", "PBXResourcesBuildPhase" }, { ".txt", "PBXResourcesBuildPhase" }, { ".xcodeproj", null }, { ".xib", "PBXResourcesBuildPhase" }, { ".strings", "PBXResourcesBuildPhase" }, { ".bundle", "PBXResourcesBuildPhase" }, { ".dylib", "PBXFrameworksBuildPhase" } }; public PBXFileReference( string guid, PBXDictionary dictionary ) : base( guid, dictionary ) { } public PBXFileReference( string filePath, TreeEnum tree = TreeEnum.SOURCE_ROOT ) : base() { this.Add( PATH_KEY, filePath ); this.Add( NAME_KEY, System.IO.Path.GetFileName( filePath ) ); this.Add( SOURCETREE_KEY, (string)( System.IO.Path.IsPathRooted( filePath ) ? trees[TreeEnum.ABSOLUTE] : trees[tree] ) ); this.GuessFileType(); } public string name { get { if( !ContainsKey( NAME_KEY ) ) { return null; } return (string)_data[NAME_KEY]; } } private void GuessFileType() { this.Remove( EXPLICIT_FILE_TYPE_KEY ); this.Remove( LASTKNOWN_FILE_TYPE_KEY ); string extension = System.IO.Path.GetExtension( (string)_data[ PATH_KEY ] ); if( !PBXFileReference.typeNames.ContainsKey( extension ) ){ Debug.LogWarning( "Unknown file extension: " + extension + "\nPlease add extension and Xcode type to PBXFileReference.types" ); return; } this.Add( LASTKNOWN_FILE_TYPE_KEY, PBXFileReference.typeNames[ extension ] ); this.buildPhase = PBXFileReference.typePhases[ extension ]; } private void SetFileType( string fileType ) { this.Remove( EXPLICIT_FILE_TYPE_KEY ); this.Remove( LASTKNOWN_FILE_TYPE_KEY ); this.Add( EXPLICIT_FILE_TYPE_KEY, fileType ); } // class PBXFileReference(PBXType): // def __init__(self, d=None): // PBXType.__init__(self, d) // self.build_phase = None // // types = { // '.a':('archive.ar', 'PBXFrameworksBuildPhase'), // '.app': ('wrapper.application', None), // '.s': ('sourcecode.asm', 'PBXSourcesBuildPhase'), // '.c': ('sourcecode.c.c', 'PBXSourcesBuildPhase'), // '.cpp': ('sourcecode.cpp.cpp', 'PBXSourcesBuildPhase'), // '.framework': ('wrapper.framework','PBXFrameworksBuildPhase'), // '.h': ('sourcecode.c.h', None), // '.icns': ('image.icns','PBXResourcesBuildPhase'), // '.m': ('sourcecode.c.objc', 'PBXSourcesBuildPhase'), // '.mm': ('sourcecode.cpp.objcpp', 'PBXSourcesBuildPhase'), // '.nib': ('wrapper.nib', 'PBXResourcesBuildPhase'), // '.plist': ('text.plist.xml', 'PBXResourcesBuildPhase'), // '.png': ('image.png', 'PBXResourcesBuildPhase'), // '.rtf': ('text.rtf', 'PBXResourcesBuildPhase'), // '.tiff': ('image.tiff', 'PBXResourcesBuildPhase'), // '.txt': ('text', 'PBXResourcesBuildPhase'), // '.xcodeproj': ('wrapper.pb-project', None), // '.xib': ('file.xib', 'PBXResourcesBuildPhase'), // '.strings': ('text.plist.strings', 'PBXResourcesBuildPhase'), // '.bundle': ('wrapper.plug-in', 'PBXResourcesBuildPhase'), // '.dylib': ('compiled.mach-o.dylib', 'PBXFrameworksBuildPhase') // } // // trees = [ // '<absolute>', // '<group>', // 'BUILT_PRODUCTS_DIR', // 'DEVELOPER_DIR', // 'SDKROOT', // 'SOURCE_ROOT', // ] // // def guess_file_type(self): // self.remove('explicitFileType') // self.remove('lastKnownFileType') // ext = os.path.splitext(self.get('name', ''))[1] // // f_type, build_phase = PBXFileReference.types.get(ext, ('?', None)) // // self['lastKnownFileType'] = f_type // self.build_phase = build_phase // // if f_type == '?': // print 'unknown file extension: %s' % ext // print 'please add extension and Xcode type to PBXFileReference.types' // // return f_type // // def set_file_type(self, ft): // self.remove('explicitFileType') // self.remove('lastKnownFileType') // // self['explicitFileType'] = ft // // @classmethod // def Create(cls, os_path, tree='SOURCE_ROOT'): // if tree not in cls.trees: // print 'Not a valid sourceTree type: %s' % tree // return None // // fr = cls() // fr.id = cls.GenerateId() // fr['path'] = os_path // fr['name'] = os.path.split(os_path)[1] // fr['sourceTree'] = '<absolute>' if os.path.isabs(os_path) else tree // fr.guess_file_type() // // return fr } public enum TreeEnum { ABSOLUTE, GROUP, BUILT_PRODUCTS_DIR, DEVELOPER_DIR, SDKROOT, SOURCE_ROOT } }
/** * 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.Collections.Generic; using IndexOutput = Lucene.Net.Store.IndexOutput; using RAMOutputStream = Lucene.Net.Store.RAMOutputStream; using ArrayUtil = Lucene.Net.Util.ArrayUtil; namespace Lucene.Net.Index { internal sealed class TermVectorsTermsWriter : TermsHashConsumer { internal readonly DocumentsWriter docWriter; //internal TermVectorsWriter termVectorsWriter; internal PerDoc[] docFreeList = new PerDoc[1]; internal int freeCount; internal IndexOutput tvx; internal IndexOutput tvd; internal IndexOutput tvf; internal int lastDocID; public TermVectorsTermsWriter(DocumentsWriter docWriter) { this.docWriter = docWriter; } internal override TermsHashConsumerPerThread addThread(TermsHashPerThread termsHashPerThread) { return new TermVectorsTermsWriterPerThread(termsHashPerThread, this); } internal override void createPostings(RawPostingList[] postings, int start, int count) { int end = start + count; for (int i = start; i < end; i++) postings[i] = new PostingList(); } internal override void flush(IDictionary<object, object> threadsAndFields, DocumentsWriter.FlushState state) { lock (this) { if (tvx != null) { if (state.numDocsInStore > 0) // In case there are some documents that we // didn't see (because they hit a non-aborting exception): fill(state.numDocsInStore - docWriter.GetDocStoreOffset()); tvx.Flush(); tvd.Flush(); tvf.Flush(); } IEnumerator<KeyValuePair<object, object>> it = threadsAndFields.GetEnumerator(); while (it.MoveNext()) { KeyValuePair<object, object> entry = (KeyValuePair<object, object>)it.Current; IEnumerator<object> it2 = ((ICollection<object>)entry.Value).GetEnumerator(); while (it2.MoveNext()) { TermVectorsTermsWriterPerField perField = (TermVectorsTermsWriterPerField)it2.Current; perField.termsHashPerField.reset(); perField.shrinkHash(); } TermVectorsTermsWriterPerThread perThread = (TermVectorsTermsWriterPerThread)entry.Key; perThread.termsHashPerThread.reset(true); } } } internal override void closeDocStore(DocumentsWriter.FlushState state) { lock (this) { if (tvx != null) { // At least one doc in this run had term vectors // enabled fill(state.numDocsInStore - docWriter.GetDocStoreOffset()); tvx.Close(); tvf.Close(); tvd.Close(); tvx = null; System.Diagnostics.Debug.Assert(state.docStoreSegmentName != null); if (4 + state.numDocsInStore * 16 != state.directory.FileLength(state.docStoreSegmentName + "." + IndexFileNames.VECTORS_INDEX_EXTENSION)) throw new System.SystemException("after flush: tvx size mismatch: " + state.numDocsInStore + " docs vs " + state.directory.FileLength(state.docStoreSegmentName + "." + IndexFileNames.VECTORS_INDEX_EXTENSION) + " length in bytes of " + state.docStoreSegmentName + "." + IndexFileNames.VECTORS_INDEX_EXTENSION); string tvxFile = state.docStoreSegmentName + "." + IndexFileNames.VECTORS_INDEX_EXTENSION; string tvfFile = state.docStoreSegmentName + "." + IndexFileNames.VECTORS_FIELDS_EXTENSION; string tvdFile = state.docStoreSegmentName + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION; state.flushedFiles[tvxFile] = tvxFile; state.flushedFiles[tvfFile] = tvfFile; state.flushedFiles[tvdFile] = tvdFile; docWriter.RemoveOpenFile(tvxFile); docWriter.RemoveOpenFile(tvfFile); docWriter.RemoveOpenFile(tvdFile); lastDocID = 0; } } } internal int allocCount; internal PerDoc getPerDoc() { lock (this) { if (freeCount == 0) { allocCount++; if (allocCount > docFreeList.Length) { // Grow our free list up front to make sure we have // enough space to recycle all outstanding PerDoc // instances System.Diagnostics.Debug.Assert(allocCount == 1 + docFreeList.Length); docFreeList = new PerDoc[ArrayUtil.GetNextSize(allocCount)]; } return new PerDoc(this); } else return docFreeList[--freeCount]; } } /** Fills in no-term-vectors for all docs we haven't seen * since the last doc that had term vectors. */ internal void fill(int docID) { int docStoreOffset = docWriter.GetDocStoreOffset(); int end = docID + docStoreOffset; if (lastDocID < end) { long tvfPosition = tvf.GetFilePointer(); while (lastDocID < end) { tvx.WriteLong(tvd.GetFilePointer()); tvd.WriteVInt(0); tvx.WriteLong(tvfPosition); lastDocID++; } } } internal void initTermVectorsWriter() { lock (this) { if (tvx == null) { string docStoreSegment = docWriter.GetDocStoreSegment(); if (docStoreSegment == null) return; System.Diagnostics.Debug.Assert(docStoreSegment != null); // If we hit an exception while init'ing the term // vector output files, we must abort this segment // because those files will be in an unknown // state: tvx = docWriter.directory.CreateOutput(docStoreSegment + "." + IndexFileNames.VECTORS_INDEX_EXTENSION); tvd = docWriter.directory.CreateOutput(docStoreSegment + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION); tvf = docWriter.directory.CreateOutput(docStoreSegment + "." + IndexFileNames.VECTORS_FIELDS_EXTENSION); tvx.WriteInt(TermVectorsReader.FORMAT_CURRENT); tvd.WriteInt(TermVectorsReader.FORMAT_CURRENT); tvf.WriteInt(TermVectorsReader.FORMAT_CURRENT); docWriter.AddOpenFile(docStoreSegment + "." + IndexFileNames.VECTORS_INDEX_EXTENSION); docWriter.AddOpenFile(docStoreSegment + "." + IndexFileNames.VECTORS_FIELDS_EXTENSION); docWriter.AddOpenFile(docStoreSegment + "." + IndexFileNames.VECTORS_DOCUMENTS_EXTENSION); lastDocID = 0; } } } internal void finishDocument(PerDoc perDoc) { lock (this) { System.Diagnostics.Debug.Assert(docWriter.writer.TestPoint("TermVectorsTermsWriter.finishDocument start")); initTermVectorsWriter(); fill(perDoc.docID); // Append term vectors to the real outputs: tvx.WriteLong(tvd.GetFilePointer()); tvx.WriteLong(tvf.GetFilePointer()); tvd.WriteVInt(perDoc.numVectorFields); if (perDoc.numVectorFields > 0) { for (int i = 0; i < perDoc.numVectorFields; i++) tvd.WriteVInt(perDoc.fieldNumbers[i]); System.Diagnostics.Debug.Assert(0 == perDoc.fieldPointers[0]); long lastPos = perDoc.fieldPointers[0]; for (int i = 1; i < perDoc.numVectorFields; i++) { long pos = perDoc.fieldPointers[i]; tvd.WriteVLong(pos - lastPos); lastPos = pos; } perDoc.tvf.WriteTo(tvf); perDoc.tvf.Reset(); perDoc.numVectorFields = 0; } System.Diagnostics.Debug.Assert(lastDocID == perDoc.docID + docWriter.GetDocStoreOffset()); lastDocID++; free(perDoc); System.Diagnostics.Debug.Assert(docWriter.writer.TestPoint("TermVectorsTermsWriter.finishDocument end")); } } public bool freeRAM() { // We don't hold any state beyond one doc, so we don't // free persistent RAM here return false; } internal override void Abort() { if (tvx != null) { try { tvx.Close(); } catch (System.Exception) { } tvx = null; } if (tvd != null) { try { tvd.Close(); } catch (System.Exception) { } tvd = null; } if (tvf != null) { try { tvf.Close(); } catch (System.Exception) { } tvf = null; } lastDocID = 0; } internal void free(PerDoc doc) { lock (this) { System.Diagnostics.Debug.Assert(freeCount < docFreeList.Length); docFreeList[freeCount++] = doc; } } internal class PerDoc : DocumentsWriter.DocWriter { // TODO: use something more memory efficient; for small // docs the 1024 buffer size of RAMOutputStream wastes alot internal RAMOutputStream tvf = new RAMOutputStream(); internal int numVectorFields; internal int[] fieldNumbers = new int[1]; internal long[] fieldPointers = new long[1]; private TermVectorsTermsWriter enclosing_instance; internal PerDoc(TermVectorsTermsWriter enclosing_instance) { this.enclosing_instance = enclosing_instance; } internal void reset() { tvf.Reset(); numVectorFields = 0; } internal override void Abort() { reset(); enclosing_instance.free(this); } internal void addField(int fieldNumber) { if (numVectorFields == fieldNumbers.Length) { fieldNumbers = ArrayUtil.Grow(fieldNumbers); fieldPointers = ArrayUtil.Grow(fieldPointers); } fieldNumbers[numVectorFields] = fieldNumber; fieldPointers[numVectorFields] = tvf.GetFilePointer(); numVectorFields++; } internal override long SizeInBytes() { return tvf.SizeInBytes(); } internal override void Finish() { enclosing_instance.finishDocument(this); } } internal class PostingList : RawPostingList { internal int freq; // How many times this term occurred in the current doc internal int lastOffset; // Last offset we saw internal int lastPosition; // Last position where this term occurred } internal override int bytesPerPosting() { return RawPostingList.BYTES_SIZE + 3 * DocumentsWriter.INT_NUM_BYTE; } } }
using UnityEngine; using System.Collections; using Xft; using System.Collections.Generic; namespace Xft { public class CustomMesh : RenderObject { protected VertexPool.VertexSegment Vertexsegment; public Mesh MyMesh; public Vector3[] MeshVerts; public Color MyColor; public Vector3 MyPosition = Vector3.zero; public Vector2 MyScale = Vector2.one; public Quaternion MyRotation = Quaternion.identity; public Vector3 MyDirection; Matrix4x4 LocalMat; Matrix4x4 WorldMat; // float Fps = 0.016f; float ElapsedTime = 0f; // EffectNode Owner; public bool ColorChanged = false; public bool UVChanged = false; protected Vector2 LowerLeftUV; protected Vector2 UVDimensions; protected Vector2[] m_oriUvs = null; #region override //x for displacement control //y for dissolve control. public override void ApplyShaderParam(float x, float y) { Vector2 param = Vector2.one; param.x = x; param.y = y; VertexPool pool = Vertexsegment.Pool; int index = Vertexsegment.VertStart; for (int i = 0; i < Vertexsegment.VertCount; i++) { pool.UVs2[index + i] = param; } Vertexsegment.Pool.UV2Changed = true; } public override void Initialize(EffectNode node) { base.Initialize(node); SetColor(Node.Color); SetRotation(Node.OriRotateAngle); SetScale(Node.OriScaleX, Node.OriScaleY); SetUVCoord(Node.LowerLeftUV, Node.UVDimensions); //if (Node.Owner.DirType != DIRECTION_TYPE.Sphere) // SetDirection(Node.Owner.ClientTransform.rotation * Node.OriDirection); //else SetDirection(Node.OriDirection); } public override void Reset() { SetColor(Color.clear); SetRotation(Node.OriRotateAngle); Update(true, 0f); } public override void Update(float deltaTime) { SetScale(Node.Scale.x * Node.OriScaleX, Node.Scale.y * Node.OriScaleY); //if (Node.Owner.ColorAffectorEnable || Node.mIsFade) SetColor(Node.Color); if (Node.Owner.UVAffectorEnable || Node.Owner.UVRotAffectorEnable || Node.Owner.UVScaleAffectorEnable) SetUVCoord(Node.LowerLeftUV, Node.UVDimensions); SetRotation((float)Node.OriRotateAngle + Node.RotateAngle); SetPosition(Node.CurWorldPos); Update(false, deltaTime); } #endregion public CustomMesh(VertexPool.VertexSegment segment, Mesh mesh,Vector3 dir, float maxFps) { MyMesh = mesh; MeshVerts = new Vector3[mesh.vertices.Length]; mesh.vertices.CopyTo(MeshVerts,0); Vertexsegment = segment; MyDirection = dir; //Fps = 1f / maxFps; SetPosition(Vector3.zero); InitVerts(); } public void SetDirection(Vector3 dir) { MyDirection = dir; } public void SetUVCoord(Vector2 lowerleft, Vector2 dimensions) { LowerLeftUV = lowerleft; UVDimensions = dimensions; XftTools.TopLeftUVToLowerLeft(ref LowerLeftUV, ref UVDimensions); //Debug.LogWarning(LowerLeftUV + ":" + dimensions); UVChanged = true; } public void SetColor(Color c) { MyColor = c; ColorChanged = true; } public void SetPosition(Vector3 pos) { MyPosition = pos; } public void SetScale(float width, float height) { MyScale.x = width; MyScale.y = height; } public void SetRotation(float angle) { MyRotation = Quaternion.AngleAxis(angle, Node.Owner.MeshRotateAxis); } public void InitVerts() { VertexPool pool = Vertexsegment.Pool; int index = Vertexsegment.IndexStart; int vindex = Vertexsegment.VertStart; for (int i = 0; i < MeshVerts.Length; i++) { //pool.Vertices[vindex + i] = MeshVerts[i]; pool.Vertices[vindex + i] = Vector3.zero; } int[] indices = MyMesh.triangles; for (int i = 0; i < Vertexsegment.IndexCount; i++) { pool.Indices[i + index] = indices[i] + vindex; } m_oriUvs = MyMesh.uv; for (int i = 0; i < m_oriUvs.Length; i++) { pool.UVs[i + vindex] = m_oriUvs[i]; } Color[] colors = MyMesh.colors; for (int i = 0; i < colors.Length; i++) { //pool.Colors[i + vindex] = colors[i]; pool.Colors[i + vindex] = Color.clear; } } public void UpdateUV() { VertexPool pool = Vertexsegment.Pool; int vindex = Vertexsegment.VertStart; for (int i = 0; i < m_oriUvs.Length; i++) { Vector2 curScale = LowerLeftUV + Vector2.Scale(m_oriUvs[i] , UVDimensions); //fix wrap : repeat. if (curScale.x > UVDimensions.x + LowerLeftUV.x) { float delta = curScale.x - UVDimensions.x - LowerLeftUV.x; delta = Mathf.Repeat(delta,UVDimensions.x + LowerLeftUV.x); curScale.x = LowerLeftUV.x + delta * UVDimensions.x; } pool.UVs[i + vindex] = curScale; } Vertexsegment.Pool.UVChanged = true; } public void UpdateColor() { VertexPool pool = Vertexsegment.Pool; int index = Vertexsegment.VertStart; for (int i = 0; i < Vertexsegment.VertCount; i++) { pool.Colors[index + i] = MyColor; } Vertexsegment.Pool.ColorChanged = true; } public void Transform() { Quaternion rot = Quaternion.identity; if (Node.Owner.DirType != DIRECTION_TYPE.Planar)//NOTE, PLANAR DIR JUST IGNORE IT.. rot = Quaternion.FromToRotation(Vector3.up, MyDirection); Quaternion prot = Quaternion.identity; if (Node.Owner.AlwaysSyncRotation) prot = Node.Owner.transform.rotation; Vector3 scale = Vector3.one; scale.x = scale.z = MyScale.x; scale.y = MyScale.y; LocalMat.SetTRS(Vector3.zero, prot * rot * MyRotation, scale); WorldMat.SetTRS(MyPosition, Quaternion.identity, Vector3.one); Matrix4x4 mat = WorldMat * LocalMat; VertexPool pool = Vertexsegment.Pool; for (int i = Vertexsegment.VertStart; i < Vertexsegment.VertStart + Vertexsegment.VertCount; i++) { pool.Vertices[i] = mat.MultiplyPoint3x4(MeshVerts[i - Vertexsegment.VertStart]); } } public void Update(bool force,float deltaTime) { ElapsedTime += deltaTime; if (ElapsedTime > Fps || force) { Transform(); if (ColorChanged) UpdateColor(); if (UVChanged) UpdateUV(); ColorChanged = UVChanged = false; if (!force) ElapsedTime -= Fps; } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Doctors Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KCDDataSet : EduHubDataSet<KCD> { /// <inheritdoc /> public override string Name { get { return "KCD"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KCDDataSet(EduHubContext Context) : base(Context) { Index_KCDKEY = new Lazy<Dictionary<string, KCD>>(() => this.ToDictionary(i => i.KCDKEY)); Index_LW_DATE = new Lazy<NullDictionary<DateTime?, IReadOnlyList<KCD>>>(() => this.ToGroupedNullDictionary(i => i.LW_DATE)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KCD" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KCD" /> fields for each CSV column header</returns> internal override Action<KCD, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KCD, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KCDKEY": mapper[i] = (e, v) => e.KCDKEY = v; break; case "TITLE": mapper[i] = (e, v) => e.TITLE = v; break; case "DR_GROUP": mapper[i] = (e, v) => e.DR_GROUP = v; break; case "ADDRESS01": mapper[i] = (e, v) => e.ADDRESS01 = v; break; case "ADDRESS02": mapper[i] = (e, v) => e.ADDRESS02 = v; break; case "SUBURB": mapper[i] = (e, v) => e.SUBURB = v; break; case "STATE": mapper[i] = (e, v) => e.STATE = v; break; case "POSTCODE": mapper[i] = (e, v) => e.POSTCODE = v; break; case "TELEPHONE": mapper[i] = (e, v) => e.TELEPHONE = v; break; case "FAX": mapper[i] = (e, v) => e.FAX = v; break; case "KAP_LINK": mapper[i] = (e, v) => e.KAP_LINK = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KCD" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KCD" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KCD" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KCD}"/> of entities</returns> internal override IEnumerable<KCD> ApplyDeltaEntities(IEnumerable<KCD> Entities, List<KCD> DeltaEntities) { HashSet<string> Index_KCDKEY = new HashSet<string>(DeltaEntities.Select(i => i.KCDKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KCDKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KCDKEY.Remove(entity.KCDKEY); if (entity.KCDKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, KCD>> Index_KCDKEY; private Lazy<NullDictionary<DateTime?, IReadOnlyList<KCD>>> Index_LW_DATE; #endregion #region Index Methods /// <summary> /// Find KCD by KCDKEY field /// </summary> /// <param name="KCDKEY">KCDKEY value used to find KCD</param> /// <returns>Related KCD entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCD FindByKCDKEY(string KCDKEY) { return Index_KCDKEY.Value[KCDKEY]; } /// <summary> /// Attempt to find KCD by KCDKEY field /// </summary> /// <param name="KCDKEY">KCDKEY value used to find KCD</param> /// <param name="Value">Related KCD entity</param> /// <returns>True if the related KCD entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKCDKEY(string KCDKEY, out KCD Value) { return Index_KCDKEY.Value.TryGetValue(KCDKEY, out Value); } /// <summary> /// Attempt to find KCD by KCDKEY field /// </summary> /// <param name="KCDKEY">KCDKEY value used to find KCD</param> /// <returns>Related KCD entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCD TryFindByKCDKEY(string KCDKEY) { KCD value; if (Index_KCDKEY.Value.TryGetValue(KCDKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find KCD by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find KCD</param> /// <returns>List of related KCD entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCD> FindByLW_DATE(DateTime? LW_DATE) { return Index_LW_DATE.Value[LW_DATE]; } /// <summary> /// Attempt to find KCD by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find KCD</param> /// <param name="Value">List of related KCD entities</param> /// <returns>True if the list of related KCD entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByLW_DATE(DateTime? LW_DATE, out IReadOnlyList<KCD> Value) { return Index_LW_DATE.Value.TryGetValue(LW_DATE, out Value); } /// <summary> /// Attempt to find KCD by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find KCD</param> /// <returns>List of related KCD entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCD> TryFindByLW_DATE(DateTime? LW_DATE) { IReadOnlyList<KCD> value; if (Index_LW_DATE.Value.TryGetValue(LW_DATE, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KCD table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KCD]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KCD]( [KCDKEY] varchar(10) NOT NULL, [TITLE] varchar(30) NULL, [DR_GROUP] varchar(1) NULL, [ADDRESS01] varchar(30) NULL, [ADDRESS02] varchar(30) NULL, [SUBURB] varchar(30) NULL, [STATE] varchar(3) NULL, [POSTCODE] varchar(4) NULL, [TELEPHONE] varchar(20) NULL, [FAX] varchar(20) NULL, [KAP_LINK] varchar(34) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KCD_Index_KCDKEY] PRIMARY KEY CLUSTERED ( [KCDKEY] ASC ) ); CREATE NONCLUSTERED INDEX [KCD_Index_LW_DATE] ON [dbo].[KCD] ( [LW_DATE] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCD]') AND name = N'KCD_Index_LW_DATE') ALTER INDEX [KCD_Index_LW_DATE] ON [dbo].[KCD] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCD]') AND name = N'KCD_Index_LW_DATE') ALTER INDEX [KCD_Index_LW_DATE] ON [dbo].[KCD] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KCD"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KCD"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KCD> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_KCDKEY = new List<string>(); foreach (var entity in Entities) { Index_KCDKEY.Add(entity.KCDKEY); } builder.AppendLine("DELETE [dbo].[KCD] WHERE"); // Index_KCDKEY builder.Append("[KCDKEY] IN ("); for (int index = 0; index < Index_KCDKEY.Count; index++) { if (index != 0) builder.Append(", "); // KCDKEY var parameterKCDKEY = $"@p{parameterIndex++}"; builder.Append(parameterKCDKEY); command.Parameters.Add(parameterKCDKEY, SqlDbType.VarChar, 10).Value = Index_KCDKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCD data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCD data set</returns> public override EduHubDataSetDataReader<KCD> GetDataSetDataReader() { return new KCDDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCD data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCD data set</returns> public override EduHubDataSetDataReader<KCD> GetDataSetDataReader(List<KCD> Entities) { return new KCDDataReader(new EduHubDataSetLoadedReader<KCD>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KCDDataReader : EduHubDataSetDataReader<KCD> { public KCDDataReader(IEduHubDataSetReader<KCD> Reader) : base (Reader) { } public override int FieldCount { get { return 14; } } public override object GetValue(int i) { switch (i) { case 0: // KCDKEY return Current.KCDKEY; case 1: // TITLE return Current.TITLE; case 2: // DR_GROUP return Current.DR_GROUP; case 3: // ADDRESS01 return Current.ADDRESS01; case 4: // ADDRESS02 return Current.ADDRESS02; case 5: // SUBURB return Current.SUBURB; case 6: // STATE return Current.STATE; case 7: // POSTCODE return Current.POSTCODE; case 8: // TELEPHONE return Current.TELEPHONE; case 9: // FAX return Current.FAX; case 10: // KAP_LINK return Current.KAP_LINK; case 11: // LW_DATE return Current.LW_DATE; case 12: // LW_TIME return Current.LW_TIME; case 13: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // TITLE return Current.TITLE == null; case 2: // DR_GROUP return Current.DR_GROUP == null; case 3: // ADDRESS01 return Current.ADDRESS01 == null; case 4: // ADDRESS02 return Current.ADDRESS02 == null; case 5: // SUBURB return Current.SUBURB == null; case 6: // STATE return Current.STATE == null; case 7: // POSTCODE return Current.POSTCODE == null; case 8: // TELEPHONE return Current.TELEPHONE == null; case 9: // FAX return Current.FAX == null; case 10: // KAP_LINK return Current.KAP_LINK == null; case 11: // LW_DATE return Current.LW_DATE == null; case 12: // LW_TIME return Current.LW_TIME == null; case 13: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KCDKEY return "KCDKEY"; case 1: // TITLE return "TITLE"; case 2: // DR_GROUP return "DR_GROUP"; case 3: // ADDRESS01 return "ADDRESS01"; case 4: // ADDRESS02 return "ADDRESS02"; case 5: // SUBURB return "SUBURB"; case 6: // STATE return "STATE"; case 7: // POSTCODE return "POSTCODE"; case 8: // TELEPHONE return "TELEPHONE"; case 9: // FAX return "FAX"; case 10: // KAP_LINK return "KAP_LINK"; case 11: // LW_DATE return "LW_DATE"; case 12: // LW_TIME return "LW_TIME"; case 13: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KCDKEY": return 0; case "TITLE": return 1; case "DR_GROUP": return 2; case "ADDRESS01": return 3; case "ADDRESS02": return 4; case "SUBURB": return 5; case "STATE": return 6; case "POSTCODE": return 7; case "TELEPHONE": return 8; case "FAX": return 9; case "KAP_LINK": return 10; case "LW_DATE": return 11; case "LW_TIME": return 12; case "LW_USER": return 13; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Linq; using System.Collections.Generic; using UnityEditor.Experimental.GraphView; using UnityEngine; using UnityEditor.Experimental.VFX; using Object = UnityEngine.Object; namespace UnityEditor.VFX.UI { class VFXGraphUndoStack { public VFXGraphUndoStack(VFXGraph initialState) { m_graphUndoCursor = ScriptableObject.CreateInstance<VFXGraphUndoCursor>(); m_graphUndoCursor.hideFlags = HideFlags.HideAndDontSave; m_undoStack = new SortedDictionary<int, SerializedState>(); m_graphUndoCursor.index = 0; m_lastGraphUndoCursor = 0; m_undoStack.Add(0, new SerializedState() {serializedGraph = initialState.Backup()}); m_Graph = initialState; } VFXGraph m_Graph; public void IncrementGraphState() { Undo.RecordObject(m_graphUndoCursor, string.Format("VFXGraph ({0})", m_graphUndoCursor.index + 1)); m_graphUndoCursor.index = m_graphUndoCursor.index + 1; } public bool IsDirtyState() { return m_lastGraphUndoCursor != m_graphUndoCursor.index; } public void FlushAndPushGraphState(VFXGraph graph) { int lastCursorInStack = m_undoStack.Last().Key; while (lastCursorInStack > m_lastGraphUndoCursor) { //An action has been performed which overwrite m_undoStack.Remove(lastCursorInStack); lastCursorInStack = m_undoStack.Last().Key; } m_undoStack.Add(m_graphUndoCursor.index, new SerializedState() {serializedGraph = graph.Backup()}); } public void CleanDirtyState() { m_lastGraphUndoCursor = m_graphUndoCursor.index; } public void RestoreCurrentGraphState() { SerializedState refGraph = null; if (!m_undoStack.TryGetValue(m_graphUndoCursor.index, out refGraph)) { throw new Exception(string.Format("Unable to retrieve current state at : {0} (max {1})", m_graphUndoCursor.index, m_undoStack.Last().Key)); } m_Graph.Restore(refGraph.serializedGraph); if (refGraph.slotDeltas != null) { foreach (var kv in refGraph.slotDeltas) { kv.Key.value = kv.Value; } } } public void AddSlotDelta(VFXSlot slot) { SerializedState state = null; if (m_undoStack.TryGetValue(m_lastGraphUndoCursor, out state)) { if (state.slotDeltas == null) state.slotDeltas = new Dictionary<VFXSlot, object>(); state.slotDeltas[slot] = slot.value; } } class SerializedState { public object serializedGraph; public Dictionary<VFXSlot, object> slotDeltas; } [NonSerialized] private SortedDictionary<int, SerializedState> m_undoStack; [NonSerialized] private VFXGraphUndoCursor m_graphUndoCursor; [NonSerialized] private int m_lastGraphUndoCursor; } partial class VFXViewController : Controller<VisualEffectResource> { [NonSerialized] private bool m_reentrant; [NonSerialized] private VFXGraphUndoStack m_graphUndoStack; private void InitializeUndoStack() { m_graphUndoStack = new VFXGraphUndoStack(graph); } private void ReleaseUndoStack() { m_graphUndoStack = null; } public void IncremenentGraphUndoRedoState(VFXModel model, VFXModel.InvalidationCause cause) { if (cause == VFXModel.InvalidationCause.kParamChanged && model is VFXSlot) { m_graphUndoStack.AddSlotDelta(model as VFXSlot); return; } if (cause == VFXModel.InvalidationCause.kExpressionInvalidated || // Ignore invalidation which doesn't modify model cause == VFXModel.InvalidationCause.kExpressionGraphChanged) return; if (m_reentrant) { m_reentrant = false; throw new InvalidOperationException("Reentrant undo/redo, this is not supposed to happen!"); } if (m_graphUndoStack != null) { if (m_graphUndoStack == null) { Debug.LogError("Unexpected IncrementGraphState (not initialize)"); return; } m_graphUndoStack.IncrementGraphState(); } } public bool m_InLiveModification; public void BeginLiveModification() { if (m_InLiveModification == true) throw new InvalidOperationException("BeginLiveModification is not reentrant"); m_InLiveModification = true; } public void EndLiveModification() { if (m_InLiveModification == false) throw new InvalidOperationException("EndLiveModification is not reentrant"); m_InLiveModification = false; if (m_graphUndoStack.IsDirtyState()) { m_graphUndoStack.FlushAndPushGraphState(graph); m_graphUndoStack.CleanDirtyState(); } } private void WillFlushUndoRecord() { if (m_graphUndoStack == null) { return; } if (!m_InLiveModification) { if (m_graphUndoStack.IsDirtyState()) { m_graphUndoStack.FlushAndPushGraphState(graph); m_graphUndoStack.CleanDirtyState(); } } } private void SynchronizeUndoRedoState() { if (m_graphUndoStack == null) { return; } if (m_graphUndoStack.IsDirtyState()) { try { m_graphUndoStack.RestoreCurrentGraphState(); m_reentrant = true; ExpressionGraphDirty = true; model.GetOrCreateGraph().UpdateSubAssets(); NotifyUpdate(); m_reentrant = false; m_graphUndoStack.CleanDirtyState(); } catch (Exception e) { Debug.LogError(e); Undo.ClearAll(); m_graphUndoStack = new VFXGraphUndoStack(graph); } } else { //The graph didn't change by this undo, only, potentially the slot values. // Any undo could be a slot value undo: update input slot expressions and expression graph values ExpressionGraphDirty = true; ExpressionGraphDirtyParamOnly = true; if (model != null && graph != null) { foreach (var element in AllSlotContainerControllers) { foreach (var slot in (element.model as IVFXSlotContainer).inputSlots) { slot.UpdateDefaultExpressionValue(); } } foreach (var parameter in m_ParameterControllers.Keys) { parameter.UpdateDefaultExpressionValue(); } graph.SetExpressionValueDirty(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace System.IO { internal sealed partial class Win32FileSystem : FileSystem { internal const int GENERIC_READ = unchecked((int)0x80000000); public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); int errorCode = Interop.Kernel32.CopyFile(sourceFullPath, destFullPath, !overwrite); if (errorCode != Interop.Errors.ERROR_SUCCESS) { string fileName = destFullPath; if (errorCode != Interop.Errors.ERROR_FILE_EXISTS) { // For a number of error codes (sharing violation, path // not found, etc) we don't know if the problem was with // the source or dest file. Try reading the source file. using (SafeFileHandle handle = Interop.Kernel32.UnsafeCreateFile(sourceFullPath, GENERIC_READ, FileShare.Read, ref secAttrs, FileMode.Open, 0, IntPtr.Zero)) { if (handle.IsInvalid) fileName = sourceFullPath; } if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) { if (DirectoryExists(destFullPath)) throw new IOException(SR.Format(SR.Arg_FileIsDirectory_Name, destFullPath), Interop.Errors.ERROR_ACCESS_DENIED); } } throw Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors) { int flags = ignoreMetadataErrors ? Interop.Kernel32.REPLACEFILE_IGNORE_MERGE_ERRORS : 0; if (!Interop.Kernel32.ReplaceFile(destFullPath, sourceFullPath, destBackupFullPath, flags, IntPtr.Zero, IntPtr.Zero)) { throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } [System.Security.SecuritySafeCritical] public override void CreateDirectory(string fullPath) { // We can save a bunch of work if the directory we want to create already exists. This also // saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the // final path is accessible and the directory already exists. For example, consider trying // to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo // and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar // and fail to due so, causing an exception to be thrown. This is not what we want. if (DirectoryExists(fullPath)) return; List<string> stackDir = new List<string>(); // Attempt to figure out which directories don't exist, and only // create the ones we need. Note that InternalExists may fail due // to Win32 ACL's preventing us from seeing a directory, and this // isn't threadsafe. bool somepathexists = false; int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath)) length--; int lengthRoot = PathInternal.GetRootLength(fullPath); if (length > lengthRoot) { // Special case root (fullpath = X:\\) int i = length - 1; while (i >= lengthRoot && !somepathexists) { string dir = fullPath.Substring(0, i + 1); if (!DirectoryExists(dir)) // Create only the ones missing stackDir.Add(dir); else somepathexists = true; while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) i--; i--; } } int count = stackDir.Count; // If we were passed a DirectorySecurity, convert it to a security // descriptor and set it in he call to CreateDirectory. Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); bool r = true; int firstError = 0; string errorString = fullPath; // If all the security checks succeeded create all the directories while (stackDir.Count > 0) { string name = stackDir[stackDir.Count - 1]; stackDir.RemoveAt(stackDir.Count - 1); r = Interop.Kernel32.CreateDirectory(name, ref secAttrs); if (!r && (firstError == 0)) { int currentError = Marshal.GetLastWin32Error(); // While we tried to avoid creating directories that don't // exist above, there are at least two cases that will // cause us to see ERROR_ALREADY_EXISTS here. InternalExists // can fail because we didn't have permission to the // directory. Secondly, another thread or process could // create the directory between the time we check and the // time we try using the directory. Thirdly, it could // fail because the target does exist, but is a file. if (currentError != Interop.Errors.ERROR_ALREADY_EXISTS) firstError = currentError; else { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. if (File.InternalExists(name) || (!DirectoryExists(name, out currentError) && currentError == Interop.Errors.ERROR_ACCESS_DENIED)) { firstError = currentError; errorString = name; } } } } // We need this check to mask OS differences // Handle CreateDirectory("X:\\") when X: doesn't exist. Similarly for n/w paths. if ((count == 0) && !somepathexists) { string root = Directory.InternalGetDirectoryRoot(fullPath); if (!DirectoryExists(root)) throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, root); return; } // Only throw an exception if creating the exact directory we // wanted failed to work correctly. if (!r && (firstError != 0)) throw Win32Marshal.GetExceptionForWin32Error(firstError, errorString); } public override void DeleteFile(string fullPath) { bool r = Interop.Kernel32.DeleteFile(fullPath); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) return; else throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override bool DirectoryExists(string fullPath) { int lastError = Interop.Errors.ERROR_SUCCESS; return DirectoryExists(fullPath, out lastError); } private bool DirectoryExists(string path, out int lastError) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); lastError = FillAttributeInfo(path, ref data, returnErrorOnNotFound: true); return (lastError == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) != 0); } public override IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return Win32FileSystemEnumerableFactory.CreateFileNameIterator(fullPath, fullPath, searchPattern, (searchTarget & SearchTarget.Files) == SearchTarget.Files, (searchTarget & SearchTarget.Directories) == SearchTarget.Directories, searchOption); } public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { switch (searchTarget) { case SearchTarget.Directories: return Win32FileSystemEnumerableFactory.CreateDirectoryInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Files: return Win32FileSystemEnumerableFactory.CreateFileInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Both: return Win32FileSystemEnumerableFactory.CreateFileSystemInfoIterator(fullPath, fullPath, searchPattern, searchOption); default: throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(searchTarget)); } } /// <summary> /// Returns 0 on success, otherwise a Win32 error code. Note that /// classes should use -1 as the uninitialized state for dataInitialized. /// </summary> /// <param name="returnErrorOnNotFound">Return the error code for not found errors?</param> [System.Security.SecurityCritical] internal static int FillAttributeInfo(string path, ref Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data, bool returnErrorOnNotFound) { int errorCode = Interop.Errors.ERROR_SUCCESS; // Neither GetFileAttributes or FindFirstFile like trailing separators path = path.TrimEnd(PathHelpers.DirectorySeparatorChars); using (DisableMediaInsertionPrompt.Create()) { if (!Interop.Kernel32.GetFileAttributesEx(path, Interop.Kernel32.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data)) { errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) { // Files that are marked for deletion will not let you GetFileAttributes, // ERROR_ACCESS_DENIED is given back without filling out the data struct. // FindFirstFile, however, will. Historically we always gave back attributes // for marked-for-deletion files. var findData = new Interop.Kernel32.WIN32_FIND_DATA(); using (SafeFindHandle handle = Interop.Kernel32.FindFirstFile(path, ref findData)) { if (handle.IsInvalid) { errorCode = Marshal.GetLastWin32Error(); } else { errorCode = Interop.Errors.ERROR_SUCCESS; data.PopulateFrom(ref findData); } } } } } if (errorCode != Interop.Errors.ERROR_SUCCESS && !returnErrorOnNotFound) { switch (errorCode) { case Interop.Errors.ERROR_FILE_NOT_FOUND: case Interop.Errors.ERROR_PATH_NOT_FOUND: case Interop.Errors.ERROR_NOT_READY: // Removable media not ready // Return default value for backward compatibility data.fileAttributes = -1; return Interop.Errors.ERROR_SUCCESS; } } return errorCode; } public override bool FileExists(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); return (errorCode == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0); } public override FileAttributes GetAttributes(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); return (FileAttributes)data.fileAttributes; } public override string GetCurrentDirectory() { StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH + 1); if (Interop.Kernel32.GetCurrentDirectory(sb.Capacity, sb) == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); string currentDirectory = sb.ToString(); // Note that if we have somehow put our command prompt into short // file name mode (i.e. by running edlin or a DOS grep, etc), then // this will return a short file name. if (currentDirectory.IndexOf('~') >= 0) { int r = Interop.Kernel32.GetLongPathName(currentDirectory, sb, sb.Capacity); if (r == 0 || r >= Interop.Kernel32.MAX_PATH) { int errorCode = Marshal.GetLastWin32Error(); if (r >= Interop.Kernel32.MAX_PATH) errorCode = Interop.Errors.ERROR_FILENAME_EXCED_RANGE; if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND && errorCode != Interop.Errors.ERROR_INVALID_FUNCTION && // by design - enough said. errorCode != Interop.Errors.ERROR_ACCESS_DENIED) throw Win32Marshal.GetExceptionForWin32Error(errorCode); } currentDirectory = sb.ToString(); } StringBuilderCache.Release(sb); return currentDirectory; } public override DateTimeOffset GetCreationTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow); return DateTimeOffset.FromFileTime(dt); } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); } public override DateTimeOffset GetLastAccessTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow); return DateTimeOffset.FromFileTime(dt); } public override DateTimeOffset GetLastWriteTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow); return DateTimeOffset.FromFileTime(dt); } public override void MoveDirectory(string sourceFullPath, string destFullPath) { if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, sourceFullPath); // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp. throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), Win32Marshal.MakeHRFromErrorCode(errorCode)); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } public override void MoveFile(string sourceFullPath, string destFullPath) { if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } [System.Security.SecurityCritical] private static SafeFileHandle OpenHandle(string fullPath, bool asDirectory) { string root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath)); if (root == fullPath && root[1] == Path.VolumeSeparatorChar) { // intentionally not fullpath, most upstack public APIs expose this as path. throw new ArgumentException(SR.Arg_PathIsVolume, "path"); } Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); SafeFileHandle handle = Interop.Kernel32.SafeCreateFile( fullPath, Interop.Kernel32.GenericOperations.GENERIC_WRITE, FileShare.ReadWrite | FileShare.Delete, ref secAttrs, FileMode.Open, asDirectory ? Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS : (int)FileOptions.None, IntPtr.Zero ); if (handle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); // NT5 oddity - when trying to open "C:\" as a File, // we usually get ERROR_PATH_NOT_FOUND from the OS. We should // probably be consistent w/ every other directory. if (!asDirectory && errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && fullPath.Equals(Directory.GetDirectoryRoot(fullPath))) errorCode = Interop.Errors.ERROR_ACCESS_DENIED; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } return handle; } public override void RemoveDirectory(string fullPath, bool recursive) { // Do not recursively delete through reparse points. if (!recursive || IsReparsePoint(fullPath)) { RemoveDirectoryInternal(fullPath, topLevel: true); return; } // We want extended syntax so we can delete "extended" subdirectories and files // (most notably ones with trailing whitespace or periods) fullPath = PathInternal.EnsureExtendedPrefix(fullPath); Interop.Kernel32.WIN32_FIND_DATA findData = new Interop.Kernel32.WIN32_FIND_DATA(); RemoveDirectoryRecursive(fullPath, ref findData, topLevel: true); } private static bool IsReparsePoint(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound: true); if (errorCode != Interop.Errors.ERROR_SUCCESS) { // File not found doesn't make much sense coming from a directory delete. if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } return (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0); } private static void RemoveDirectoryRecursive(string fullPath, ref Interop.Kernel32.WIN32_FIND_DATA findData, bool topLevel) { int errorCode; Exception exception = null; using (SafeFindHandle handle = Interop.Kernel32.FindFirstFile(Directory.EnsureTrailingDirectorySeparator(fullPath) + "*", ref findData)) { if (handle.IsInvalid) throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); do { if ((findData.dwFileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0) { // File string fileName = findData.cFileName.GetStringFromFixedBuffer(); if (!Interop.Kernel32.DeleteFile(Path.Combine(fullPath, fileName)) && exception == null) { errorCode = Marshal.GetLastWin32Error(); // We don't care if something else deleted the file first if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } } else { // Directory, skip ".", "..". if (findData.cFileName.FixedBufferEqualsString(".") || findData.cFileName.FixedBufferEqualsString("..")) continue; string fileName = findData.cFileName.GetStringFromFixedBuffer(); if ((findData.dwFileAttributes & (int)FileAttributes.ReparsePoint) == 0) { // Not a reparse point, recurse. try { RemoveDirectoryRecursive( Path.Combine(fullPath, fileName), findData: ref findData, topLevel: false); } catch (Exception e) { if (exception == null) exception = e; } } else { // Reparse point, don't recurse, just remove. (dwReserved0 is documented for this flag) if (findData.dwReserved0 == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT) { // Mount point. Unmount using full path plus a trailing '\'. // (Note: This doesn't remove the underlying directory) string mountPoint = Path.Combine(fullPath, fileName + PathHelpers.DirectorySeparatorCharAsString); if (!Interop.Kernel32.DeleteVolumeMountPoint(mountPoint) && exception == null) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_SUCCESS && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } } // Note that RemoveDirectory on a symbolic link will remove the link itself. if (!Interop.Kernel32.RemoveDirectory(Path.Combine(fullPath, fileName)) && exception == null) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } } } } while (Interop.Kernel32.FindNextFile(handle, ref findData)); if (exception != null) throw exception; errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_SUCCESS && errorCode != Interop.Errors.ERROR_NO_MORE_FILES) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } // As we successfully removed all of the files we shouldn't care about the directory itself // not being empty. As file deletion is just a marker to remove the file when all handles // are closed we could still have contents hanging around. RemoveDirectoryInternal(fullPath, topLevel: topLevel, allowDirectoryNotEmpty: true); } private static void RemoveDirectoryInternal(string fullPath, bool topLevel, bool allowDirectoryNotEmpty = false) { if (!Interop.Kernel32.RemoveDirectory(fullPath)) { int errorCode = Marshal.GetLastWin32Error(); switch (errorCode) { case Interop.Errors.ERROR_FILE_NOT_FOUND: // File not found doesn't make much sense coming from a directory delete. errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; goto case Interop.Errors.ERROR_PATH_NOT_FOUND; case Interop.Errors.ERROR_PATH_NOT_FOUND: // We only throw for the top level directory not found, not for any contents. if (!topLevel) return; break; case Interop.Errors.ERROR_DIR_NOT_EMPTY: if (allowDirectoryNotEmpty) return; break; case Interop.Errors.ERROR_ACCESS_DENIED: // This conversion was originally put in for Win9x. Keeping for compatibility. throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); } throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetAttributes(string fullPath, FileAttributes attributes) { SetAttributesInternal(fullPath, attributes); } private static void SetAttributesInternal(string fullPath, FileAttributes attributes) { bool r = Interop.Kernel32.SetFileAttributes(fullPath, (int)attributes); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_PARAMETER) throw new ArgumentException(SR.Arg_InvalidFileAttrs, nameof(attributes)); throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetCreationTimeInternal(fullPath, time, asDirectory); } private static void SetCreationTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, creationTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetCurrentDirectory(string fullPath) { if (!Interop.Kernel32.SetCurrentDirectory(fullPath)) { // If path doesn't exist, this sets last error to 2 (File // not Found). LEGACY: This may potentially have worked correctly // on Win9x, maybe. int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastAccessTimeInternal(fullPath, time, asDirectory); } private static void SetLastAccessTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, lastAccessTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastWriteTimeInternal(fullPath, time, asDirectory); } private static void SetLastWriteTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, lastWriteTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override string[] GetLogicalDrives() { return DriveInfoInternal.GetLogicalDrives(); } } }
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 VSLiveSampleService.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; } } }
using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Xml; namespace FileHelpers.Dynamic { /// <summary>The MAIN class to work with runtime defined records.</summary> public abstract class ClassBuilder { //--------------------- //-> STATIC METHODS #region LoadFromString /// <summary>Compiles the source code passed and returns the FIRST Type of the assembly. (Code in C#)</summary> /// <param name="classStr">The Source Code of the class in C#</param> /// <returns>The Type generated by runtime compilation of the class source.</returns> public static Type ClassFromString(string classStr) { return ClassFromString(classStr, ""); } /// <summary>Compiles the source code passed and returns the FIRST Type of the assembly.</summary> /// <param name="classStr">The Source Code of the class in the specified language</param> /// <returns>The Type generated by runtime compilation of the class source.</returns> /// <param name="lang">One of the .NET Languages</param> public static Type ClassFromString(string classStr, NetLanguage lang) { return ClassFromString(classStr, "", lang); } /// <summary>Compiles the source code passed and returns the Type with the name className. (Code in C#)</summary> /// <param name="classStr">The Source Code of the class in C#</param> /// <param name="className">The Name of the Type that must be returned</param> /// <returns>The Type generated by runtime compilation of the class source.</returns> public static Type ClassFromString(string classStr, string className) { return ClassFromString(classStr, className, NetLanguage.CSharp); } private static List<string> mReferences; private static readonly object mReferencesLock = new object(); /// <summary>Compiles the source code passed and returns the Type with the name className.</summary> /// <param name="classStr">The Source Code of the class in the specified language</param> /// <param name="className">The Name of the Type that must be returned</param> /// <param name="lang">One of the .NET Languages</param> /// <param name="additionalReferences">List of assemblies to be added in the dynamic compilation </param> /// <returns>The Type generated by runtime compilation of the class source.</returns> public static Type ClassFromString(string classStr, string className, NetLanguage lang, List<Assembly> additionalReferences = null) { if (classStr.Length < 4) { throw new BadUsageException( "There is not enough text to be a proper class, load your class and try again"); } var cp = new CompilerParameters(); //cp.ReferencedAssemblies.Add("System.dll"); //cp.ReferencedAssemblies.Add("System.Data.dll"); //cp.ReferencedAssemblies.Add(typeof(ClassBuilder).Assembly.GetModules()[0].FullyQualifiedName); bool mustAddSystemData = false; lock (mReferencesLock) { if (mReferences == null) { mReferences = new List<string>(); var added = new Dictionary<string, bool>(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { Module module = assembly.GetModules()[0]; if (module.Name == "mscorlib.dll" || module.Name == "<Unknown>") continue; if (module.Name == "System.Data.dll") mustAddSystemData = true; if (!module.Name.Equals("System.Data.dll", StringComparison.OrdinalIgnoreCase) && !module.Name.Equals("System.Core.dll", StringComparison.OrdinalIgnoreCase) && !module.Name.Equals("System.dll", StringComparison.OrdinalIgnoreCase) && !module.Name.Equals("FileHelpers.dll", StringComparison.OrdinalIgnoreCase) && !module.Name.Equals("System.Xml.dll", StringComparison.OrdinalIgnoreCase) ) { continue; } var moduleName = module.Name.ToLower(); if (added.ContainsKey(moduleName)) continue; added.Add(moduleName, true); if (File.Exists(module.FullyQualifiedName)) mReferences.Add(module.FullyQualifiedName); } } if (additionalReferences != null) { foreach (var additionalReference in additionalReferences) { var moduleName = additionalReference.GetModules()[0].FullyQualifiedName; foreach (var reference in mReferences) { if (reference.Equals(moduleName, StringComparison.OrdinalIgnoreCase)) { moduleName = ""; break; } } if (moduleName.Length > 0) mReferences.Add(moduleName); } } } cp.ReferencedAssemblies.AddRange(mReferences.ToArray()); cp.GenerateExecutable = false; cp.GenerateInMemory = true; cp.IncludeDebugInformation = false; var code = new StringBuilder(); switch (lang) { case NetLanguage.CSharp: code.Append("using System; using FileHelpers; using System.Collections; using System.Collections.Generic;"); if (mustAddSystemData) code.Append(" using System.Data;"); break; case NetLanguage.VbNet: if ( CultureInfo.CurrentCulture.CompareInfo.IndexOf(classStr, "Imports System", CompareOptions.IgnoreCase) == -1) code.Append("Imports System\n"); if ( CultureInfo.CurrentCulture.CompareInfo.IndexOf(classStr, "Imports FileHelpers", CompareOptions.IgnoreCase) == -1) code.Append("Imports FileHelpers\n"); if (mustAddSystemData && CultureInfo.CurrentCulture.CompareInfo.IndexOf(classStr, "Imports System.Data", CompareOptions.IgnoreCase) == -1) code.Append("Imports System.Data\n"); break; } code.Append(classStr); CodeDomProvider prov = null; switch (lang) { case NetLanguage.CSharp: prov = CodeDomProvider.CreateProvider("cs"); break; case NetLanguage.VbNet: prov = CodeDomProvider.CreateProvider("vb"); break; } var cr = prov.CompileAssemblyFromSource(cp, code.ToString()); if (cr.Errors.HasErrors) { var error = new StringBuilder(); error.Append("Error Compiling Expression: " + StringHelper.NewLine); foreach (CompilerError err in cr.Errors) error.AppendFormat("Line {0}: {1}\n", err.Line, err.ErrorText); throw new DynamicCompilationException(error.ToString(), classStr, cr.Errors); } // Assembly.Load(cr.CompiledAssembly.); if (className != "") return cr.CompiledAssembly.GetType(className, true, true); else { Type[] ts = cr.CompiledAssembly.GetTypes(); if (ts.Length > 0) { foreach (var t in ts) { if (t.FullName.StartsWith("My.My") == false && t.IsDefined(typeof (TypedRecordAttribute), false)) return t; } } throw new BadUsageException("The compiled assembly does not have any type inside."); } } #endregion //public bool AddCurrentDomainReferences { get; set; } #region CreateFromFile /// <summary> /// Create a class from a source file. /// </summary> /// <param name="filename">The filename with the source of the class.</param> /// <returns>The compiled class.</returns> public static Type ClassFromSourceFile(string filename) { return ClassFromSourceFile(filename, ""); } /// <summary> /// Create a class from a source file. /// </summary> /// <param name="filename">The filename with the source of the class.</param> /// <param name="lang">The language used to compile the class.</param> /// <returns>The compiled class.</returns> public static Type ClassFromSourceFile(string filename, NetLanguage lang) { return ClassFromSourceFile(filename, "", lang); } /// <summary> /// Create a class from a source file. /// </summary> /// <param name="filename">The filename with the source of the class.</param> /// <param name="className">The name of the class to return.</param> /// <returns>The compiled class.</returns> public static Type ClassFromSourceFile(string filename, string className) { return ClassFromSourceFile(filename, className, NetLanguage.CSharp); } /// <summary> /// Create a class from a source file. /// </summary> /// <param name="filename">The filename with the source of the class.</param> /// <param name="className">The name of the class to return.</param> /// <param name="lang">The language used to compile the class.</param> /// <returns>The compiled class.</returns> public static Type ClassFromSourceFile(string filename, string className, NetLanguage lang) { var reader = new StreamReader(filename); string classDef = reader.ReadToEnd(); reader.Close(); return ClassFromString(classDef, className, lang); } /// <summary> /// Create a class from a encrypted source file with the default password /// </summary> /// <param name="filename">The filename with the source of the class.</param> /// <returns>The compiled class.</returns> public static Type ClassFromBinaryFile(string filename) { return ClassFromBinaryFile(filename, "", NetLanguage.CSharp); } /// <summary> /// Create a class from a encrypted source file with the default password /// </summary> /// <param name="filename">The filename with the source of the class.</param> /// <param name="lang">The language used to compile the class.</param> /// <returns>The compiled class.</returns> public static Type ClassFromBinaryFile(string filename, NetLanguage lang) { return ClassFromBinaryFile(filename, "", lang); } /// <summary> /// Create a class from a encrypted source file with the default password /// </summary> /// <param name="filename">The filename with the source of the class.</param> /// <param name="lang">The language used to compile the class.</param> /// <param name="className">The name of the class to return.</param> /// <returns>The compiled class.</returns> public static Type ClassFromBinaryFile(string filename, string className, NetLanguage lang) { return ClassFromBinaryFile(filename, className, lang, "withthefilehelpers1.0.0youcancodewithoutproblems1.5.0"); } /// <summary> /// Create a class from a encrypted source file with the given password /// </summary> /// <remarks>Edited by: Shreyas Narasimhan (17 March 2010)</remarks> /// <param name="filename">The filename with the source of the class.</param> /// <param name="className">The name of the class to return.</param> /// <param name="lang">The language used to compile the class.</param> /// <param name="password">The password used to decrypt the file</param> /// <returns></returns> public static Type ClassFromBinaryFile(string filename, string className, NetLanguage lang, string password) { var reader = new StreamReader(filename); string classDef = reader.ReadToEnd(); reader.Close(); classDef = Decrypt(classDef, password); return ClassFromString(classDef, className, lang); } /// <summary> /// Create a class from a XML file generated with the Wizard or /// saved using the SaveToXml Method. /// </summary> /// <param name="filename">The filename with the XML definition.</param> /// <returns>The compiled class.</returns> public static Type ClassFromXmlFile(string filename) { ClassBuilder cb = LoadFromXml(filename); return cb.CreateRecordClass(); } /// <summary> /// Encrypt the class source code with the default password and write it to a file. /// </summary> /// <param name="filename">The file name to write to.</param> /// <param name="classSource">The class source to write to</param> public static void ClassToBinaryFile(string filename, string classSource) { ClassToBinaryFile(filename, classSource, "withthefilehelpers1.0.0youcancodewithoutproblems1.5.0"); } /// <summary> /// Encrypt the class source code with the given password and write it to a file. /// </summary> /// <remarks>Edited by: Shreyas Narasimhan (17 March 2010)</remarks> /// <param name="filename">The file name to write to</param> /// <param name="classSource">The class source to write to</param> /// <param name="password">The password with which to encrypt the file</param> public static void ClassToBinaryFile(string filename, string classSource, string password) { classSource = Encrypt(classSource, password); var writer = new StreamWriter(filename); writer.Write(classSource); writer.Close(); } #endregion public List<Assembly> AdditionalReferences { get; private set; } #region SaveToFile /// <summary>Write the source code of the current class to a file. (In C#)</summary> /// <param name="filename">The file to write to.</param> public void SaveToSourceFile(string filename) { SaveToSourceFile(filename, NetLanguage.CSharp); } /// <summary>Write the source code of the current class to a file. (In the specified language)</summary> /// <param name="filename">The file to write to.</param> /// <param name="lang">The .NET Language used to write the source code.</param> public void SaveToSourceFile(string filename, NetLanguage lang) { var writer = new StreamWriter(filename); writer.Write(GetClassSourceCode(lang)); writer.Close(); } /// <summary>Write the ENCRYPTED source code of the current class to a file. (In C#)</summary> /// <param name="filename">The file to write to.</param> public void SaveToBinaryFile(string filename) { SaveToBinaryFile(filename, NetLanguage.CSharp); } /// <summary>Write the ENCRYPTED source code of the current class to a file. (In C#)</summary> /// <param name="filename">The file to write to.</param> /// <param name="lang">The .NET Language used to write the source code.</param> public void SaveToBinaryFile(string filename, NetLanguage lang) { var writer = new StreamWriter(filename); writer.Write(GetClassBinaryCode(lang)); writer.Close(); } #endregion /// <summary> /// Create a class with 'classname' /// </summary> /// <param name="className">Name of class to create</param> internal ClassBuilder(string className) { className = className.Trim(); if (ValidIdentifierValidator.ValidIdentifier(className) == false) { throw new FileHelpersException(Messages.Errors.InvalidIdentifier .Identifier(className) .Text); } mClassName = className; AdditionalReferences = new List<Assembly>(); } /// <summary>Generate the runtime record class to be used by the engines.</summary> /// <returns>The generated record class</returns> public Type CreateRecordClass() { string classCode = GetClassSourceCode(NetLanguage.CSharp); return ClassFromString(classCode, "", NetLanguage.CSharp, AdditionalReferences); } //-------------- //-> Fields #region Fields /// <summary>Removes all the Fields of the current class.</summary> public void ClearFields() { mFields.Clear(); } /// <summary> /// List of all the fields in the class /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal ArrayList mFields = new ArrayList(); /// <summary> /// Add a field to the class /// </summary> /// <param name="field">Field details to add</param> internal void AddFieldInternal(FieldBuilder field) { field.mFieldIndex = mFields.Add(field); field.mClassBuilder = this; } /// <summary>Returns the current fields of the class.</summary> public FieldBuilder[] Fields { get { return (FieldBuilder[]) mFields.ToArray(typeof (FieldBuilder)); } } /// <summary>Returns the current number of fields.</summary> public int FieldCount { get { return mFields.Count; } } /// <summary>Return the field at the specified index.</summary> /// <param name="index">The index of the field.</param> /// <returns>The field at the specified index.</returns> public FieldBuilder FieldByIndex(int index) { return (FieldBuilder) mFields[index]; } #endregion #region ClassName [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string mClassName; /// <summary>Gets or sets the name of the Class.</summary> public string ClassName { get { return mClassName; } set { mClassName = value; } } #endregion //---------------------------- //-> ATTRIBUTE MAPPING #region IgnoreFirstLines [DebuggerBrowsable(DebuggerBrowsableState.Never)] private int mIgnoreFirstLines = 0; /// <summary>Indicates the number of FIRST LINES or heading records to be ignored by the engines.</summary> public int IgnoreFirstLines { get { return mIgnoreFirstLines; } set { mIgnoreFirstLines = value; } } #endregion #region IgnoreLastLines [DebuggerBrowsable(DebuggerBrowsableState.Never)] private int mIgnoreLastLines = 0; /// <summary>Indicates the number of LAST LINES or trailing records to be ignored by the engines.</summary> public int IgnoreLastLines { get { return mIgnoreLastLines; } set { mIgnoreLastLines = value; } } #endregion #region IgnoreEmptyLines [DebuggerBrowsable(DebuggerBrowsableState.Never)] private bool mIgnoreEmptyLines = false; /// <summary>Indicates that the engines must ignore the empty lines in the files.</summary> public bool IgnoreEmptyLines { get { return mIgnoreEmptyLines; } set { mIgnoreEmptyLines = value; } } #endregion [DebuggerBrowsable(DebuggerBrowsableState.Never)] private bool mGenerateProperties = false; /// <summary>Indicates if this ClassBuilder generates also the property accessors (Perfect for DataBinding)</summary> public bool GenerateProperties { get { return mGenerateProperties; } set { mGenerateProperties = value; } } /// <summary> /// Returns the ENCRYPTED code for the current class in the specified language. /// </summary> /// <param name="lang">The language for the return code.</param> /// <returns>The ENCRYPTED code for the class that are currently building.</returns> public string GetClassBinaryCode(NetLanguage lang) { return Encrypt(GetClassSourceCode(lang), "withthefilehelpers1.0.0youcancodewithoutproblems1.5.0"); } /// <summary> /// Returns the source code for the current class in the specified language. /// </summary> /// <param name="lang">The language for the return code.</param> /// <returns>The Source Code for the class that are currently building.</returns> public string GetClassSourceCode(NetLanguage lang) { ValidateClass(); var sb = new StringBuilder(100); BeginNamespace(lang, sb); var attbs = new AttributesBuilder(lang); AddAttributesInternal(attbs); AddAttributesCode(attbs, lang); sb.Append(attbs.GetAttributesCode()); switch (lang) { case NetLanguage.VbNet: sb.Append(GetVisibility(lang, mVisibility) + GetSealed(lang) + "Class " + mClassName); sb.Append(StringHelper.NewLine); break; case NetLanguage.CSharp: sb.Append(GetVisibility(lang, mVisibility) + GetSealed(lang) + "class " + mClassName); sb.Append(StringHelper.NewLine); sb.Append("{"); break; } sb.Append(StringHelper.NewLine); sb.Append(StringHelper.NewLine); foreach (FieldBuilder field in mFields) { sb.Append(field.GetFieldCode(lang)); sb.Append(StringHelper.NewLine); } sb.Append(StringHelper.NewLine); switch (lang) { case NetLanguage.VbNet: sb.Append("End Class"); break; case NetLanguage.CSharp: sb.Append("}"); break; } EndNamespace(lang, sb); return sb.ToString(); } private void ValidateClass() { if (ClassName.Trim().Length == 0) throw new FileHelpersException(Messages.Errors.EmptyClassName.Text); for (int i = 0; i < mFields.Count; i++) { if (((FieldBuilder) mFields[i]).FieldName.Trim().Length == 0) { throw new FileHelpersException(Messages.Errors.EmptyFieldName .Position((i + 1).ToString()) .Text); } if (((FieldBuilder) mFields[i]).FieldType.Trim().Length == 0) { throw new FileHelpersException(Messages.Errors.EmptyFieldType .Position((i + 1).ToString()) .Text); } } } /// <summary> /// Store the attributes for adding when we write the code to text /// </summary> /// <param name="attbs">Where attributes are stored</param> /// <param name="lang"></param> internal abstract void AddAttributesCode(AttributesBuilder attbs, NetLanguage lang); private void AddAttributesInternal(AttributesBuilder attbs) { if (mIgnoreFirstLines != 0) attbs.AddAttribute("IgnoreFirst(" + mIgnoreFirstLines.ToString() + ")"); if (mIgnoreLastLines != 0) attbs.AddAttribute("IgnoreLast(" + mIgnoreLastLines.ToString() + ")"); if (mIgnoreEmptyLines) attbs.AddAttribute("IgnoreEmptyLines()"); if (mRecordConditionInfo.Condition != FileHelpers.RecordCondition.None) { attbs.AddAttribute("ConditionalRecord(RecordCondition." + mRecordConditionInfo.Condition.ToString() + ", \"" + mRecordConditionInfo.Selector + "\")"); } if (!string.IsNullOrEmpty(mIgnoreCommentInfo.CommentMarker)) { attbs.AddAttribute("IgnoreCommentedLines(\"" + mIgnoreCommentInfo.CommentMarker + "\", " + mIgnoreCommentInfo.InAnyPlace.ToString().ToLower() + ")"); } } #region " EncDec " private static byte[] Encrypt(byte[] clearData, byte[] key, byte[] iv) { var ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Key = key; alg.IV = iv; var cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(clearData, 0, clearData.Length); cs.Close(); byte[] encryptedData = ms.ToArray(); return encryptedData; } private static string Encrypt(string clearText, string Password) { byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); var pdb = new PasswordDeriveBytes(Password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16)); return Convert.ToBase64String(encryptedData); } // Decrypt a byte array into a byte array using a key and an IV private static byte[] Decrypt(byte[] cipherData, byte[] key, byte[] iv) { var ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Key = key; alg.IV = iv; var cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(cipherData, 0, cipherData.Length); cs.Close(); var decryptedData = ms.ToArray(); return decryptedData; } private static string Decrypt(string cipherText, string password) { var cipherBytes = Convert.FromBase64String(cipherText); var pdb = new PasswordDeriveBytes(password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); var decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16)); return Encoding.Unicode.GetString(decryptedData); } #endregion [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string mCommentText = null; /// <summary>Comment text placed above the class definition</summary> public string CommentText { get { return mCommentText; } set { mCommentText = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private NetVisibility mVisibility = NetVisibility.Public; /// <summary>The Visibility for the class.</summary> public NetVisibility Visibility { get { return mVisibility; } set { mVisibility = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private bool mSealedClass = true; /// <summary>Indicates if the generated class must be sealed.</summary> public bool SealedClass { get { return mSealedClass; } set { mSealedClass = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string mNamespace = ""; /// <summary>The namespace used when creating the class.</summary> public string Namespace { get { return mNamespace; } set { mNamespace = value; } } /// <summary> /// Convert visibility type to word needed by the language /// </summary> /// <param name="lang">Language C# or Visual Basic</param> /// <param name="visibility">Public, internal, protected, etc</param> /// <returns>Visibility correct for the language</returns> internal static string GetVisibility(NetLanguage lang, NetVisibility visibility) { switch (lang) { case NetLanguage.CSharp: switch (visibility) { case NetVisibility.Public: return "public "; case NetVisibility.Private: return "private "; case NetVisibility.Internal: return "internal "; case NetVisibility.Protected: return "protected "; } break; case NetLanguage.VbNet: switch (visibility) { case NetVisibility.Public: return "Public "; case NetVisibility.Private: return "Private "; case NetVisibility.Internal: return "Friend "; case NetVisibility.Protected: return "Protected "; } break; } return ""; } /// <summary> /// Get the sealed prefix, if needed /// </summary> /// <param name="lang">Language we are writing in</param> /// <returns>nothing, sealed or NotInheritable</returns> private string GetSealed(NetLanguage lang) { if (mSealedClass == false) return ""; switch (lang) { case NetLanguage.CSharp: return "sealed "; case NetLanguage.VbNet: return "NotInheritable "; } return ""; } /// <summary> /// Add the namespace to the class details /// </summary> /// <param name="lang">Language type we are generating</param> /// <param name="sb">class text</param> private void BeginNamespace(NetLanguage lang, StringBuilder sb) { if (mNamespace == "") return; switch (lang) { case NetLanguage.CSharp: sb.Append("namespace "); sb.Append(mNamespace); sb.Append(StringHelper.NewLine); sb.Append("{"); break; case NetLanguage.VbNet: sb.Append("Namespace "); sb.Append(mNamespace); sb.Append(StringHelper.NewLine); break; } sb.Append(StringHelper.NewLine); } /// <summary> /// Add the end of namespace to text /// </summary> /// <param name="lang">language we are generating</param> /// <param name="sb">class text to add to</param> private void EndNamespace(NetLanguage lang, StringBuilder sb) { if (mNamespace == "") return; sb.Append(StringHelper.NewLine); switch (lang) { case NetLanguage.CSharp: sb.Append("}"); break; case NetLanguage.VbNet: sb.Append("End Namespace"); break; } } /// <summary> /// Loads the XML representation of a ClassBuilder inheritor and return /// it. (for XML saved with SaveToXml method) /// </summary> /// <remarks> /// ClassBuilder inheritors: <see cref="DelimitedClassBuilder"/> or <see cref="FixedLengthClassBuilder"/> /// </remarks> /// <param name="xml">The XML representation of the record class.</param> /// <returns>A new instance of a ClassBuilder inheritor: <see cref="DelimitedClassBuilder"/> or <see cref="FixedLengthClassBuilder"/> </returns> public static ClassBuilder LoadFromXmlString(string xml) { var document = new XmlDocument(); document.Load(new StringReader(xml)); return LoadFromXml(document); } /// <summary> /// Loads the XML representation of a ClassBuilder inheritor and return /// it. (for XML saved with SaveToXml method) /// </summary> /// <remarks> /// ClassBuilder inheritors: <see cref="DelimitedClassBuilder"/> or <see cref="FixedLengthClassBuilder"/> /// </remarks> /// <param name="document">The XML document with the representation of the record class.</param> /// <returns>A new instance of a ClassBuilder inheritor: <see cref="DelimitedClassBuilder"/> or <see cref="FixedLengthClassBuilder"/> </returns> public static ClassBuilder LoadFromXml(XmlDocument document) { ClassBuilder res = null; string classtype = document.DocumentElement.LocalName; if (classtype == "DelimitedClass") res = DelimitedClassBuilder.LoadXmlInternal(document); else res = FixedLengthClassBuilder.LoadXmlInternal(document); XmlNode node = document.DocumentElement["IgnoreLastLines"]; if (node != null) res.IgnoreLastLines = int.Parse(node.InnerText); node = document.DocumentElement["IgnoreFirstLines"]; if (node != null) res.IgnoreFirstLines = int.Parse(node.InnerText); node = document.DocumentElement["IgnoreEmptyLines"]; if (node != null) res.IgnoreEmptyLines = true; node = document.DocumentElement["CommentMarker"]; if (node != null) res.IgnoreCommentedLines.CommentMarker = node.InnerText; node = document.DocumentElement["CommentInAnyPlace"]; if (node != null) res.IgnoreCommentedLines.InAnyPlace = bool.Parse(node.InnerText.ToLower()); node = document.DocumentElement["SealedClass"]; res.SealedClass = node != null; node = document.DocumentElement["Namespace"]; if (node != null) res.Namespace = node.InnerText; node = document.DocumentElement["Visibility"]; if (node != null) res.Visibility = (NetVisibility) Enum.Parse(typeof (NetVisibility), node.InnerText); node = document.DocumentElement["RecordCondition"]; if (node != null) res.RecordCondition.Condition = (RecordCondition) Enum.Parse(typeof (RecordCondition), node.InnerText); node = document.DocumentElement["RecordConditionSelector"]; if (node != null) res.RecordCondition.Selector = node.InnerText; node = document.DocumentElement["CommentText"]; if (node != null) res.CommentText = node.InnerText; res.ReadClassElements(document); node = document.DocumentElement["Fields"]; XmlNodeList nodes; if (classtype == "DelimitedClass") nodes = node.SelectNodes("/DelimitedClass/Fields/Field"); else nodes = node.SelectNodes("/FixedLengthClass/Fields/Field"); foreach (XmlNode n in nodes) res.ReadField(n); return res; } /// <summary> /// Loads the XML representation of a ClassBuilder inheritor and return /// it. (for XML saved with SaveToXml method) /// </summary> /// <remarks> /// ClassBuilder inheritors: <see cref="DelimitedClassBuilder"/> or <see cref="FixedLengthClassBuilder"/> /// </remarks> /// <param name="filename">A file with the XML representation of the record class.</param> /// <returns>A new instance of a ClassBuilder inheritor: <see cref="DelimitedClassBuilder"/> or <see cref="FixedLengthClassBuilder"/> </returns> public static ClassBuilder LoadFromXml(string filename) { var document = new XmlDocument(); document.Load(filename); return LoadFromXml(document); } /// <summary> /// Creates the XML representation of the current record class. /// </summary> /// <returns> /// The representation of the current record class as xml string. /// </returns> public string SaveToXmlString() { var sb = new StringBuilder(); using (var writer = new StringWriter(sb)) SaveToXml(writer); return sb.ToString(); } /// <summary> /// Saves to a file the XML representation of the current record class. /// </summary> /// <param name="filename">A file name to write to.</param> public void SaveToXml(string filename) { using (var stream = new FileStream(filename, FileMode.Create)) SaveToXml(stream); } /// <summary> /// Saves to an Stream the XML representation of the current record class. /// </summary> /// <param name="stream">Stream to be written.</param> public void SaveToXml(Stream stream) { using (TextWriter writer = new StreamWriter(stream)) SaveToXml(writer); } /// <summary> /// Save to a TextWriter the XML representation of the current record class. /// </summary> /// <param name="writer">The TextWriter for the output Stream.</param> public void SaveToXml(TextWriter writer) { var xml = new XmlHelper(); xml.BeginWriteStream(writer); WriteHeaderElement(xml); xml.WriteElement("ClassName", ClassName); xml.WriteElement("Namespace", this.Namespace, ""); xml.WriteElement("SealedClass", this.SealedClass); xml.WriteElement("Visibility", this.Visibility.ToString(), "Public"); xml.WriteElement("IgnoreEmptyLines", this.IgnoreEmptyLines); xml.WriteElement("IgnoreFirstLines", this.IgnoreFirstLines.ToString(), "0"); xml.WriteElement("IgnoreLastLines", this.IgnoreLastLines.ToString(), "0"); xml.WriteElement("CommentMarker", this.IgnoreCommentedLines.CommentMarker, ""); xml.WriteElement("CommentInAnyPlace", this.IgnoreCommentedLines.InAnyPlace.ToString().ToLower(), true.ToString().ToLower()); xml.WriteElement("RecordCondition", this.RecordCondition.Condition.ToString(), "None"); xml.WriteElement("RecordConditionSelector", this.RecordCondition.Selector, ""); WriteExtraElements(xml); xml.Writer.WriteStartElement("Fields"); for (int i = 0; i < mFields.Count; i++) ((FieldBuilder) mFields[i]).SaveToXml(xml); xml.Writer.WriteEndElement(); xml.Writer.WriteEndElement(); xml.EndWrite(); } /// <summary> /// write header information for this class /// </summary> /// <param name="writer">writer to write on</param> internal abstract void WriteHeaderElement(XmlHelper writer); /// <summary> /// write any extra information for the class /// </summary> /// <param name="writer">writer to put xml on</param> internal abstract void WriteExtraElements(XmlHelper writer); /// <summary> /// read class elements from xml document /// </summary> /// <param name="document">document to read from</param> internal abstract void ReadClassElements(XmlDocument document); /// <summary> /// read attribute information for class /// </summary> /// <param name="node"></param> internal abstract void ReadField(XmlNode node); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly RecordConditionInfo mRecordConditionInfo = new RecordConditionInfo(); /// <summary>Allow to tell the engine what records must be included or excluded while reading.</summary> public RecordConditionInfo RecordCondition { get { return mRecordConditionInfo; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly IgnoreCommentInfo mIgnoreCommentInfo = new IgnoreCommentInfo(); /// <summary>Indicates that the engine must ignore the lines with this comment marker.</summary> public IgnoreCommentInfo IgnoreCommentedLines { get { return mIgnoreCommentInfo; } } /// <summary>Allow to tell the engine what records must be included or excluded while reading.</summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public sealed class RecordConditionInfo { internal RecordConditionInfo() {} private RecordCondition mRecordCondition = FileHelpers.RecordCondition.None; /// <summary>Allow to tell the engine what records must be included or excluded while reading.</summary> public RecordCondition Condition { get { return mRecordCondition; } set { mRecordCondition = value; } } private string mRecordConditionSelector = ""; /// <summary>The selector used by the <see cref="RecordCondition"/>.</summary> public string Selector { get { return mRecordConditionSelector; } set { mRecordConditionSelector = value; } } } /// <summary>Indicates that the engine must ignore the lines with this comment marker.</summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public sealed class IgnoreCommentInfo { internal IgnoreCommentInfo() {} /// <summary> /// <para>Indicates that the engine must ignore the lines with this /// comment marker.</para> /// <para>An empty string or null indicates that the engine does /// not look for comments</para> /// </summary> public string CommentMarker { get { return mMarker; } set { if (value != null) value = value.Trim(); mMarker = value; } } private string mMarker = ""; /// <summary>Indicates if the comment can have spaces or tabs at left (true by default)</summary> public bool InAnyPlace { get { return mInAnyPlace; } set { mInAnyPlace = value; } } private bool mInAnyPlace = true; } /// <summary> /// Break down a class into a generic or a full type name /// </summary> /// <param name="type">type to get type of</param> /// <returns>Type of the class as a string</returns> internal static string TypeToString(Type type) { if (type.IsGenericType) { var sb = new StringBuilder(); sb.Append(type.FullName.Substring(0, type.FullName.IndexOf("`", StringComparison.Ordinal))); sb.Append("<"); Type[] args = type.GetGenericArguments(); for (int i = 0; i < args.Length; i++) { if (i > 0) sb.Append(","); sb.Append(TypeToString(args[i])); } sb.Append(">"); return sb.ToString(); } else return type.FullName; } } }
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 BankingAppNew.Web.Areas.HelpPage.Models; namespace BankingAppNew.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified 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); } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Xml; using OpenGamingLibrary.Xunit.Extensions; using Xunit; using OpenGamingLibrary.Json; using System.IO; using OpenGamingLibrary.Json.Converters; using OpenGamingLibrary.Json.Utilities; namespace OpenGamingLibrary.Json.Test { public class JsonTextWriterTest : TestFixtureBase { [Fact] public void NewLine() { MemoryStream ms = new MemoryStream(); using (var streamWriter = new StreamWriter(ms, new UTF8Encoding(false)) { NewLine = "\n" }) using (var jsonWriter = new JsonTextWriter(streamWriter) { CloseOutput = true, Indentation = 2, Formatting = Formatting.Indented }) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("prop"); jsonWriter.WriteValue(true); jsonWriter.WriteEndObject(); } byte[] data = ms.ToArray(); string json = Encoding.UTF8.GetString(data, 0, data.Length); Assert.Equal(@"{" + '\n' + @" ""prop"": true" + '\n' + "}", json); } [Fact] public void QuoteNameAndStrings() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); JsonTextWriter writer = new JsonTextWriter(sw) { QuoteName = false }; writer.WriteStartObject(); writer.WritePropertyName("name"); writer.WriteValue("value"); writer.WriteEndObject(); writer.Flush(); Assert.Equal(@"{name:""value""}", sb.ToString()); } [Fact] public void CloseOutput() { MemoryStream ms = new MemoryStream(); JsonTextWriter writer = new JsonTextWriter(new StreamWriter(ms)); Assert.True(ms.CanRead); writer.Close(); Assert.False(ms.CanRead); ms = new MemoryStream(); writer = new JsonTextWriter(new StreamWriter(ms)) { CloseOutput = false }; Assert.True(ms.CanRead); writer.Close(); Assert.True(ms.CanRead); } #if !(PORTABLE || ASPNETCORE50 || NETFX_CORE) [Fact] public void WriteIConvertable() { var sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteValue(new ConvertibleInt(1)); Assert.Equal("1", sw.ToString()); } #endif [Fact] public void ValueFormatting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue('@'); jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'"); jsonWriter.WriteValue(true); jsonWriter.WriteValue(10); jsonWriter.WriteValue(10.99); jsonWriter.WriteValue(0.99); jsonWriter.WriteValue(0.000000000000000001d); jsonWriter.WriteValue(0.000000000000000001m); jsonWriter.WriteValue((string)null); jsonWriter.WriteValue((object)null); jsonWriter.WriteValue("This is a string."); jsonWriter.WriteNull(); jsonWriter.WriteUndefined(); jsonWriter.WriteEndArray(); } string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]"; string result = sb.ToString(); Console.WriteLine("ValueFormatting"); Console.WriteLine(result); Assert.Equal(expected, result); } [Fact] public void NullableValueFormatting() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue((char?)null); jsonWriter.WriteValue((char?)'c'); jsonWriter.WriteValue((bool?)null); jsonWriter.WriteValue((bool?)true); jsonWriter.WriteValue((byte?)null); jsonWriter.WriteValue((byte?)1); jsonWriter.WriteValue((sbyte?)null); jsonWriter.WriteValue((sbyte?)1); jsonWriter.WriteValue((short?)null); jsonWriter.WriteValue((short?)1); jsonWriter.WriteValue((ushort?)null); jsonWriter.WriteValue((ushort?)1); jsonWriter.WriteValue((int?)null); jsonWriter.WriteValue((int?)1); jsonWriter.WriteValue((uint?)null); jsonWriter.WriteValue((uint?)1); jsonWriter.WriteValue((long?)null); jsonWriter.WriteValue((long?)1); jsonWriter.WriteValue((ulong?)null); jsonWriter.WriteValue((ulong?)1); jsonWriter.WriteValue((double?)null); jsonWriter.WriteValue((double?)1.1); jsonWriter.WriteValue((float?)null); jsonWriter.WriteValue((float?)1.1); jsonWriter.WriteValue((decimal?)null); jsonWriter.WriteValue((decimal?)1.1m); jsonWriter.WriteValue((DateTime?)null); jsonWriter.WriteValue((DateTime?)new DateTime(DateTimeUtils.InitialJavaScriptDateTicks, DateTimeKind.Utc)); #if !NET20 jsonWriter.WriteValue((DateTimeOffset?)null); jsonWriter.WriteValue((DateTimeOffset?)new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, TimeSpan.Zero)); #endif jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected; #if !NET20 expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z"",null,""1970-01-01T00:00:00+00:00""]"; #else expected = @"[null,""c"",null,true,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1,null,1.1,null,1.1,null,1.1,null,""1970-01-01T00:00:00Z""]"; #endif Assert.Equal(expected, json); } [Fact] public void WriteValueObjectWithNullable() { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { char? value = 'c'; jsonWriter.WriteStartArray(); jsonWriter.WriteValue((object)value); jsonWriter.WriteEndArray(); } string json = sw.ToString(); string expected = @"[""c""]"; Assert.Equal(expected, json); } [Fact] public void WriteValueObjectWithUnsupportedValue() { AssertException.Throws<JsonWriterException>(() => { StringWriter sw = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(new Version(1, 1, 1, 1)); jsonWriter.WriteEndArray(); } }, @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation. Path ''."); } [Fact] public void StringEscaping() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(@"""These pretzels are making me thirsty!"""); jsonWriter.WriteValue("Jeff's house was burninated."); jsonWriter.WriteValue("1. You don't talk about fight club.\r\n2. You don't talk about fight club."); jsonWriter.WriteValue("35% of\t statistics\n are made\r up."); jsonWriter.WriteEndArray(); } string expected = @"[""\""These pretzels are making me thirsty!\"""",""Jeff's house was burninated."",""1. You don't talk about fight club.\r\n2. You don't talk about fight club."",""35% of\t statistics\n are made\r up.""]"; string result = sb.ToString(); Console.WriteLine("StringEscaping"); Console.WriteLine(result); Assert.Equal(expected, result); } [Fact] public void WriteEnd() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEndObject(); Assert.Equal(WriteState.Start, jsonWriter.WriteState); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.Equal(expected, result); } [Fact] public void CloseWithRemainingContent() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.Close(); } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.Equal(expected, result); } [Fact] public void Indenting() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("CPU"); jsonWriter.WriteValue("Intel"); jsonWriter.WritePropertyName("PSU"); jsonWriter.WriteValue("500W"); jsonWriter.WritePropertyName("Drives"); jsonWriter.WriteStartArray(); jsonWriter.WriteValue("DVD read/writer"); jsonWriter.WriteComment("(broken)"); jsonWriter.WriteValue("500 gigabyte hard drive"); jsonWriter.WriteValue("200 gigabype hard drive"); jsonWriter.WriteEnd(); jsonWriter.WriteEndObject(); Assert.Equal(WriteState.Start, jsonWriter.WriteState); } // { // "CPU": "Intel", // "PSU": "500W", // "Drives": [ // "DVD read/writer" // /*(broken)*/, // "500 gigabyte hard drive", // "200 gigabype hard drive" // ] // } string expected = @"{ ""CPU"": ""Intel"", ""PSU"": ""500W"", ""Drives"": [ ""DVD read/writer"" /*(broken)*/, ""500 gigabyte hard drive"", ""200 gigabype hard drive"" ] }"; string result = sb.ToString(); StringAssert.Equal(expected, result); } [Fact] public void State() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { Assert.Equal(WriteState.Start, jsonWriter.WriteState); jsonWriter.WriteStartObject(); Assert.Equal(WriteState.Object, jsonWriter.WriteState); Assert.Equal("", jsonWriter.Path); jsonWriter.WritePropertyName("CPU"); Assert.Equal(WriteState.Property, jsonWriter.WriteState); Assert.Equal("CPU", jsonWriter.Path); jsonWriter.WriteValue("Intel"); Assert.Equal(WriteState.Object, jsonWriter.WriteState); Assert.Equal("CPU", jsonWriter.Path); jsonWriter.WritePropertyName("Drives"); Assert.Equal(WriteState.Property, jsonWriter.WriteState); Assert.Equal("Drives", jsonWriter.Path); jsonWriter.WriteStartArray(); Assert.Equal(WriteState.Array, jsonWriter.WriteState); jsonWriter.WriteValue("DVD read/writer"); Assert.Equal(WriteState.Array, jsonWriter.WriteState); Assert.Equal("Drives[0]", jsonWriter.Path); jsonWriter.WriteEnd(); Assert.Equal(WriteState.Object, jsonWriter.WriteState); Assert.Equal("Drives", jsonWriter.Path); jsonWriter.WriteEndObject(); Assert.Equal(WriteState.Start, jsonWriter.WriteState); Assert.Equal("", jsonWriter.Path); } } [Fact] public void FloatingPointNonFiniteNumbers_Symbol() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ NaN, Infinity, -Infinity, NaN, Infinity, -Infinity ]"; string result = sb.ToString(); StringAssert.Equal(expected, result); } [Fact] public void FloatingPointNonFiniteNumbers_Zero() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.DefaultValue; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue((double?)double.NaN); jsonWriter.WriteValue((double?)double.PositiveInfinity); jsonWriter.WriteValue((double?)double.NegativeInfinity); jsonWriter.WriteValue((float?)float.NaN); jsonWriter.WriteValue((float?)float.PositiveInfinity); jsonWriter.WriteValue((float?)float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, null, null, null, null, null, null ]"; string result = sb.ToString(); StringAssert.Equal(expected, result); } [Fact] public void FloatingPointNonFiniteNumbers_String() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ ""NaN"", ""Infinity"", ""-Infinity"", ""NaN"", ""Infinity"", ""-Infinity"" ]"; string result = sb.ToString(); StringAssert.Equal(expected, result); } [Fact] public void FloatingPointNonFiniteNumbers_QuoteChar() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.String; jsonWriter.QuoteChar = '\''; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteEndArray(); jsonWriter.Flush(); } string expected = @"[ 'NaN', 'Infinity', '-Infinity', 'NaN', 'Infinity', '-Infinity' ]"; string result = sb.ToString(); StringAssert.Equal(expected, result); } [Fact] public void WriteRawInStart() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteRaw("[1,2,3,4,5]"); jsonWriter.WriteWhitespace(" "); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteEndArray(); } string expected = @"[1,2,3,4,5] [ NaN ]"; string result = sb.ToString(); StringAssert.Equal(expected, result); } [Fact] public void WriteRawInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteRaw(",[1,2,3,4,5]"); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } string expected = @"[ NaN,[1,2,3,4,5],[1,2,3,4,5], NaN ]"; string result = sb.ToString(); StringAssert.Equal(expected, result); } [Fact] public void WriteRawInObject() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.WriteStartObject(); jsonWriter.WriteRaw(@"""PropertyName"":[1,2,3,4,5]"); jsonWriter.WriteEnd(); } string expected = @"{""PropertyName"":[1,2,3,4,5]}"; string result = sb.ToString(); Assert.Equal(expected, result); } [Fact] public void WriteToken() { JsonTextReader reader = new JsonTextReader(new StringReader("[1,2,3,4,5]")); reader.Read(); reader.Read(); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteToken(reader); Assert.Equal("1", sw.ToString()); } [Fact] public void WriteRawValue() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { int i = 0; string rawJson = "[1,2]"; jsonWriter.WriteStartObject(); while (i < 3) { jsonWriter.WritePropertyName("d" + i); jsonWriter.WriteRawValue(rawJson); i++; } jsonWriter.WriteEndObject(); } Assert.Equal(@"{""d0"":[1,2],""d1"":[1,2],""d2"":[1,2]}", sb.ToString()); } [Fact] public void WriteObjectNestedInConstructor() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("con"); jsonWriter.WriteStartConstructor("Ext.data.JsonStore"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("aa"); jsonWriter.WriteValue("aa"); jsonWriter.WriteEndObject(); jsonWriter.WriteEndConstructor(); jsonWriter.WriteEndObject(); } Assert.Equal(@"{""con"":new Ext.data.JsonStore({""aa"":""aa""})}", sb.ToString()); } [Fact] public void WriteFloatingPointNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteValue(0f); jsonWriter.WriteValue(0.1); jsonWriter.WriteValue(1.0); jsonWriter.WriteValue(1.000001); jsonWriter.WriteValue(0.000001); jsonWriter.WriteValue(double.Epsilon); jsonWriter.WriteValue(double.PositiveInfinity); jsonWriter.WriteValue(double.NegativeInfinity); jsonWriter.WriteValue(double.NaN); jsonWriter.WriteValue(double.MaxValue); jsonWriter.WriteValue(double.MinValue); jsonWriter.WriteValue(float.PositiveInfinity); jsonWriter.WriteValue(float.NegativeInfinity); jsonWriter.WriteValue(float.NaN); jsonWriter.WriteEndArray(); } Assert.Equal(@"[0.0,0.0,0.1,1.0,1.000001,1E-06,4.94065645841247E-324,Infinity,-Infinity,NaN,1.7976931348623157E+308,-1.7976931348623157E+308,Infinity,-Infinity,NaN]", sb.ToString()); } [Fact] public void WriteIntegerNumber() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented }) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(int.MaxValue); jsonWriter.WriteValue(int.MinValue); jsonWriter.WriteValue(0); jsonWriter.WriteValue(-0); jsonWriter.WriteValue(9L); jsonWriter.WriteValue(9UL); jsonWriter.WriteValue(long.MaxValue); jsonWriter.WriteValue(long.MinValue); jsonWriter.WriteValue(ulong.MaxValue); jsonWriter.WriteValue(ulong.MinValue); jsonWriter.WriteEndArray(); } Console.WriteLine(sb.ToString()); StringAssert.Equal(@"[ 2147483647, -2147483648, 0, 0, 9, 9, 9223372036854775807, -9223372036854775808, 18446744073709551615, 0 ]", sb.ToString()); } [Fact] public void BadWriteEndArray() { AssertException.Throws<JsonWriterException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.WriteStartArray(); jsonWriter.WriteValue(0.0); jsonWriter.WriteEndArray(); jsonWriter.WriteEndArray(); } }, "No token to close. Path ''."); } [Fact] public void InvalidQuoteChar() { AssertException.Throws<ArgumentException>(() => { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.QuoteChar = '*'; } }, @"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); } [Fact] public void Indentation() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; jsonWriter.FloatFormatHandling = FloatFormatHandling.Symbol; Assert.Equal(Formatting.Indented, jsonWriter.Formatting); jsonWriter.Indentation = 5; Assert.Equal(5, jsonWriter.Indentation); jsonWriter.IndentChar = '_'; Assert.Equal('_', jsonWriter.IndentChar); jsonWriter.QuoteName = true; Assert.Equal(true, jsonWriter.QuoteName); jsonWriter.QuoteChar = '\''; Assert.Equal('\'', jsonWriter.QuoteChar); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("propertyName"); jsonWriter.WriteValue(double.NaN); jsonWriter.IndentChar = '?'; Assert.Equal('?', jsonWriter.IndentChar); jsonWriter.Indentation = 6; Assert.Equal(6, jsonWriter.Indentation); jsonWriter.WritePropertyName("prop2"); jsonWriter.WriteValue(123); jsonWriter.WriteEndObject(); } string expected = @"{ _____'propertyName': NaN, ??????'prop2': 123 }"; string result = sb.ToString(); StringAssert.Equal(expected, result); } [Fact] public void WriteSingleBytes() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.Equal(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteValue(data); } string expected = @"""SGVsbG8gd29ybGQu"""; string result = sb.ToString(); Assert.Equal(expected, result); byte[] d2 = Convert.FromBase64String(result.Trim('"')); Assert.Equal(text, Encoding.UTF8.GetString(d2, 0, d2.Length)); } [Fact] public void WriteBytesInArray() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; Assert.Equal(Formatting.Indented, jsonWriter.Formatting); jsonWriter.WriteStartArray(); jsonWriter.WriteValue(data); jsonWriter.WriteValue(data); jsonWriter.WriteValue((object)data); jsonWriter.WriteValue((byte[])null); jsonWriter.WriteValue((Uri)null); jsonWriter.WriteEndArray(); } string expected = @"[ ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", ""SGVsbG8gd29ybGQu"", null, null ]"; string result = sb.ToString(); StringAssert.Equal(expected, result); } [Fact] public void Path() { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); string text = "Hello world."; byte[] data = Encoding.UTF8.GetBytes(text); using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartArray(); Assert.Equal("", writer.Path); writer.WriteStartObject(); Assert.Equal("[0]", writer.Path); writer.WritePropertyName("Property1"); Assert.Equal("[0].Property1", writer.Path); writer.WriteStartArray(); Assert.Equal("[0].Property1", writer.Path); writer.WriteValue(1); Assert.Equal("[0].Property1[0]", writer.Path); writer.WriteStartArray(); Assert.Equal("[0].Property1[1]", writer.Path); writer.WriteStartArray(); Assert.Equal("[0].Property1[1][0]", writer.Path); writer.WriteStartArray(); Assert.Equal("[0].Property1[1][0][0]", writer.Path); writer.WriteEndObject(); Assert.Equal("[0]", writer.Path); writer.WriteStartObject(); Assert.Equal("[1]", writer.Path); writer.WritePropertyName("Property2"); Assert.Equal("[1].Property2", writer.Path); writer.WriteStartConstructor("Constructor1"); Assert.Equal("[1].Property2", writer.Path); writer.WriteNull(); Assert.Equal("[1].Property2[0]", writer.Path); writer.WriteStartArray(); Assert.Equal("[1].Property2[1]", writer.Path); writer.WriteValue(1); Assert.Equal("[1].Property2[1][0]", writer.Path); writer.WriteEnd(); Assert.Equal("[1].Property2[1]", writer.Path); writer.WriteEndObject(); Assert.Equal("[1]", writer.Path); writer.WriteEndArray(); Assert.Equal("", writer.Path); } StringAssert.Equal(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]", sb.ToString()); } [Fact] public void BuildStateArray() { JsonWriter.State[][] stateArray = JsonWriter.BuildStateArray(); var valueStates = JsonWriter.StateArrayTempate[7]; foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken))) { switch (valueToken) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: Assert.Equal(valueStates, stateArray[(int)valueToken]); break; } } } [Fact] public void DateTimeZoneHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { DateTimeZoneHandling = Json.DateTimeZoneHandling.Utc }; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified)); Assert.Equal(@"""2000-01-01T01:01:01Z""", sw.ToString()); } [Fact] public void HtmlStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeHtml }; string script = @"<script type=""text/javascript"">alert('hi');</script>"; writer.WriteValue(script); string json = sw.ToString(); Assert.Equal(@"""\u003cscript type=\u0022text/javascript\u0022\u003ealert(\u0027hi\u0027);\u003c/script\u003e""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.Equal(script, reader.ReadAsString()); //Console.WriteLine(HttpUtility.HtmlEncode(script)); //System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer(); //Console.WriteLine(s.Serialize(new { html = script })); } [Fact] public void NonAsciiStringEscapeHandling() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii }; string unicode = "\u5f20"; writer.WriteValue(unicode); string json = sw.ToString(); Assert.Equal(8, json.Length); Assert.Equal(@"""\u5f20""", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); Assert.Equal(unicode, reader.ReadAsString()); sw = new StringWriter(); writer = new JsonTextWriter(sw) { StringEscapeHandling = StringEscapeHandling.Default }; writer.WriteValue(unicode); json = sw.ToString(); Assert.Equal(3, json.Length); Assert.Equal("\"\u5f20\"", json); } [Fact] public void WriteEndOnProperty() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.QuoteChar = '\''; writer.WriteStartObject(); writer.WritePropertyName("Blah"); writer.WriteEnd(); Assert.Equal("{'Blah':null}", sw.ToString()); } #if !NET20 [Fact] public void QuoteChar() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.DateFormatString = "yyyy gg"; writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteValue(new byte[] { 1, 2, 3 }); writer.WriteValue(TimeSpan.Zero); writer.WriteValue(new Uri("http://www.google.com/")); writer.WriteValue(Guid.Empty); writer.WriteEnd(); StringAssert.Equal(@"[ '2000-01-01T01:01:01Z', '2000-01-01T01:01:01+00:00', '\/Date(946688461000)\/', '\/Date(946688461000+0000)\/', '2000 A.D.', '2000 A.D.', 'AQID', '00:00:00', 'http://www.google.com/', '00000000-0000-0000-0000-000000000000' ]", sw.ToString()); } [Fact] public void Culture() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.DateFormatString = "yyyy tt"; writer.Culture = new CultureInfo("en-NZ"); writer.QuoteChar = '\''; writer.WriteStartArray(); writer.WriteValue(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc)); writer.WriteValue(new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero)); writer.WriteEnd(); StringAssert.Equal(@"[ '2000 a.m.', '2000 a.m.' ]", sw.ToString()); } #endif [Fact] public void CompareNewStringEscapingWithOld() { Console.WriteLine("Started"); char c = (char)0; do { if (c % 1000 == 0) Console.WriteLine("Position: " + (int)c); StringWriter swNew = new StringWriter(); char[] buffer = null; JavaScriptUtils.WriteEscapedJavaScriptString(swNew, c.ToString(), '"', true, JavaScriptUtils.DoubleQuoteCharEscapeFlags, StringEscapeHandling.Default, ref buffer); StringWriter swOld = new StringWriter(); WriteEscapedJavaScriptStringOld(swOld, c.ToString(), '"', true); string newText = swNew.ToString(); string oldText = swOld.ToString(); if (newText != oldText) throw new Exception("Difference for char '{0}' (value {1}). Old text: {2}, New text: {3}".FormatWith(CultureInfo.InvariantCulture, c, (int)c, oldText, newText)); c++; } while (c != char.MaxValue); Console.WriteLine("Finished"); } private const string EscapedUnicodeText = "!"; private static void WriteEscapedJavaScriptStringOld(TextWriter writer, string s, char delimiter, bool appendDelimiters) { // leading delimiter if (appendDelimiters) writer.Write(delimiter); if (s != null) { char[] chars = null; char[] unicodeBuffer = null; int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\' && c != delimiter) continue; string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; case '\'': // this charater is being used as the delimiter escapedValue = @"\'"; break; case '"': // this charater is being used as the delimiter escapedValue = "\\\""; break; default: if (c <= '\u001f') { if (unicodeBuffer == null) unicodeBuffer = new char[6]; StringUtils.ToCharAsUnicode(c, unicodeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } else { escapedValue = null; } break; } if (escapedValue == null) continue; if (i > lastWritePosition) { if (chars == null) chars = s.ToCharArray(); // write unchanged chars before writing escaped text writer.Write(chars, lastWritePosition, i - lastWritePosition); } lastWritePosition = i + 1; if (!string.Equals(escapedValue, EscapedUnicodeText)) writer.Write(escapedValue); else writer.Write(unicodeBuffer); } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { if (chars == null) chars = s.ToCharArray(); // write remaining text writer.Write(chars, lastWritePosition, s.Length - lastWritePosition); } } // trailing delimiter if (appendDelimiters) writer.Write(delimiter); } [Fact] public void CustomJsonTextWriterTests() { StringWriter sw = new StringWriter(); CustomJsonTextWriter writer = new CustomJsonTextWriter(sw) { Formatting = Formatting.Indented }; writer.WriteStartObject(); Assert.Equal(WriteState.Object, writer.WriteState); writer.WritePropertyName("Property1"); Assert.Equal(WriteState.Property, writer.WriteState); Assert.Equal("Property1", writer.Path); writer.WriteNull(); Assert.Equal(WriteState.Object, writer.WriteState); writer.WriteEndObject(); Assert.Equal(WriteState.Start, writer.WriteState); StringAssert.Equal(@"{{{ ""1ytreporP"": NULL!!! }}}", sw.ToString()); } [Fact] public void QuoteDictionaryNames() { var d = new Dictionary<string, int> { { "a", 1 }, }; var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, }; var serializer = JsonSerializer.Create(jsonSerializerSettings); using (var stringWriter = new StringWriter()) { using (var writer = new JsonTextWriter(stringWriter) { QuoteName = false }) { serializer.Serialize(writer, d); writer.Close(); } StringAssert.Equal(@"{ a: 1 }", stringWriter.ToString()); } } [Fact] public void WriteComments() { string json = @"//comment*//*hi*/ {//comment Name://comment true//comment after true" + StringUtils.CarriageReturn + @" ,//comment after comma" + StringUtils.CarriageReturnLineFeed + @" ""ExpiryDate""://comment" + StringUtils.LineFeed + @" new " + StringUtils.LineFeed + @"Constructor (//comment null//comment ), ""Price"": 3.99, ""Sizes"": //comment [//comment ""Small""//comment ]//comment }//comment //comment 1 "; JsonTextReader r = new JsonTextReader(new StringReader(json)); StringWriter sw = new StringWriter(); JsonTextWriter w = new JsonTextWriter(sw); w.Formatting = Formatting.Indented; w.WriteToken(r, true); StringAssert.Equal(@"/*comment*//*hi*/*/{/*comment*/ ""Name"": /*comment*/ true/*comment after true*//*comment after comma*/, ""ExpiryDate"": /*comment*/ new Constructor( /*comment*/, null /*comment*/ ), ""Price"": 3.99, ""Sizes"": /*comment*/ [ /*comment*/ ""Small"" /*comment*/ ]/*comment*/ }/*comment *//*comment 1 */", sw.ToString()); } } public class CustomJsonTextWriter : JsonTextWriter { private readonly TextWriter _writer; public CustomJsonTextWriter(TextWriter textWriter) : base(textWriter) { _writer = textWriter; } public override void WritePropertyName(string name) { WritePropertyName(name, true); } public override void WritePropertyName(string name, bool escape) { SetWriteState(JsonToken.PropertyName, name); if (QuoteName) _writer.Write(QuoteChar); _writer.Write(new string(name.ToCharArray().Reverse().ToArray())); if (QuoteName) _writer.Write(QuoteChar); _writer.Write(':'); } public override void WriteNull() { SetWriteState(JsonToken.Null, null); _writer.Write("NULL!!!"); } public override void WriteStartObject() { SetWriteState(JsonToken.StartObject, null); _writer.Write("{{{"); } public override void WriteEndObject() { SetWriteState(JsonToken.EndObject, null); } protected override void WriteEnd(JsonToken token) { if (token == JsonToken.EndObject) _writer.Write("}}}"); else base.WriteEnd(token); } } #if !(PORTABLE || ASPNETCORE50 || NETFX_CORE) public struct ConvertibleInt : IConvertible { private readonly int _value; public ConvertibleInt(int value) { _value = value; } public TypeCode GetTypeCode() { return TypeCode.Int32; } public bool ToBoolean(IFormatProvider provider) { throw new NotImplementedException(); } public byte ToByte(IFormatProvider provider) { throw new NotImplementedException(); } public char ToChar(IFormatProvider provider) { throw new NotImplementedException(); } public DateTime ToDateTime(IFormatProvider provider) { throw new NotImplementedException(); } public decimal ToDecimal(IFormatProvider provider) { throw new NotImplementedException(); } public double ToDouble(IFormatProvider provider) { throw new NotImplementedException(); } public short ToInt16(IFormatProvider provider) { throw new NotImplementedException(); } public int ToInt32(IFormatProvider provider) { throw new NotImplementedException(); } public long ToInt64(IFormatProvider provider) { throw new NotImplementedException(); } public sbyte ToSByte(IFormatProvider provider) { throw new NotImplementedException(); } public float ToSingle(IFormatProvider provider) { throw new NotImplementedException(); } public string ToString(IFormatProvider provider) { throw new NotImplementedException(); } public object ToType(Type conversionType, IFormatProvider provider) { if (conversionType == typeof(int)) return _value; throw new Exception("Type not supported: " + conversionType.FullName); } public ushort ToUInt16(IFormatProvider provider) { throw new NotImplementedException(); } public uint ToUInt32(IFormatProvider provider) { throw new NotImplementedException(); } public ulong ToUInt64(IFormatProvider provider) { throw new NotImplementedException(); } } #endif }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Text; using System; using System.Diagnostics.Contracts; namespace System.Text { // An Encoder is used to encode a sequence of blocks of characters into // a sequence of blocks of bytes. Following instantiation of an encoder, // sequential blocks of characters are converted into blocks of bytes through // calls to the GetBytes method. The encoder maintains state between the // conversions, allowing it to correctly encode character sequences that span // adjacent blocks. // // Instances of specific implementations of the Encoder abstract base // class are typically obtained through calls to the GetEncoder method // of Encoding objects. // internal class EncoderNLS : Encoder { // Need a place for the last left over character, most of our encodings use this internal char charLeftOver; protected EncodingNLS m_encoding; protected bool m_mustFlush; internal bool m_throwOnOverflow; internal int m_charsUsed; internal EncoderFallback m_fallback; internal EncoderFallbackBuffer m_fallbackBuffer; internal EncoderNLS(EncodingNLS encoding) { m_encoding = encoding; m_fallback = m_encoding.EncoderFallback; Reset(); } internal new EncoderFallback Fallback { get { return m_fallback; } } internal bool InternalHasFallbackBuffer { get { return m_fallbackBuffer != null; } } public new EncoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { if (m_fallback != null) m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); else m_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return m_fallbackBuffer; } } // This one is used when deserializing (like UTF7Encoding.Encoder) internal EncoderNLS() { m_encoding = null; Reset(); } public override void Reset() { charLeftOver = (char)0; if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid empty input problem if (chars.Length == 0) chars = new char[1]; // Just call the pointer version int result = -1; fixed (char* pChars = chars) { result = GetByteCount(pChars + index, count, flush); } return result; } [System.Security.SecurityCritical] // auto-generated public unsafe int GetByteCount(char* chars, int count, bool flush) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetByteCount(chars, count, this); } [System.Security.SecuritySafeCritical] // auto-generated public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); if (chars.Length == 0) chars = new char[1]; int byteCount = bytes.Length - byteIndex; if (bytes.Length == 0) bytes = new byte[1]; // Just call pointer version fixed (char* pChars = chars) fixed (byte* pBytes = bytes) // Remember that charCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush); } [System.Security.SecurityCritical] // auto-generated public unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? "byteCount" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); m_mustFlush = flush; m_throwOnOverflow = true; return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); } // This method is used when your output buffer might not be large enough for the entire result. // Just call the pointer version. (This gets bytes) [System.Security.SecuritySafeCritical] // auto-generated public override unsafe void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); Contract.EndContractBlock(); // Avoid empty input problem if (chars.Length == 0) chars = new char[1]; if (bytes.Length == 0) bytes = new byte[1]; // Just call the pointer version (can't do this for non-msft encoders) fixed (char* pChars = chars) { fixed (byte* pBytes = bytes) { Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); } } } // This is the version that uses pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting bytes [System.Security.SecurityCritical] // auto-generated public unsafe void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { // Validate input parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); // We don't want to throw m_mustFlush = flush; m_throwOnOverflow = false; m_charsUsed = 0; // Do conversion bytesUsed = m_encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = m_charsUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (charsUsed == charCount) && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); // Our data thingies are now full, we can return } public Encoding Encoding { get { return m_encoding; } } public bool MustFlush { get { return m_mustFlush; } } // Anything left in our encoder? internal virtual bool HasState { get { return (charLeftOver != (char)0); } } // Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow) internal void ClearMustFlush() { m_mustFlush = false; } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using Common.Logging; using Quartz.Core; using Quartz.Simpl; using Quartz.Spi; namespace Quartz.Impl { /// <summary> /// A singleton implementation of <see cref="ISchedulerFactory" />. /// </summary> /// <remarks> /// Here are some examples of using this class: /// <para> /// To create a scheduler that does not write anything to the database (is not /// persistent), you can call <see cref="CreateVolatileScheduler" />: /// </para> /// <code> /// DirectSchedulerFactory.Instance.CreateVolatileScheduler(10); // 10 threads /// // don't forget to start the scheduler: /// DirectSchedulerFactory.Instance.GetScheduler().Start(); /// </code> /// <para> /// Several create methods are provided for convenience. All create methods /// eventually end up calling the create method with all the parameters: /// </para> /// <code> /// public void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool, IJobStore jobStore) /// </code> /// <para> /// Here is an example of using this method: /// </para> /// <code> /// // create the thread pool /// SimpleThreadPool threadPool = new SimpleThreadPool(maxThreads, ThreadPriority.Normal); /// threadPool.Initialize(); /// // create the job store /// JobStore jobStore = new RAMJobStore(); /// /// DirectSchedulerFactory.Instance.CreateScheduler("My Quartz Scheduler", "My Instance", threadPool, jobStore); /// // don't forget to start the scheduler: /// DirectSchedulerFactory.Instance.GetScheduler("My Quartz Scheduler", "My Instance").Start(); /// </code> /// </remarks>> /// <author>Mohammad Rezaei</author> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> /// <seealso cref="IJobStore" /> /// <seealso cref="ThreadPool" /> public class DirectSchedulerFactory : ISchedulerFactory { private readonly ILog log; public const string DefaultInstanceId = "SIMPLE_NON_CLUSTERED"; public const string DefaultSchedulerName = "SimpleQuartzScheduler"; private static readonly DefaultThreadExecutor DefaultThreadExecutor = new DefaultThreadExecutor(); private const int DefaultBatchMaxSize = 1; private readonly TimeSpan DefaultBatchTimeWindow = TimeSpan.Zero; private bool initialized; private static readonly DirectSchedulerFactory instance = new DirectSchedulerFactory(); /// <summary> /// Gets the log. /// </summary> /// <value>The log.</value> public ILog Log { get { return log; } } /// <summary> /// Gets the instance. /// </summary> /// <value>The instance.</value> public static DirectSchedulerFactory Instance { get { return instance; } } /// <summary> <para> /// Returns a handle to all known Schedulers (made by any /// StdSchedulerFactory instance.). /// </para> /// </summary> public virtual ICollection<IScheduler> AllSchedulers { get { return SchedulerRepository.Instance.LookupAll(); } } /// <summary> /// Initializes a new instance of the <see cref="DirectSchedulerFactory"/> class. /// </summary> protected DirectSchedulerFactory() { log = LogManager.GetLogger(GetType()); } /// <summary> /// Creates an in memory job store (<see cref="RAMJobStore" />) /// The thread priority is set to Thread.NORM_PRIORITY /// </summary> /// <param name="maxThreads">The number of threads in the thread pool</param> public virtual void CreateVolatileScheduler(int maxThreads) { SimpleThreadPool threadPool = new SimpleThreadPool(maxThreads, ThreadPriority.Normal); threadPool.Initialize(); IJobStore jobStore = new RAMJobStore(); CreateScheduler(threadPool, jobStore); } /// <summary> /// Creates a proxy to a remote scheduler. This scheduler can be retrieved /// via <see cref="DirectSchedulerFactory.GetScheduler()" />. /// </summary> /// <throws> SchedulerException </throws> public virtual void CreateRemoteScheduler(string proxyAddress) { CreateRemoteScheduler(DefaultSchedulerName, DefaultInstanceId, proxyAddress); } /// <summary> /// Same as <see cref="DirectSchedulerFactory.CreateRemoteScheduler(string)" />, /// with the addition of specifying the scheduler name and instance ID. This /// scheduler can only be retrieved via <see cref="DirectSchedulerFactory.GetScheduler(string)" />. /// </summary> /// <param name="schedulerName">The name for the scheduler.</param> /// <param name="schedulerInstanceId">The instance ID for the scheduler.</param> /// <param name="proxyAddress"></param> /// <throws> SchedulerException </throws> protected virtual void CreateRemoteScheduler(string schedulerName, string schedulerInstanceId, string proxyAddress) { string uid = QuartzSchedulerResources.GetUniqueIdentifier(schedulerName, schedulerInstanceId); var proxyBuilder = new RemotingSchedulerProxyFactory(); proxyBuilder.Address = proxyAddress; RemoteScheduler remoteScheduler = new RemoteScheduler(uid, proxyBuilder); SchedulerRepository schedRep = SchedulerRepository.Instance; schedRep.Bind(remoteScheduler); initialized = true; } /// <summary> /// Creates a scheduler using the specified thread pool and job store. This /// scheduler can be retrieved via DirectSchedulerFactory#GetScheduler() /// </summary> /// <param name="threadPool"> /// The thread pool for executing jobs /// </param> /// <param name="jobStore"> /// The type of job store /// </param> /// <throws> SchedulerException </throws> /// <summary> if initialization failed /// </summary> public virtual void CreateScheduler(IThreadPool threadPool, IJobStore jobStore) { CreateScheduler(DefaultSchedulerName, DefaultInstanceId, threadPool, jobStore); initialized = true; } /// <summary> /// Same as DirectSchedulerFactory#createScheduler(ThreadPool threadPool, JobStore jobStore), /// with the addition of specifying the scheduler name and instance ID. This /// scheduler can only be retrieved via DirectSchedulerFactory#getScheduler(String) /// </summary> /// <param name="schedulerName">The name for the scheduler.</param> /// <param name="schedulerInstanceId">The instance ID for the scheduler.</param> /// <param name="threadPool">The thread pool for executing jobs</param> /// <param name="jobStore">The type of job store</param> public virtual void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool, IJobStore jobStore) { CreateScheduler(schedulerName, schedulerInstanceId, threadPool, jobStore, TimeSpan.Zero, TimeSpan.Zero); } /// <summary> /// Creates a scheduler using the specified thread pool and job store and /// binds it for remote access. /// </summary> /// <param name="schedulerName">The name for the scheduler.</param> /// <param name="schedulerInstanceId">The instance ID for the scheduler.</param> /// <param name="threadPool">The thread pool for executing jobs</param> /// <param name="jobStore">The type of job store</param> /// <param name="idleWaitTime">The idle wait time. You can specify "-1" for /// the default value, which is currently 30000 ms.</param> /// <param name="dbFailureRetryInterval">The db failure retry interval.</param> public virtual void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool, IJobStore jobStore, TimeSpan idleWaitTime, TimeSpan dbFailureRetryInterval) { CreateScheduler(schedulerName, schedulerInstanceId, threadPool, jobStore, null, idleWaitTime, dbFailureRetryInterval); } /// <summary> /// Creates a scheduler using the specified thread pool and job store and /// binds it for remote access. /// </summary> /// <param name="schedulerName">The name for the scheduler.</param> /// <param name="schedulerInstanceId">The instance ID for the scheduler.</param> /// <param name="threadPool">The thread pool for executing jobs</param> /// <param name="jobStore">The type of job store</param> /// <param name="schedulerPluginMap"></param> /// <param name="idleWaitTime">The idle wait time. You can specify TimeSpan.Zero for /// the default value, which is currently 30000 ms.</param> /// <param name="dbFailureRetryInterval">The db failure retry interval.</param> public virtual void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool, IJobStore jobStore, IDictionary<string, ISchedulerPlugin> schedulerPluginMap, TimeSpan idleWaitTime, TimeSpan dbFailureRetryInterval) { CreateScheduler( schedulerName, schedulerInstanceId, threadPool, DefaultThreadExecutor, jobStore, schedulerPluginMap, idleWaitTime, dbFailureRetryInterval); } /// <summary> /// Creates a scheduler using the specified thread pool and job store and /// binds it for remote access. /// </summary> /// <param name="schedulerName">The name for the scheduler.</param> /// <param name="schedulerInstanceId">The instance ID for the scheduler.</param> /// <param name="threadPool">The thread pool for executing jobs</param> /// <param name="threadExecutor">Thread executor.</param> /// <param name="jobStore">The type of job store</param> /// <param name="schedulerPluginMap"></param> /// <param name="idleWaitTime">The idle wait time. You can specify TimeSpan.Zero for /// the default value, which is currently 30000 ms.</param> /// <param name="dbFailureRetryInterval">The db failure retry interval.</param> public virtual void CreateScheduler(string schedulerName, string schedulerInstanceId, IThreadPool threadPool, IThreadExecutor threadExecutor, IJobStore jobStore, IDictionary<string, ISchedulerPlugin> schedulerPluginMap, TimeSpan idleWaitTime, TimeSpan dbFailureRetryInterval) { CreateScheduler(schedulerName, schedulerInstanceId, threadPool, threadExecutor, jobStore, schedulerPluginMap, idleWaitTime, DefaultBatchMaxSize, DefaultBatchTimeWindow); } /// <summary> /// Creates a scheduler using the specified thread pool and job store and /// binds it for remote access. /// </summary> /// <param name="schedulerName">The name for the scheduler.</param> /// <param name="schedulerInstanceId">The instance ID for the scheduler.</param> /// <param name="threadPool">The thread pool for executing jobs</param> /// <param name="threadExecutor">Thread executor.</param> /// <param name="jobStore">The type of job store</param> /// <param name="schedulerPluginMap"></param> /// <param name="idleWaitTime">The idle wait time. You can specify TimeSpan.Zero for /// the default value, which is currently 30000 ms.</param> /// <param name="maxBatchSize">The maximum batch size of triggers, when acquiring them</param> /// <param name="batchTimeWindow">The time window for which it is allowed to "pre-acquire" triggers to fire</param> public virtual void CreateScheduler( string schedulerName, string schedulerInstanceId, IThreadPool threadPool, IThreadExecutor threadExecutor, IJobStore jobStore, IDictionary<string, ISchedulerPlugin> schedulerPluginMap, TimeSpan idleWaitTime, int maxBatchSize, TimeSpan batchTimeWindow) { CreateScheduler(schedulerName, schedulerInstanceId, threadPool, threadExecutor, jobStore, schedulerPluginMap, idleWaitTime, maxBatchSize, batchTimeWindow, null); } /// <summary> /// Creates a scheduler using the specified thread pool and job store and /// binds it for remote access. /// </summary> /// <param name="schedulerName">The name for the scheduler.</param> /// <param name="schedulerInstanceId">The instance ID for the scheduler.</param> /// <param name="threadPool">The thread pool for executing jobs</param> /// <param name="threadExecutor">Thread executor.</param> /// <param name="jobStore">The type of job store</param> /// <param name="schedulerPluginMap"></param> /// <param name="idleWaitTime">The idle wait time. You can specify TimeSpan.Zero for /// the default value, which is currently 30000 ms.</param> /// <param name="maxBatchSize">The maximum batch size of triggers, when acquiring them</param> /// <param name="batchTimeWindow">The time window for which it is allowed to "pre-acquire" triggers to fire</param> /// <param name="schedulerExporter">The scheduler exporter to use</param> public virtual void CreateScheduler( string schedulerName, string schedulerInstanceId, IThreadPool threadPool, IThreadExecutor threadExecutor, IJobStore jobStore, IDictionary<string, ISchedulerPlugin> schedulerPluginMap, TimeSpan idleWaitTime, int maxBatchSize, TimeSpan batchTimeWindow, ISchedulerExporter schedulerExporter) { // Currently only one run-shell factory is available... IJobRunShellFactory jrsf = new StdJobRunShellFactory(); // Fire everything u // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ threadPool.Initialize(); QuartzSchedulerResources qrs = new QuartzSchedulerResources(); qrs.Name = schedulerName; qrs.InstanceId = schedulerInstanceId; SchedulerDetailsSetter.SetDetails(threadPool, schedulerName, schedulerInstanceId); qrs.JobRunShellFactory = jrsf; qrs.ThreadPool = threadPool; qrs.ThreadExecutor= threadExecutor; qrs.JobStore = jobStore; qrs.MaxBatchSize = maxBatchSize; qrs.BatchTimeWindow = batchTimeWindow; qrs.SchedulerExporter = schedulerExporter; // add plugins if (schedulerPluginMap != null) { foreach (ISchedulerPlugin plugin in schedulerPluginMap.Values) { qrs.AddSchedulerPlugin(plugin); } } QuartzScheduler qs = new QuartzScheduler(qrs, idleWaitTime); ITypeLoadHelper cch = new SimpleTypeLoadHelper(); cch.Initialize(); SchedulerDetailsSetter.SetDetails(jobStore, schedulerName, schedulerInstanceId); jobStore.Initialize(cch, qs.SchedulerSignaler); IScheduler scheduler = new StdScheduler(qs); jrsf.Initialize(scheduler); qs.Initialize(); // Initialize plugins now that we have a Scheduler instance. if (schedulerPluginMap != null) { foreach (var pluginEntry in schedulerPluginMap) { pluginEntry.Value.Initialize(pluginEntry.Key, scheduler); } } Log.Info(string.Format(CultureInfo.InvariantCulture, "Quartz scheduler '{0}", scheduler.SchedulerName)); Log.Info(string.Format(CultureInfo.InvariantCulture, "Quartz scheduler version: {0}", qs.Version)); SchedulerRepository schedRep = SchedulerRepository.Instance; qs.AddNoGCObject(schedRep); // prevents the repository from being // garbage collected schedRep.Bind(scheduler); initialized = true; } /// <summary> /// Returns a handle to the Scheduler produced by this factory. /// <para> /// you must call createRemoteScheduler or createScheduler methods before /// calling getScheduler() /// </para> /// </summary> /// <returns></returns> /// <throws> SchedulerException </throws> public virtual IScheduler GetScheduler() { if (!initialized) { throw new SchedulerException( "you must call createRemoteScheduler or createScheduler methods before calling getScheduler()"); } SchedulerRepository schedRep = SchedulerRepository.Instance; return schedRep.Lookup(DefaultSchedulerName); } /// <summary> /// Returns a handle to the Scheduler with the given name, if it exists. /// </summary> public virtual IScheduler GetScheduler(string schedName) { SchedulerRepository schedRep = SchedulerRepository.Instance; return schedRep.Lookup(schedName); } } }
using System; using System.Diagnostics; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Modes { /** * A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to * be used to produce cipher text which is the same outLength as the plain text. */ public class CtsBlockCipher : BufferedBlockCipher { private readonly int blockSize; /** * Create a buffered block cipher that uses Cipher Text Stealing * * @param cipher the underlying block cipher this buffering object wraps. */ public CtsBlockCipher( IBlockCipher cipher) { // TODO Should this test for acceptable ones instead? if (cipher is OfbBlockCipher || cipher is CfbBlockCipher) throw new ArgumentException("CtsBlockCipher can only accept ECB, or CBC ciphers"); this.cipher = cipher; blockSize = cipher.GetBlockSize(); buf = new byte[blockSize * 2]; bufOff = 0; } /** * return the size of the output buffer required for an update of 'length' bytes. * * @param length the outLength of the input. * @return the space required to accommodate a call to update * with length bytes of input. */ public override int GetUpdateOutputSize( int length) { int total = length + bufOff; int leftOver = total % buf.Length; if (leftOver == 0) { return total - buf.Length; } return total - leftOver; } /** * return the size of the output buffer required for an update plus a * doFinal with an input of length bytes. * * @param length the outLength of the input. * @return the space required to accommodate a call to update and doFinal * with length bytes of input. */ public override int GetOutputSize( int length) { return length + bufOff; } /** * process a single byte, producing an output block if neccessary. * * @param in the input byte. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessByte( byte input, byte[] output, int outOff) { int resultLen = 0; if (bufOff == buf.Length) { resultLen = cipher.ProcessBlock(buf, 0, output, outOff); Debug.Assert(resultLen == blockSize); Array.Copy(buf, blockSize, buf, 0, blockSize); bufOff = blockSize; } buf[bufOff++] = input; return resultLen; } /** * process an array of bytes, producing output if necessary. * * @param in the input byte array. * @param inOff the offset at which the input data starts. * @param length the number of bytes to be copied out of the input array. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessBytes( byte[] input, int inOff, int length, byte[] output, int outOff) { if (length < 0) { throw new ArgumentException("Can't have a negative input outLength!"); } int blockSize = GetBlockSize(); int outLength = GetUpdateOutputSize(length); if (outLength > 0) { if ((outOff + outLength) > output.Length) { throw new DataLengthException("output buffer too short"); } } int resultLen = 0; int gapLen = buf.Length - bufOff; if (length > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); resultLen += cipher.ProcessBlock(buf, 0, output, outOff); Array.Copy(buf, blockSize, buf, 0, blockSize); bufOff = blockSize; length -= gapLen; inOff += gapLen; while (length > blockSize) { Array.Copy(input, inOff, buf, bufOff, blockSize); resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen); Array.Copy(buf, blockSize, buf, 0, blockSize); length -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, buf, bufOff, length); bufOff += length; return resultLen; } /** * Process the last block in the buffer. * * @param out the array the block currently being held is copied into. * @param outOff the offset at which the copying starts. * @return the number of output bytes copied to out. * @exception DataLengthException if there is insufficient space in out for * the output. * @exception InvalidOperationException if the underlying cipher is not * initialised. * @exception InvalidCipherTextException if cipher text decrypts wrongly (in * case the exception will never Get thrown). */ public override int DoFinal( byte[] output, int outOff) { if (bufOff + outOff > output.Length) { throw new DataLengthException("output buffer too small in doFinal"); } int blockSize = cipher.GetBlockSize(); int length = bufOff - blockSize; byte[] block = new byte[blockSize]; if (forEncryption) { cipher.ProcessBlock(buf, 0, block, 0); if (bufOff < blockSize) { throw new DataLengthException("need at least one block of input for CTS"); } for (int i = bufOff; i != buf.Length; i++) { buf[i] = block[i - blockSize]; } for (int i = blockSize; i != bufOff; i++) { buf[i] ^= block[i - blockSize]; } IBlockCipher c = (cipher is CbcBlockCipher) ? ((CbcBlockCipher)cipher).GetUnderlyingCipher() : cipher; c.ProcessBlock(buf, blockSize, output, outOff); Array.Copy(block, 0, output, outOff + blockSize, length); } else { byte[] lastBlock = new byte[blockSize]; IBlockCipher c = (cipher is CbcBlockCipher) ? ((CbcBlockCipher)cipher).GetUnderlyingCipher() : cipher; c.ProcessBlock(buf, 0, block, 0); for (int i = blockSize; i != bufOff; i++) { lastBlock[i - blockSize] = (byte)(block[i - blockSize] ^ buf[i]); } Array.Copy(buf, blockSize, block, 0, length); cipher.ProcessBlock(block, 0, output, outOff); Array.Copy(lastBlock, 0, output, outOff + blockSize, length); } int offset = bufOff; Reset(); return offset; } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.6400 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by wsdl, Version=2.0.50727.3038. // namespace WebsitePanel.EnterpriseServer { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; using WebsitePanel.Providers.Common; using WebsitePanel.Providers.HostedSolution; using WebsitePanel.Providers.ResultObjects; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="esLyncSoap", Namespace="http://tempuri.org/")] public partial class esLync : Microsoft.Web.Services3.WebServicesClientProtocol { private System.Threading.SendOrPostCallback CreateLyncUserOperationCompleted; private System.Threading.SendOrPostCallback DeleteLyncUserOperationCompleted; private System.Threading.SendOrPostCallback GetLyncUsersPagedOperationCompleted; private System.Threading.SendOrPostCallback GetLyncUsersByPlanIdOperationCompleted; private System.Threading.SendOrPostCallback GetLyncUserCountOperationCompleted; private System.Threading.SendOrPostCallback GetLyncUserPlansOperationCompleted; private System.Threading.SendOrPostCallback GetLyncUserPlanOperationCompleted; private System.Threading.SendOrPostCallback AddLyncUserPlanOperationCompleted; private System.Threading.SendOrPostCallback UpdateLyncUserPlanOperationCompleted; private System.Threading.SendOrPostCallback DeleteLyncUserPlanOperationCompleted; private System.Threading.SendOrPostCallback SetOrganizationDefaultLyncUserPlanOperationCompleted; private System.Threading.SendOrPostCallback GetLyncUserGeneralSettingsOperationCompleted; private System.Threading.SendOrPostCallback SetLyncUserGeneralSettingsOperationCompleted; private System.Threading.SendOrPostCallback SetUserLyncPlanOperationCompleted; private System.Threading.SendOrPostCallback GetFederationDomainsOperationCompleted; private System.Threading.SendOrPostCallback AddFederationDomainOperationCompleted; private System.Threading.SendOrPostCallback RemoveFederationDomainOperationCompleted; /// <remarks/> public esLync() { this.Url = "http://localhost:9002/esLync.asmx"; } /// <remarks/> public event CreateLyncUserCompletedEventHandler CreateLyncUserCompleted; /// <remarks/> public event DeleteLyncUserCompletedEventHandler DeleteLyncUserCompleted; /// <remarks/> public event GetLyncUsersPagedCompletedEventHandler GetLyncUsersPagedCompleted; /// <remarks/> public event GetLyncUsersByPlanIdCompletedEventHandler GetLyncUsersByPlanIdCompleted; /// <remarks/> public event GetLyncUserCountCompletedEventHandler GetLyncUserCountCompleted; /// <remarks/> public event GetLyncUserPlansCompletedEventHandler GetLyncUserPlansCompleted; /// <remarks/> public event GetLyncUserPlanCompletedEventHandler GetLyncUserPlanCompleted; /// <remarks/> public event AddLyncUserPlanCompletedEventHandler AddLyncUserPlanCompleted; /// <remarks/> public event UpdateLyncUserPlanCompletedEventHandler UpdateLyncUserPlanCompleted; /// <remarks/> public event DeleteLyncUserPlanCompletedEventHandler DeleteLyncUserPlanCompleted; /// <remarks/> public event SetOrganizationDefaultLyncUserPlanCompletedEventHandler SetOrganizationDefaultLyncUserPlanCompleted; /// <remarks/> public event GetLyncUserGeneralSettingsCompletedEventHandler GetLyncUserGeneralSettingsCompleted; /// <remarks/> public event SetLyncUserGeneralSettingsCompletedEventHandler SetLyncUserGeneralSettingsCompleted; /// <remarks/> public event SetUserLyncPlanCompletedEventHandler SetUserLyncPlanCompleted; /// <remarks/> public event GetFederationDomainsCompletedEventHandler GetFederationDomainsCompleted; /// <remarks/> public event AddFederationDomainCompletedEventHandler AddFederationDomainCompleted; /// <remarks/> public event RemoveFederationDomainCompletedEventHandler RemoveFederationDomainCompleted; /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/CreateLyncUser", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public LyncUserResult CreateLyncUser(int itemId, int accountId, int lyncUserPlanId) { object[] results = this.Invoke("CreateLyncUser", new object[] { itemId, accountId, lyncUserPlanId}); return ((LyncUserResult)(results[0])); } /// <remarks/> public System.IAsyncResult BeginCreateLyncUser(int itemId, int accountId, int lyncUserPlanId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("CreateLyncUser", new object[] { itemId, accountId, lyncUserPlanId}, callback, asyncState); } /// <remarks/> public LyncUserResult EndCreateLyncUser(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((LyncUserResult)(results[0])); } /// <remarks/> public void CreateLyncUserAsync(int itemId, int accountId, int lyncUserPlanId) { this.CreateLyncUserAsync(itemId, accountId, lyncUserPlanId, null); } /// <remarks/> public void CreateLyncUserAsync(int itemId, int accountId, int lyncUserPlanId, object userState) { if ((this.CreateLyncUserOperationCompleted == null)) { this.CreateLyncUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateLyncUserOperationCompleted); } this.InvokeAsync("CreateLyncUser", new object[] { itemId, accountId, lyncUserPlanId}, this.CreateLyncUserOperationCompleted, userState); } private void OnCreateLyncUserOperationCompleted(object arg) { if ((this.CreateLyncUserCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.CreateLyncUserCompleted(this, new CreateLyncUserCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/DeleteLyncUser", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public ResultObject DeleteLyncUser(int itemId, int accountId) { object[] results = this.Invoke("DeleteLyncUser", new object[] { itemId, accountId}); return ((ResultObject)(results[0])); } /// <remarks/> public System.IAsyncResult BeginDeleteLyncUser(int itemId, int accountId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("DeleteLyncUser", new object[] { itemId, accountId}, callback, asyncState); } /// <remarks/> public ResultObject EndDeleteLyncUser(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((ResultObject)(results[0])); } /// <remarks/> public void DeleteLyncUserAsync(int itemId, int accountId) { this.DeleteLyncUserAsync(itemId, accountId, null); } /// <remarks/> public void DeleteLyncUserAsync(int itemId, int accountId, object userState) { if ((this.DeleteLyncUserOperationCompleted == null)) { this.DeleteLyncUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteLyncUserOperationCompleted); } this.InvokeAsync("DeleteLyncUser", new object[] { itemId, accountId}, this.DeleteLyncUserOperationCompleted, userState); } private void OnDeleteLyncUserOperationCompleted(object arg) { if ((this.DeleteLyncUserCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.DeleteLyncUserCompleted(this, new DeleteLyncUserCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetLyncUsersPaged", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public LyncUsersPagedResult GetLyncUsersPaged(int itemId, string sortColumn, string sortDirection, int startRow, int maximumRows) { object[] results = this.Invoke("GetLyncUsersPaged", new object[] { itemId, sortColumn, sortDirection, startRow, maximumRows}); return ((LyncUsersPagedResult)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetLyncUsersPaged(int itemId, string sortColumn, string sortDirection, int startRow, int maximumRows, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetLyncUsersPaged", new object[] { itemId, sortColumn, sortDirection, startRow, maximumRows}, callback, asyncState); } /// <remarks/> public LyncUsersPagedResult EndGetLyncUsersPaged(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((LyncUsersPagedResult)(results[0])); } /// <remarks/> public void GetLyncUsersPagedAsync(int itemId, string sortColumn, string sortDirection, int startRow, int maximumRows) { this.GetLyncUsersPagedAsync(itemId, sortColumn, sortDirection, startRow, maximumRows, null); } /// <remarks/> public void GetLyncUsersPagedAsync(int itemId, string sortColumn, string sortDirection, int startRow, int maximumRows, object userState) { if ((this.GetLyncUsersPagedOperationCompleted == null)) { this.GetLyncUsersPagedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetLyncUsersPagedOperationCompleted); } this.InvokeAsync("GetLyncUsersPaged", new object[] { itemId, sortColumn, sortDirection, startRow, maximumRows}, this.GetLyncUsersPagedOperationCompleted, userState); } private void OnGetLyncUsersPagedOperationCompleted(object arg) { if ((this.GetLyncUsersPagedCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetLyncUsersPagedCompleted(this, new GetLyncUsersPagedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetLyncUsersByPlanId", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public LyncUser[] GetLyncUsersByPlanId(int itemId, int planId) { object[] results = this.Invoke("GetLyncUsersByPlanId", new object[] { itemId, planId}); return ((LyncUser[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetLyncUsersByPlanId(int itemId, int planId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetLyncUsersByPlanId", new object[] { itemId, planId}, callback, asyncState); } /// <remarks/> public LyncUser[] EndGetLyncUsersByPlanId(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((LyncUser[])(results[0])); } /// <remarks/> public void GetLyncUsersByPlanIdAsync(int itemId, int planId) { this.GetLyncUsersByPlanIdAsync(itemId, planId, null); } /// <remarks/> public void GetLyncUsersByPlanIdAsync(int itemId, int planId, object userState) { if ((this.GetLyncUsersByPlanIdOperationCompleted == null)) { this.GetLyncUsersByPlanIdOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetLyncUsersByPlanIdOperationCompleted); } this.InvokeAsync("GetLyncUsersByPlanId", new object[] { itemId, planId}, this.GetLyncUsersByPlanIdOperationCompleted, userState); } private void OnGetLyncUsersByPlanIdOperationCompleted(object arg) { if ((this.GetLyncUsersByPlanIdCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetLyncUsersByPlanIdCompleted(this, new GetLyncUsersByPlanIdCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetLyncUserCount", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public IntResult GetLyncUserCount(int itemId) { object[] results = this.Invoke("GetLyncUserCount", new object[] { itemId}); return ((IntResult)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetLyncUserCount(int itemId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetLyncUserCount", new object[] { itemId}, callback, asyncState); } /// <remarks/> public IntResult EndGetLyncUserCount(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((IntResult)(results[0])); } /// <remarks/> public void GetLyncUserCountAsync(int itemId) { this.GetLyncUserCountAsync(itemId, null); } /// <remarks/> public void GetLyncUserCountAsync(int itemId, object userState) { if ((this.GetLyncUserCountOperationCompleted == null)) { this.GetLyncUserCountOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetLyncUserCountOperationCompleted); } this.InvokeAsync("GetLyncUserCount", new object[] { itemId}, this.GetLyncUserCountOperationCompleted, userState); } private void OnGetLyncUserCountOperationCompleted(object arg) { if ((this.GetLyncUserCountCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetLyncUserCountCompleted(this, new GetLyncUserCountCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetLyncUserPlans", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public LyncUserPlan[] GetLyncUserPlans(int itemId) { object[] results = this.Invoke("GetLyncUserPlans", new object[] { itemId}); return ((LyncUserPlan[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetLyncUserPlans(int itemId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetLyncUserPlans", new object[] { itemId}, callback, asyncState); } /// <remarks/> public LyncUserPlan[] EndGetLyncUserPlans(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((LyncUserPlan[])(results[0])); } /// <remarks/> public void GetLyncUserPlansAsync(int itemId) { this.GetLyncUserPlansAsync(itemId, null); } /// <remarks/> public void GetLyncUserPlansAsync(int itemId, object userState) { if ((this.GetLyncUserPlansOperationCompleted == null)) { this.GetLyncUserPlansOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetLyncUserPlansOperationCompleted); } this.InvokeAsync("GetLyncUserPlans", new object[] { itemId}, this.GetLyncUserPlansOperationCompleted, userState); } private void OnGetLyncUserPlansOperationCompleted(object arg) { if ((this.GetLyncUserPlansCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetLyncUserPlansCompleted(this, new GetLyncUserPlansCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetLyncUserPlan", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public LyncUserPlan GetLyncUserPlan(int itemId, int lyncUserPlanId) { object[] results = this.Invoke("GetLyncUserPlan", new object[] { itemId, lyncUserPlanId}); return ((LyncUserPlan)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetLyncUserPlan(int itemId, int lyncUserPlanId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetLyncUserPlan", new object[] { itemId, lyncUserPlanId}, callback, asyncState); } /// <remarks/> public LyncUserPlan EndGetLyncUserPlan(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((LyncUserPlan)(results[0])); } /// <remarks/> public void GetLyncUserPlanAsync(int itemId, int lyncUserPlanId) { this.GetLyncUserPlanAsync(itemId, lyncUserPlanId, null); } /// <remarks/> public void GetLyncUserPlanAsync(int itemId, int lyncUserPlanId, object userState) { if ((this.GetLyncUserPlanOperationCompleted == null)) { this.GetLyncUserPlanOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetLyncUserPlanOperationCompleted); } this.InvokeAsync("GetLyncUserPlan", new object[] { itemId, lyncUserPlanId}, this.GetLyncUserPlanOperationCompleted, userState); } private void OnGetLyncUserPlanOperationCompleted(object arg) { if ((this.GetLyncUserPlanCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetLyncUserPlanCompleted(this, new GetLyncUserPlanCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/AddLyncUserPlan", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int AddLyncUserPlan(int itemId, LyncUserPlan lyncUserPlan) { object[] results = this.Invoke("AddLyncUserPlan", new object[] { itemId, lyncUserPlan}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginAddLyncUserPlan(int itemId, LyncUserPlan lyncUserPlan, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddLyncUserPlan", new object[] { itemId, lyncUserPlan}, callback, asyncState); } /// <remarks/> public int EndAddLyncUserPlan(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void AddLyncUserPlanAsync(int itemId, LyncUserPlan lyncUserPlan) { this.AddLyncUserPlanAsync(itemId, lyncUserPlan, null); } /// <remarks/> public void AddLyncUserPlanAsync(int itemId, LyncUserPlan lyncUserPlan, object userState) { if ((this.AddLyncUserPlanOperationCompleted == null)) { this.AddLyncUserPlanOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddLyncUserPlanOperationCompleted); } this.InvokeAsync("AddLyncUserPlan", new object[] { itemId, lyncUserPlan}, this.AddLyncUserPlanOperationCompleted, userState); } private void OnAddLyncUserPlanOperationCompleted(object arg) { if ((this.AddLyncUserPlanCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AddLyncUserPlanCompleted(this, new AddLyncUserPlanCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/UpdateLyncUserPlan", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int UpdateLyncUserPlan(int itemId, LyncUserPlan lyncUserPlan) { object[] results = this.Invoke("UpdateLyncUserPlan", new object[] { itemId, lyncUserPlan}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginUpdateLyncUserPlan(int itemId, LyncUserPlan lyncUserPlan, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("UpdateLyncUserPlan", new object[] { itemId, lyncUserPlan}, callback, asyncState); } /// <remarks/> public int EndUpdateLyncUserPlan(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void UpdateLyncUserPlanAsync(int itemId, LyncUserPlan lyncUserPlan) { this.UpdateLyncUserPlanAsync(itemId, lyncUserPlan, null); } /// <remarks/> public void UpdateLyncUserPlanAsync(int itemId, LyncUserPlan lyncUserPlan, object userState) { if ((this.UpdateLyncUserPlanOperationCompleted == null)) { this.UpdateLyncUserPlanOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateLyncUserPlanOperationCompleted); } this.InvokeAsync("UpdateLyncUserPlan", new object[] { itemId, lyncUserPlan}, this.UpdateLyncUserPlanOperationCompleted, userState); } private void OnUpdateLyncUserPlanOperationCompleted(object arg) { if ((this.UpdateLyncUserPlanCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.UpdateLyncUserPlanCompleted(this, new UpdateLyncUserPlanCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/DeleteLyncUserPlan", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int DeleteLyncUserPlan(int itemId, int lyncUserPlanId) { object[] results = this.Invoke("DeleteLyncUserPlan", new object[] { itemId, lyncUserPlanId}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginDeleteLyncUserPlan(int itemId, int lyncUserPlanId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("DeleteLyncUserPlan", new object[] { itemId, lyncUserPlanId}, callback, asyncState); } /// <remarks/> public int EndDeleteLyncUserPlan(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void DeleteLyncUserPlanAsync(int itemId, int lyncUserPlanId) { this.DeleteLyncUserPlanAsync(itemId, lyncUserPlanId, null); } /// <remarks/> public void DeleteLyncUserPlanAsync(int itemId, int lyncUserPlanId, object userState) { if ((this.DeleteLyncUserPlanOperationCompleted == null)) { this.DeleteLyncUserPlanOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteLyncUserPlanOperationCompleted); } this.InvokeAsync("DeleteLyncUserPlan", new object[] { itemId, lyncUserPlanId}, this.DeleteLyncUserPlanOperationCompleted, userState); } private void OnDeleteLyncUserPlanOperationCompleted(object arg) { if ((this.DeleteLyncUserPlanCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.DeleteLyncUserPlanCompleted(this, new DeleteLyncUserPlanCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/SetOrganizationDefaultLyncUserPlan", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int SetOrganizationDefaultLyncUserPlan(int itemId, int lyncUserPlanId) { object[] results = this.Invoke("SetOrganizationDefaultLyncUserPlan", new object[] { itemId, lyncUserPlanId}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginSetOrganizationDefaultLyncUserPlan(int itemId, int lyncUserPlanId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("SetOrganizationDefaultLyncUserPlan", new object[] { itemId, lyncUserPlanId}, callback, asyncState); } /// <remarks/> public int EndSetOrganizationDefaultLyncUserPlan(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void SetOrganizationDefaultLyncUserPlanAsync(int itemId, int lyncUserPlanId) { this.SetOrganizationDefaultLyncUserPlanAsync(itemId, lyncUserPlanId, null); } /// <remarks/> public void SetOrganizationDefaultLyncUserPlanAsync(int itemId, int lyncUserPlanId, object userState) { if ((this.SetOrganizationDefaultLyncUserPlanOperationCompleted == null)) { this.SetOrganizationDefaultLyncUserPlanOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetOrganizationDefaultLyncUserPlanOperationCompleted); } this.InvokeAsync("SetOrganizationDefaultLyncUserPlan", new object[] { itemId, lyncUserPlanId}, this.SetOrganizationDefaultLyncUserPlanOperationCompleted, userState); } private void OnSetOrganizationDefaultLyncUserPlanOperationCompleted(object arg) { if ((this.SetOrganizationDefaultLyncUserPlanCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.SetOrganizationDefaultLyncUserPlanCompleted(this, new SetOrganizationDefaultLyncUserPlanCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetLyncUserGeneralSettings", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public LyncUser GetLyncUserGeneralSettings(int itemId, int accountId) { object[] results = this.Invoke("GetLyncUserGeneralSettings", new object[] { itemId, accountId}); return ((LyncUser)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetLyncUserGeneralSettings(int itemId, int accountId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetLyncUserGeneralSettings", new object[] { itemId, accountId}, callback, asyncState); } /// <remarks/> public LyncUser EndGetLyncUserGeneralSettings(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((LyncUser)(results[0])); } /// <remarks/> public void GetLyncUserGeneralSettingsAsync(int itemId, int accountId) { this.GetLyncUserGeneralSettingsAsync(itemId, accountId, null); } /// <remarks/> public void GetLyncUserGeneralSettingsAsync(int itemId, int accountId, object userState) { if ((this.GetLyncUserGeneralSettingsOperationCompleted == null)) { this.GetLyncUserGeneralSettingsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetLyncUserGeneralSettingsOperationCompleted); } this.InvokeAsync("GetLyncUserGeneralSettings", new object[] { itemId, accountId}, this.GetLyncUserGeneralSettingsOperationCompleted, userState); } private void OnGetLyncUserGeneralSettingsOperationCompleted(object arg) { if ((this.GetLyncUserGeneralSettingsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetLyncUserGeneralSettingsCompleted(this, new GetLyncUserGeneralSettingsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/SetLyncUserGeneralSettings", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public LyncUserResult SetLyncUserGeneralSettings(int itemId, int accountId, string sipAddress, string lineUri) { object[] results = this.Invoke("SetLyncUserGeneralSettings", new object[] { itemId, accountId, sipAddress, lineUri}); return ((LyncUserResult)(results[0])); } /// <remarks/> public System.IAsyncResult BeginSetLyncUserGeneralSettings(int itemId, int accountId, string sipAddress, string lineUri, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("SetLyncUserGeneralSettings", new object[] { itemId, accountId, sipAddress, lineUri}, callback, asyncState); } /// <remarks/> public LyncUserResult EndSetLyncUserGeneralSettings(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((LyncUserResult)(results[0])); } /// <remarks/> public void SetLyncUserGeneralSettingsAsync(int itemId, int accountId, string sipAddress, string lineUri) { this.SetLyncUserGeneralSettingsAsync(itemId, accountId, sipAddress, lineUri, null); } /// <remarks/> public void SetLyncUserGeneralSettingsAsync(int itemId, int accountId, string sipAddress, string lineUri, object userState) { if ((this.SetLyncUserGeneralSettingsOperationCompleted == null)) { this.SetLyncUserGeneralSettingsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetLyncUserGeneralSettingsOperationCompleted); } this.InvokeAsync("SetLyncUserGeneralSettings", new object[] { itemId, accountId, sipAddress, lineUri}, this.SetLyncUserGeneralSettingsOperationCompleted, userState); } private void OnSetLyncUserGeneralSettingsOperationCompleted(object arg) { if ((this.SetLyncUserGeneralSettingsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.SetLyncUserGeneralSettingsCompleted(this, new SetLyncUserGeneralSettingsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/SetUserLyncPlan", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public LyncUserResult SetUserLyncPlan(int itemId, int accountId, int lyncUserPlanId) { object[] results = this.Invoke("SetUserLyncPlan", new object[] { itemId, accountId, lyncUserPlanId}); return ((LyncUserResult)(results[0])); } /// <remarks/> public System.IAsyncResult BeginSetUserLyncPlan(int itemId, int accountId, int lyncUserPlanId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("SetUserLyncPlan", new object[] { itemId, accountId, lyncUserPlanId}, callback, asyncState); } /// <remarks/> public LyncUserResult EndSetUserLyncPlan(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((LyncUserResult)(results[0])); } /// <remarks/> public void SetUserLyncPlanAsync(int itemId, int accountId, int lyncUserPlanId) { this.SetUserLyncPlanAsync(itemId, accountId, lyncUserPlanId, null); } /// <remarks/> public void SetUserLyncPlanAsync(int itemId, int accountId, int lyncUserPlanId, object userState) { if ((this.SetUserLyncPlanOperationCompleted == null)) { this.SetUserLyncPlanOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetUserLyncPlanOperationCompleted); } this.InvokeAsync("SetUserLyncPlan", new object[] { itemId, accountId, lyncUserPlanId}, this.SetUserLyncPlanOperationCompleted, userState); } private void OnSetUserLyncPlanOperationCompleted(object arg) { if ((this.SetUserLyncPlanCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.SetUserLyncPlanCompleted(this, new SetUserLyncPlanCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetFederationDomains", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public LyncFederationDomain[] GetFederationDomains(int itemId) { object[] results = this.Invoke("GetFederationDomains", new object[] { itemId}); return ((LyncFederationDomain[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetFederationDomains(int itemId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetFederationDomains", new object[] { itemId}, callback, asyncState); } /// <remarks/> public LyncFederationDomain[] EndGetFederationDomains(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((LyncFederationDomain[])(results[0])); } /// <remarks/> public void GetFederationDomainsAsync(int itemId) { this.GetFederationDomainsAsync(itemId, null); } /// <remarks/> public void GetFederationDomainsAsync(int itemId, object userState) { if ((this.GetFederationDomainsOperationCompleted == null)) { this.GetFederationDomainsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetFederationDomainsOperationCompleted); } this.InvokeAsync("GetFederationDomains", new object[] { itemId}, this.GetFederationDomainsOperationCompleted, userState); } private void OnGetFederationDomainsOperationCompleted(object arg) { if ((this.GetFederationDomainsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetFederationDomainsCompleted(this, new GetFederationDomainsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/AddFederationDomain", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public LyncUserResult AddFederationDomain(int itemId, string domainName, string proxyFqdn) { object[] results = this.Invoke("AddFederationDomain", new object[] { itemId, domainName, proxyFqdn}); return ((LyncUserResult)(results[0])); } /// <remarks/> public System.IAsyncResult BeginAddFederationDomain(int itemId, string domainName, string proxyFqdn, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddFederationDomain", new object[] { itemId, domainName, proxyFqdn}, callback, asyncState); } /// <remarks/> public LyncUserResult EndAddFederationDomain(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((LyncUserResult)(results[0])); } /// <remarks/> public void AddFederationDomainAsync(int itemId, string domainName, string proxyFqdn) { this.AddFederationDomainAsync(itemId, domainName, proxyFqdn, null); } /// <remarks/> public void AddFederationDomainAsync(int itemId, string domainName, string proxyFqdn, object userState) { if ((this.AddFederationDomainOperationCompleted == null)) { this.AddFederationDomainOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddFederationDomainOperationCompleted); } this.InvokeAsync("AddFederationDomain", new object[] { itemId, domainName, proxyFqdn}, this.AddFederationDomainOperationCompleted, userState); } private void OnAddFederationDomainOperationCompleted(object arg) { if ((this.AddFederationDomainCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AddFederationDomainCompleted(this, new AddFederationDomainCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/RemoveFederationDomain", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public LyncUserResult RemoveFederationDomain(int itemId, string domainName) { object[] results = this.Invoke("RemoveFederationDomain", new object[] { itemId, domainName}); return ((LyncUserResult)(results[0])); } /// <remarks/> public System.IAsyncResult BeginRemoveFederationDomain(int itemId, string domainName, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("RemoveFederationDomain", new object[] { itemId, domainName}, callback, asyncState); } /// <remarks/> public LyncUserResult EndRemoveFederationDomain(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((LyncUserResult)(results[0])); } /// <remarks/> public void RemoveFederationDomainAsync(int itemId, string domainName) { this.RemoveFederationDomainAsync(itemId, domainName, null); } /// <remarks/> public void RemoveFederationDomainAsync(int itemId, string domainName, object userState) { if ((this.RemoveFederationDomainOperationCompleted == null)) { this.RemoveFederationDomainOperationCompleted = new System.Threading.SendOrPostCallback(this.OnRemoveFederationDomainOperationCompleted); } this.InvokeAsync("RemoveFederationDomain", new object[] { itemId, domainName}, this.RemoveFederationDomainOperationCompleted, userState); } private void OnRemoveFederationDomainOperationCompleted(object arg) { if ((this.RemoveFederationDomainCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.RemoveFederationDomainCompleted(this, new RemoveFederationDomainCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetPolicyList", RequestNamespace = "http://tempuri.org/", ResponseNamespace = "http://tempuri.org/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string[] GetPolicyList(int itemId, LyncPolicyType type, string name) { object[] results = this.Invoke("GetPolicyList", new object[] { itemId, type, name}); return ((string[])(results[0])); } /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void CreateLyncUserCompletedEventHandler(object sender, CreateLyncUserCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class CreateLyncUserCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal CreateLyncUserCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public LyncUserResult Result { get { this.RaiseExceptionIfNecessary(); return ((LyncUserResult)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void DeleteLyncUserCompletedEventHandler(object sender, DeleteLyncUserCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class DeleteLyncUserCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal DeleteLyncUserCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public ResultObject Result { get { this.RaiseExceptionIfNecessary(); return ((ResultObject)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetLyncUsersPagedCompletedEventHandler(object sender, GetLyncUsersPagedCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetLyncUsersPagedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetLyncUsersPagedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public LyncUsersPagedResult Result { get { this.RaiseExceptionIfNecessary(); return ((LyncUsersPagedResult)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetLyncUsersByPlanIdCompletedEventHandler(object sender, GetLyncUsersByPlanIdCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetLyncUsersByPlanIdCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetLyncUsersByPlanIdCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public LyncUser[] Result { get { this.RaiseExceptionIfNecessary(); return ((LyncUser[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetLyncUserCountCompletedEventHandler(object sender, GetLyncUserCountCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetLyncUserCountCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetLyncUserCountCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public IntResult Result { get { this.RaiseExceptionIfNecessary(); return ((IntResult)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetLyncUserPlansCompletedEventHandler(object sender, GetLyncUserPlansCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetLyncUserPlansCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetLyncUserPlansCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public LyncUserPlan[] Result { get { this.RaiseExceptionIfNecessary(); return ((LyncUserPlan[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetLyncUserPlanCompletedEventHandler(object sender, GetLyncUserPlanCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetLyncUserPlanCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetLyncUserPlanCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public LyncUserPlan Result { get { this.RaiseExceptionIfNecessary(); return ((LyncUserPlan)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void AddLyncUserPlanCompletedEventHandler(object sender, AddLyncUserPlanCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class AddLyncUserPlanCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal AddLyncUserPlanCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void UpdateLyncUserPlanCompletedEventHandler(object sender, UpdateLyncUserPlanCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class UpdateLyncUserPlanCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal UpdateLyncUserPlanCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void DeleteLyncUserPlanCompletedEventHandler(object sender, DeleteLyncUserPlanCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class DeleteLyncUserPlanCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal DeleteLyncUserPlanCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void SetOrganizationDefaultLyncUserPlanCompletedEventHandler(object sender, SetOrganizationDefaultLyncUserPlanCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class SetOrganizationDefaultLyncUserPlanCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal SetOrganizationDefaultLyncUserPlanCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetLyncUserGeneralSettingsCompletedEventHandler(object sender, GetLyncUserGeneralSettingsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetLyncUserGeneralSettingsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetLyncUserGeneralSettingsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public LyncUser Result { get { this.RaiseExceptionIfNecessary(); return ((LyncUser)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void SetLyncUserGeneralSettingsCompletedEventHandler(object sender, SetLyncUserGeneralSettingsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class SetLyncUserGeneralSettingsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal SetLyncUserGeneralSettingsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public LyncUserResult Result { get { this.RaiseExceptionIfNecessary(); return ((LyncUserResult)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void SetUserLyncPlanCompletedEventHandler(object sender, SetUserLyncPlanCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class SetUserLyncPlanCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal SetUserLyncPlanCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public LyncUserResult Result { get { this.RaiseExceptionIfNecessary(); return ((LyncUserResult)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetFederationDomainsCompletedEventHandler(object sender, GetFederationDomainsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetFederationDomainsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetFederationDomainsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public LyncFederationDomain[] Result { get { this.RaiseExceptionIfNecessary(); return ((LyncFederationDomain[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void AddFederationDomainCompletedEventHandler(object sender, AddFederationDomainCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class AddFederationDomainCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal AddFederationDomainCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public LyncUserResult Result { get { this.RaiseExceptionIfNecessary(); return ((LyncUserResult)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void RemoveFederationDomainCompletedEventHandler(object sender, RemoveFederationDomainCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class RemoveFederationDomainCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal RemoveFederationDomainCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public LyncUserResult Result { get { this.RaiseExceptionIfNecessary(); return ((LyncUserResult)(this.results[0])); } } } }
//------------------------------------------------------------------------------ // <copyright file="HtmlInputText.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * HtmlInputText.cs * * Copyright (c) 2000 Microsoft Corporation */ namespace System.Web.UI.HtmlControls { using System.ComponentModel; using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Web; using System.Web.UI; using System.Security.Permissions; /// <devdoc> /// <para> /// The <see langword='HtmlInputText'/> /// class defines the methods, properties, and events for the HtmlInputText server /// control. This class allows programmatic access to the HTML &lt;input type= /// text&gt; /// and &lt;input type= /// password&gt; elements on the server. /// </para> /// </devdoc> [ DefaultEvent("ServerChange"), SupportsEventValidation, ValidationProperty("Value"), ] public class HtmlInputText : HtmlInputControl, IPostBackDataHandler { private static readonly object EventServerChange = new object(); /* * Creates an intrinsic Html INPUT type=text control. */ public HtmlInputText() : base("text") { } /* * Creates an intrinsic Html INPUT type=text control. */ /// <devdoc> /// </devdoc> public HtmlInputText(string type) : base(type) { } /* * The property for the maximum characters allowed. */ /// <devdoc> /// <para> /// Gets or sets the maximum number of characters that /// can be typed into the text box. /// </para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public int MaxLength { get { string s = (string)ViewState["maxlength"]; return((s != null) ? Int32.Parse(s, CultureInfo.InvariantCulture) : -1); } set { Attributes["maxlength"] = MapIntegerAttributeToString(value); } } // /* * The property for the width of the TextBox in characters. */ /// <devdoc> /// <para> /// Gets or sets the width of a text box, in characters. /// </para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(-1), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public int Size { get { string s = Attributes["size"]; return((s != null) ? Int32.Parse(s, CultureInfo.InvariantCulture) : -1); } set { Attributes["size"] = MapIntegerAttributeToString(value); } } /* * Value property. */ /// <devdoc> /// <para> /// Gets or sets the /// contents of a text box. /// </para> /// </devdoc> public override string Value { get { string s = Attributes["value"]; return((s != null) ? s : String.Empty); } set { Attributes["value"] = MapStringAttributeToString(value); } } [ WebCategory("Action"), WebSysDescription(SR.HtmlInputText_ServerChange) ] public event EventHandler ServerChange { add { Events.AddHandler(EventServerChange, value); } remove { Events.RemoveHandler(EventServerChange, value); } } /* * Method used to raise the OnServerChange event. */ /// <devdoc> /// </devdoc> protected virtual void OnServerChange(EventArgs e) { EventHandler handler = (EventHandler)Events[EventServerChange]; if (handler != null) handler(this, e); } /* * */ /// <internalonly/> /// <devdoc> /// </devdoc> protected internal override void OnPreRender(EventArgs e) { base.OnPreRender(e); bool disabled = Disabled; if (!disabled && Page != null) { Page.RegisterEnabledControl(this); } // if no change handler, no need to save posted property unless we are disabled; // VSWhidbey 419040: We should never save password value in ViewState if ((!disabled && Events[EventServerChange] == null) || Type.Equals("password", StringComparison.OrdinalIgnoreCase)) { ViewState.SetItemDirty("value", false); } } protected override void RenderAttributes(HtmlTextWriter writer) { base.RenderAttributes(writer); if (Page != null) { Page.ClientScript.RegisterForEventValidation(RenderedNameAttribute); } } /* * Method of IPostBackDataHandler interface to process posted data. * InputText process a newly posted value. */ /// <internalonly/> /// <devdoc> /// </devdoc> bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection) { return LoadPostData(postDataKey, postCollection); } /// <internalonly/> /// <devdoc> /// </devdoc> protected virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) { string current = Value; string inputString = postCollection.GetValues(postDataKey)[0]; if (!current.Equals(inputString)) { ValidateEvent(postDataKey); Value = inputString; return true; } return false; } /* * Method of IPostBackDataHandler interface which is invoked whenever posted data * for a control has changed. InputText fires an OnServerChange event. */ /// <internalonly/> /// <devdoc> /// </devdoc> void IPostBackDataHandler.RaisePostDataChangedEvent() { RaisePostDataChangedEvent(); } /// <internalonly/> /// <devdoc> /// </devdoc> protected virtual void RaisePostDataChangedEvent() { OnServerChange(EventArgs.Empty); } } }
// 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 represents settings specified by de jure or // de facto standards for a particular country/region. In // contrast to CultureInfo, the RegionInfo does not represent // preferences of the user and does not depend on the user's // language or culture. // // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { using System; using System.Runtime.Serialization; using System.Diagnostics.Contracts; #if FEATURE_SERIALIZATION [Serializable] #endif [System.Runtime.InteropServices.ComVisible(true)] public class RegionInfo { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // // // Name of this region (ie: es-US): serialized, the field used for deserialization // internal String m_name; // // The CultureData instance that we are going to read data from. // [NonSerialized]internal CultureData m_cultureData; // // The RegionInfo for our current region // internal static volatile RegionInfo s_currentRegionInfo; //////////////////////////////////////////////////////////////////////// // // RegionInfo Constructors // // Note: We prefer that a region be created with a full culture name (ie: en-US) // because otherwise the native strings won't be right. // // In Silverlight we enforce that RegionInfos must be created with a full culture name // //////////////////////////////////////////////////////////////////////// [System.Security.SecuritySafeCritical] // auto-generated public RegionInfo(String name) { if (name==null) throw new ArgumentNullException("name"); if (name.Length == 0) //The InvariantCulture has no matching region { throw new ArgumentException(Environment.GetResourceString("Argument_NoRegionInvariantCulture"), "name"); } Contract.EndContractBlock(); // // First try it as an entire culture. We must have user override as true here so // that we can pick up custom cultures *before* built-in ones (if they want to // prefer built-in cultures they will pass "us" instead of "en-US"). // this.m_cultureData = CultureData.GetCultureDataForRegion(name,true); // this.m_name = name.ToUpper(CultureInfo.InvariantCulture); if (this.m_cultureData == null) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_InvalidCultureName"), name), "name"); // Not supposed to be neutral if (this.m_cultureData.IsNeutralCulture) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNeutralRegionName", name), "name"); SetName(name); } #if FEATURE_USE_LCID // We'd rather people use the named version since this doesn't allow custom locales [System.Security.SecuritySafeCritical] // auto-generated public RegionInfo(int culture) { if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region { throw new ArgumentException(Environment.GetResourceString("Argument_NoRegionInvariantCulture")); } if (culture == CultureInfo.LOCALE_NEUTRAL) { // Not supposed to be neutral throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), "culture"); } if (culture == CultureInfo.LOCALE_CUSTOM_DEFAULT) { // Not supposed to be neutral throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", culture), "culture"); } this.m_cultureData = CultureData.GetCultureData(culture,true); this.m_name = this.m_cultureData.SREGIONNAME; if (this.m_cultureData.IsNeutralCulture) { // Not supposed to be neutral throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), "culture"); } m_cultureId = culture; } #endif [System.Security.SecuritySafeCritical] // auto-generated internal RegionInfo(CultureData cultureData) { this.m_cultureData = cultureData; this.m_name = this.m_cultureData.SREGIONNAME; } [System.Security.SecurityCritical] // auto-generated private void SetName(string name) { #if FEATURE_CORECLR // Use the name of the region we found this.m_name = this.m_cultureData.SREGIONNAME; #else // when creating region by culture name, we keep the region name as the culture name so regions // created by custom culture names can be differentiated from built in regions. this.m_name = name.Equals(this.m_cultureData.SREGIONNAME, StringComparison.OrdinalIgnoreCase) ? this.m_cultureData.SREGIONNAME : this.m_cultureData.CultureName; #endif // FEATURE_CORECLR } #region Serialization // // m_cultureId is needed for serialization only to detect the case if the region info is created using the name or using the LCID. // in case m_cultureId is zero means that the RigionInfo is created using name. otherwise it is created using LCID. // [OptionalField(VersionAdded = 2)] int m_cultureId; // the following field is defined to keep the compatibility with Everett. // don't change/remove the names/types of these field. [OptionalField(VersionAdded = 2)] internal int m_dataItem = 0; #if !FEATURE_CORECLR static private readonly int[] IdFromEverettRegionInfoDataItem = { 0x3801, /* 0 */ // AE ar-AE Arabic (U.A.E.) 0x041C, /* 1 */ // AL sq-AL Albanian (Albania) 0x042B, /* 2 */ // AM hy-AM Armenian (Armenia) 0x2C0A, /* 3 */ // AR es-AR Spanish (Argentina) 0x0C07, /* 4 */ // AT de-AT German (Austria) 0x0C09, /* 5 */ // AU en-AU English (Australia) 0x042C, /* 6 */ // AZ az-AZ-Latn Azeri (Latin) (Azerbaijan) // 0x082C, 6, // AZ az-AZ-Cyrl Azeri (Cyrillic) (Azerbaijan) 0x080C, /* 7 */ // BE fr-BE French (Belgium) // 0x0813, 7, // BE nl-BE Dutch (Belgium) 0x0402, /* 8 */ // BG bg-BG Bulgarian (Bulgaria) 0x3C01, /* 9 */ // BH ar-BH Arabic (Bahrain) 0x083E, /* 10 */ // BN ms-BN Malay (Brunei Darussalam) 0x400A, /* 11 */ // BO es-BO Spanish (Bolivia) 0x0416, /* 12 */ // BR pt-BR Portuguese (Brazil) 0x0423, /* 13 */ // BY be-BY Belarusian (Belarus) 0x2809, /* 14 */ // BZ en-BZ English (Belize) 0x0C0C, /* 15 */ // CA fr-CA French (Canada) // 0x1009, 15, // CA en-CA English (Canada) 0x2409, /* 16 */ // CB en-CB English (Caribbean) 0x0807, /* 17 */ // CH de-CH German (Switzerland) // 0x0810, 17, // CH it-CH Italian (Switzerland) // 0x100C, 17, // CH fr-CH French (Switzerland) 0x340A, /* 18 */ // CL es-CL Spanish (Chile) 0x0804, /* 19 */ // CN zh-CN Chinese (People's Republic of China) 0x240A, /* 20 */ // CO es-CO Spanish (Colombia) 0x140A, /* 21 */ // CR es-CR Spanish (Costa Rica) 0x0405, /* 22 */ // CZ cs-CZ Czech (Czech Republic) 0x0407, /* 23 */ // DE de-DE German (Germany) 0x0406, /* 24 */ // DK da-DK Danish (Denmark) 0x1C0A, /* 25 */ // DO es-DO Spanish (Dominican Republic) 0x1401, /* 26 */ // DZ ar-DZ Arabic (Algeria) 0x300A, /* 27 */ // EC es-EC Spanish (Ecuador) 0x0425, /* 28 */ // EE et-EE Estonian (Estonia) 0x0C01, /* 29 */ // EG ar-EG Arabic (Egypt) 0x0403, /* 30 */ // ES ca-ES Catalan (Catalan) // 0x042D, 30, // ES eu-ES Basque (Basque) // 0x0456, 30, // ES gl-ES Galician (Galician) // 0x0C0A, 30, // ES es-ES Spanish (Spain) 0x040B, /* 31 */ // FI fi-FI Finnish (Finland) // 0x081D, 31, // FI sv-FI Swedish (Finland) 0x0438, /* 32 */ // FO fo-FO Faroese (Faroe Islands) 0x040C, /* 33 */ // FR fr-FR French (France) 0x0809, /* 34 */ // GB en-GB English (United Kingdom) 0x0437, /* 35 */ // GE ka-GE Georgian (Georgia) 0x0408, /* 36 */ // GR el-GR Greek (Greece) 0x100A, /* 37 */ // GT es-GT Spanish (Guatemala) 0x0C04, /* 38 */ // HK zh-HK Chinese (Hong Kong S.A.R.) 0x480A, /* 39 */ // HN es-HN Spanish (Honduras) 0x041A, /* 40 */ // HR hr-HR Croatian (Croatia) 0x040E, /* 41 */ // HU hu-HU Hungarian (Hungary) 0x0421, /* 42 */ // ID id-ID Indonesian (Indonesia) 0x1809, /* 43 */ // IE en-IE English (Ireland) 0x040D, /* 44 */ // IL he-IL Hebrew (Israel) 0x0439, /* 45 */ // IN hi-IN Hindi (India) // 0x0446, 45, // IN pa-IN Punjabi (India) // 0x0447, 45, // IN gu-IN Gujarati (India) // 0x0449, 45, // IN ta-IN Tamil (India) // 0x044A, 45, // IN te-IN Telugu (India) // 0x044B, 45, // IN kn-IN Kannada (India) // 0x044E, 45, // IN mr-IN Marathi (India) // 0x044F, 45, // IN sa-IN Sanskrit (India) // 0x0457, 45, // IN kok-IN Konkani (India) 0x0801, /* 46 */ // IQ ar-IQ Arabic (Iraq) 0x0429, /* 47 */ // IR fa-IR (Iran) 0x040F, /* 48 */ // IS is-IS Icelandic (Iceland) 0x0410, /* 49 */ // IT it-IT Italian (Italy) 0x2009, /* 50 */ // JM en-JM English (Jamaica) 0x2C01, /* 51 */ // JO ar-JO Arabic (Jordan) 0x0411, /* 52 */ // JP ja-JP Japanese (Japan) 0x0441, /* 53 */ // KE sw-KE Swahili (Kenya) 0x0440, /* 54 */ // KG ky-KG Kyrgyz (Kyrgyzstan) 0x0412, /* 55 */ // KR ko-KR Korean (Korea) 0x3401, /* 56 */ // KW ar-KW Arabic (Kuwait) 0x043F, /* 57 */ // KZ kk-KZ Kazakh (Kazakhstan) 0x3001, /* 58 */ // LB ar-LB Arabic (Lebanon) 0x1407, /* 59 */ // LI de-LI German (Liechtenstein) 0x0427, /* 60 */ // LT lt-LT Lithuanian (Lithuania) 0x1007, /* 61 */ // LU de-LU German (Luxembourg) // 0x140C, 61, // LU fr-LU French (Luxembourg) 0x0426, /* 62 */ // LV lv-LV Latvian (Latvia) 0x1001, /* 63 */ // LY ar-LY Arabic (Libya) 0x1801, /* 64 */ // MA ar-MA Arabic (Morocco) 0x180C, /* 65 */ // MC fr-MC French (Principality of Monaco) 0x042F, /* 66 */ // MK mk-MK Macedonian (Macedonia, FYRO) 0x0450, /* 67 */ // MN mn-MN Mongolian (Mongolia) 0x1404, /* 68 */ // MO zh-MO Chinese (Macau S.A.R.) 0x0465, /* 69 */ // MV div-MV Divehi (Maldives) 0x080A, /* 70 */ // MX es-MX Spanish (Mexico) 0x043E, /* 71 */ // MY ms-MY Malay (Malaysia) 0x4C0A, /* 72 */ // NI es-NI Spanish (Nicaragua) 0x0413, /* 73 */ // NL nl-NL Dutch (Netherlands) 0x0414, /* 74 */ // NO nb-NO Norwegian (Bokm?) (Norway) // 0x0814, 74, // NO nn-NO Norwegian (Nynorsk) (Norway) 0x1409, /* 75 */ // NZ en-NZ English (New Zealand) 0x2001, /* 76 */ // OM ar-OM Arabic (Oman) 0x180A, /* 77 */ // PA es-PA Spanish (Panama) 0x280A, /* 78 */ // PE es-PE Spanish (Peru) 0x3409, /* 79 */ // PH en-PH English (Republic of the Philippines) 0x0420, /* 80 */ // PK ur-PK Urdu (Islamic Republic of Pakistan) 0x0415, /* 81 */ // PL pl-PL Polish (Poland) 0x500A, /* 82 */ // PR es-PR Spanish (Puerto Rico) 0x0816, /* 83 */ // PT pt-PT Portuguese (Portugal) 0x3C0A, /* 84 */ // PY es-PY Spanish (Paraguay) 0x4001, /* 85 */ // QA ar-QA Arabic (Qatar) 0x0418, /* 86 */ // RO ro-RO Romanian (Romania) 0x0419, /* 87 */ // RU ru-RU Russian (Russia) // 0x0444, 87, // RU tt-RU Tatar (Russia) 0x0401, /* 88 */ // SA ar-SA Arabic (Saudi Arabia) 0x041D, /* 89 */ // SE sv-SE Swedish (Sweden) 0x1004, /* 90 */ // SG zh-SG Chinese (Singapore) 0x0424, /* 91 */ // SI sl-SI Slovenian (Slovenia) 0x041B, /* 92 */ // SK sk-SK Slovak (Slovakia) 0x081A, /* 93 */ // SP sr-SP-Latn Serbian (Latin) (Serbia) // 0x0C1A, 93, // SP sr-SP-Cyrl Serbian (Cyrillic) (Serbia) 0x440A, /* 94 */ // SV es-SV Spanish (El Salvador) 0x045A, /* 95 */ // SY syr-SY Syriac (Syria) // 0x2801, 95, // SY ar-SY Arabic (Syria) 0x041E, /* 96 */ // TH th-TH Thai (Thailand) 0x1C01, /* 97 */ // TN ar-TN Arabic (Tunisia) 0x041F, /* 98 */ // TR tr-TR Turkish (Turkey) 0x2C09, /* 99 */ // TT en-TT English (Trinidad and Tobago) 0x0404, /*100 */ // TW zh-TW Chinese (Taiwan) 0x0422, /*101 */ // UA uk-UA Ukrainian (Ukraine) 0x0409, /*102 */ // US en-US English (United States) 0x380A, /*103 */ // UY es-UY Spanish (Uruguay) 0x0443, /*104 */ // UZ uz-UZ-Latn Uzbek (Latin) (Uzbekistan) // 0x0843, 104 // UZ uz-UZ-Cyrl Uzbek (Cyrillic) (Uzbekistan) 0x200A, /*105*/ // VE es-VE Spanish (Venezuela) 0x042A, /*106*/ // VN vi-VN Vietnamese (Viet Nam) 0x2401, /*107*/ // YE ar-YE Arabic (Yemen) 0x0436, /*108*/ // ZA af-ZA Afrikaans (South Africa) // 0x1C09, 108, // ZA en-ZA English (South Africa) 0x3009, /*109*/ // ZW en-ZW English (Zimbabwe) }; #endif [System.Security.SecurityCritical] // auto-generated [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { #if FEATURE_CORECLR // This won't happen anyway since CoreCLR doesn't support serialization this.m_cultureData = CultureData.GetCultureData(m_name, true); #else if (m_name == null) { Contract.Assert(m_dataItem >= 0, "[RegionInfo.OnDeserialized] null name and invalid dataItem"); m_cultureId = IdFromEverettRegionInfoDataItem[m_dataItem]; } if (m_cultureId == 0) { this.m_cultureData = CultureData.GetCultureDataForRegion(this.m_name, true); } else { this.m_cultureData = CultureData.GetCultureData(m_cultureId, true); } #endif if (this.m_cultureData == null) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_InvalidCultureName"), m_name), "m_name"); if (m_cultureId == 0) { SetName(this.m_name); } else { this.m_name = this.m_cultureData.SREGIONNAME; } } [OnSerializing] private void OnSerializing(StreamingContext ctx) { // Used to fill in everett data item, unnecessary now } #endregion Serialization //////////////////////////////////////////////////////////////////////// // // GetCurrentRegion // // This instance provides methods based on the current user settings. // These settings are volatile and may change over the lifetime of the // thread. // //////////////////////////////////////////////////////////////////////// public static RegionInfo CurrentRegion { [System.Security.SecuritySafeCritical] // auto-generated get { RegionInfo temp = s_currentRegionInfo; if (temp == null) { temp = new RegionInfo(CultureInfo.CurrentCulture.m_cultureData); // Need full name for custom cultures temp.m_name=temp.m_cultureData.SREGIONNAME; s_currentRegionInfo = temp; } return temp; } } //////////////////////////////////////////////////////////////////////// // // GetName // // Returns the name of the region (ie: en-US) // //////////////////////////////////////////////////////////////////////// public virtual String Name { get { Contract.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already"); return (m_name); } } //////////////////////////////////////////////////////////////////////// // // GetEnglishName // // Returns the name of the region in English. (ie: United States) // //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SENGCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetDisplayName // // Returns the display name (localized) of the region. (ie: United States // if the current UI language is en-US) // //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SLOCALIZEDCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetNativeName // // Returns the native name of the region. (ie: Deutschland) // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public virtual String NativeName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SNATIVECOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // TwoLetterISORegionName // // Returns the two letter ISO region name (ie: US) // //////////////////////////////////////////////////////////////////////// public virtual String TwoLetterISORegionName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SISO3166CTRYNAME); } } #if !FEATURE_CORECLR //////////////////////////////////////////////////////////////////////// // // ThreeLetterISORegionName // // Returns the three letter ISO region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterISORegionName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SISO3166CTRYNAME2); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterWindowsRegionName // // Returns the three letter windows region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterWindowsRegionName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SABBREVCTRYNAME); } } #endif //////////////////////////////////////////////////////////////////////// // // IsMetric // // Returns true if this region uses the metric measurement system // //////////////////////////////////////////////////////////////////////// public virtual bool IsMetric { get { int value = this.m_cultureData.IMEASURE; return (value==0); } } [System.Runtime.InteropServices.ComVisible(false)] public virtual int GeoId { get { return (this.m_cultureData.IGEOID); } } //////////////////////////////////////////////////////////////////////// // // CurrencyEnglishName // // English name for this region's currency, ie: Swiss Franc // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public virtual String CurrencyEnglishName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SENGLISHCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencyEnglishName // // English name for this region's currency, ie: Schweizer Franken // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public virtual String CurrencyNativeName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SNATIVECURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencySymbol // // Currency Symbol for this locale, ie: Fr. or $ // //////////////////////////////////////////////////////////////////////// public virtual String CurrencySymbol { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // ISOCurrencySymbol // // ISO Currency Symbol for this locale, ie: CHF // //////////////////////////////////////////////////////////////////////// public virtual String ISOCurrencySymbol { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SINTLSYMBOL); } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same RegionInfo as the current instance. // // RegionInfos are considered equal if and only if they have the same name // (ie: en-US) // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { RegionInfo that = value as RegionInfo; if (that != null) { return this.Name.Equals(that.Name); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for RegionInfo // A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns the name of the Region, ie: es-US // //////////////////////////////////////////////////////////////////////// public override String ToString() { return (Name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogicalInt321() { var test = new ImmUnaryOpTest__ShiftRightLogicalInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalInt321 { private struct TestStruct { public Vector128<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt321 testClass) { var result = Sse2.ShiftRightLogical(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector128<Int32> _clsVar; private Vector128<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static ImmUnaryOpTest__ShiftRightLogicalInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ImmUnaryOpTest__ShiftRightLogicalInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.ShiftRightLogical( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ShiftRightLogical( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ShiftRightLogical( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ShiftRightLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Sse2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalInt321(); var result = Sse2.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ShiftRightLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((int)(firstOp[0] >> 1) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((int)(firstOp[i] >> 1) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<Int32>(Vector128<Int32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. //using System; using System.Collections.Generic; using Sharpen; namespace Couchbase.Lite.Util { /// <summary> /// BEGIN LAYOUTLIB CHANGE /// This is a custom version that doesn't use the non standard LinkedHashMap#eldest. /// </summary> /// <remarks> /// BEGIN LAYOUTLIB CHANGE /// This is a custom version that doesn't use the non standard LinkedHashMap#eldest. /// END LAYOUTLIB CHANGE /// A cache that holds strong references to a limited number of values. Each time /// a value is accessed, it is moved to the head of a queue. When a value is /// added to a full cache, the value at the end of that queue is evicted and may /// become eligible for garbage collection. /// <p>If your cached values hold resources that need to be explicitly released, /// override /// <see cref="LruCache{K, V}.EntryRemoved(bool, object, object, object)">LruCache&lt;K, V&gt;.EntryRemoved(bool, object, object, object) /// </see> /// . /// <p>If a cache miss should be computed on demand for the corresponding keys, /// override /// <see cref="LruCache{K, V}.Create(object)">LruCache&lt;K, V&gt;.Create(object)</see> /// . This simplifies the calling code, allowing it to /// assume a value will always be returned, even when there's a cache miss. /// <p>By default, the cache size is measured in the number of entries. Override /// <see cref="LruCache{K, V}.SizeOf(object, object)">LruCache&lt;K, V&gt;.SizeOf(object, object) /// </see> /// to size the cache in different units. For example, this cache /// is limited to 4MiB of bitmaps: /// <pre> /// <code>int cacheSize = 4 * 1024 * 1024; // 4MiB</code> /// LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) /// protected int sizeOf(String key, Bitmap value) { /// return value.getByteCount(); /// } /// }}</pre> /// <p>This class is thread-safe. Perform multiple cache operations atomically by /// synchronizing on the cache: <pre> /// <code></code> /// synchronized (cache) /// if (cache.get(key) == null) { /// cache.put(key, value); /// } /// }}</pre> /// <p>This class does not allow null to be used as a key or value. A return /// value of null from /// <see cref="LruCache{K, V}.Get(object)">LruCache&lt;K, V&gt;.Get(object)</see> /// , /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// or /// <see cref="LruCache{K, V}.Remove(object)">LruCache&lt;K, V&gt;.Remove(object)</see> /// is /// unambiguous: the key was not in the cache. /// <p>This class appeared in Android 3.1 (Honeycomb MR1); it's available as part /// of <a href="http://developer.android.com/sdk/compatibility-library.html">Android's /// Support Package</a> for earlier releases. /// </remarks> public class LruCache<K, V> { private readonly LinkedHashMap<K, V> map; /// <summary>Size of this cache in units.</summary> /// <remarks>Size of this cache in units. Not necessarily the number of elements.</remarks> private int size; private int maxSize; private int putCount; private int createCount; private int evictionCount; private int hitCount; private int missCount; /// <param name="maxSize"> /// for caches that do not override /// <see cref="LruCache{K, V}.SizeOf(object, object)">LruCache&lt;K, V&gt;.SizeOf(object, object) /// </see> /// , this is /// the maximum number of entries in the cache. For all other caches, /// this is the maximum sum of the sizes of the entries in this cache. /// </param> public LruCache(int maxSize) { // COPY: Copied from android.util.LruCache if (maxSize <= 0) { throw new ArgumentException("maxSize <= 0"); } this.maxSize = maxSize; this.map = new LinkedHashMap<K, V>(0, 0.75f, true); } /// <summary>Sets the size of the cache.</summary> /// <remarks>Sets the size of the cache.</remarks> /// <param name="maxSize">The new maximum size.</param> /// <hide></hide> public virtual void Resize(int maxSize) { if (maxSize <= 0) { throw new ArgumentException("maxSize <= 0"); } lock (this) { this.maxSize = maxSize; } TrimToSize(maxSize); } /// <summary> /// Returns the value for /// <code>key</code> /// if it exists in the cache or can be /// created by /// <code>#create</code> /// . If a value was returned, it is moved to the /// head of the queue. This returns null if a value is not cached and cannot /// be created. /// </summary> public V Get(K key) { if (key == null) { throw new ArgumentNullException("key == null"); } V mapValue; lock (this) { mapValue = map.Get(key); if (mapValue != null) { hitCount++; return mapValue; } missCount++; } V createdValue = Create(key); if (createdValue == null) { return null; } lock (this) { createCount++; mapValue = map.Put(key, createdValue); if (mapValue != null) { // There was a conflict so undo that last put map.Put(key, mapValue); } else { size += SafeSizeOf(key, createdValue); } } if (mapValue != null) { EntryRemoved(false, key, createdValue, mapValue); return mapValue; } else { TrimToSize(maxSize); return createdValue; } } /// <summary> /// Caches /// <code>value</code> /// for /// <code>key</code> /// . The value is moved to the head of /// the queue. /// </summary> /// <returns> /// the previous value mapped by /// <code>key</code> /// . /// </returns> public V Put(K key, V value) { if (key == null || value == null) { throw new ArgumentNullException("key == null || value == null"); } V previous; lock (this) { putCount++; size += SafeSizeOf(key, value); previous = map.Put(key, value); if (previous != null) { size -= SafeSizeOf(key, previous); } } if (previous != null) { EntryRemoved(false, key, previous, value); } TrimToSize(maxSize); return previous; } /// <param name="maxSize"> /// the maximum size of the cache before returning. May be -1 /// to evict even 0-sized elements. /// </param> private void TrimToSize(int maxSize) { while (true) { K key; V value; lock (this) { if (size < 0 || (map.IsEmpty() && size != 0)) { throw new InvalidOperationException(GetType().FullName + ".sizeOf() is reporting inconsistent results!" ); } if (size <= maxSize) { break; } // BEGIN LAYOUTLIB CHANGE // get the last item in the linked list. // This is not efficient, the goal here is to minimize the changes // compared to the platform version. KeyValuePair<K, V> toEvict = null; foreach (KeyValuePair<K, V> entry in map.EntrySet()) { toEvict = entry; } // END LAYOUTLIB CHANGE if (toEvict == null) { break; } key = toEvict.Key; value = toEvict.Value; Sharpen.Collections.Remove(map, key); size -= SafeSizeOf(key, value); evictionCount++; } EntryRemoved(true, key, value, null); } } /// <summary> /// Removes the entry for /// <code>key</code> /// if it exists. /// </summary> /// <returns> /// the previous value mapped by /// <code>key</code> /// . /// </returns> public V Remove(K key) { if (key == null) { throw new ArgumentNullException("key == null"); } V previous; lock (this) { previous = Sharpen.Collections.Remove(map, key); if (previous != null) { size -= SafeSizeOf(key, previous); } } if (previous != null) { EntryRemoved(false, key, previous, null); } return previous; } /// <summary>Called for entries that have been evicted or removed.</summary> /// <remarks> /// Called for entries that have been evicted or removed. This method is /// invoked when a value is evicted to make space, removed by a call to /// <see cref="LruCache{K, V}.Remove(object)">LruCache&lt;K, V&gt;.Remove(object)</see> /// , or replaced by a call to /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// . The default /// implementation does nothing. /// <p>The method is called without synchronization: other threads may /// access the cache while this method is executing. /// </remarks> /// <param name="evicted"> /// true if the entry is being removed to make space, false /// if the removal was caused by a /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// or /// <see cref="LruCache{K, V}.Remove(object)">LruCache&lt;K, V&gt;.Remove(object)</see> /// . /// </param> /// <param name="newValue"> /// the new value for /// <code>key</code> /// , if it exists. If non-null, /// this removal was caused by a /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// . Otherwise it was caused by /// an eviction or a /// <see cref="LruCache{K, V}.Remove(object)">LruCache&lt;K, V&gt;.Remove(object)</see> /// . /// </param> protected internal virtual void EntryRemoved(bool evicted, K key, V oldValue, V newValue ) { } /// <summary>Called after a cache miss to compute a value for the corresponding key.</summary> /// <remarks> /// Called after a cache miss to compute a value for the corresponding key. /// Returns the computed value or null if no value can be computed. The /// default implementation returns null. /// <p>The method is called without synchronization: other threads may /// access the cache while this method is executing. /// <p>If a value for /// <code>key</code> /// exists in the cache when this method /// returns, the created value will be released with /// <see cref="LruCache{K, V}.EntryRemoved(bool, object, object, object)">LruCache&lt;K, V&gt;.EntryRemoved(bool, object, object, object) /// </see> /// and discarded. This can occur when multiple threads request the same key /// at the same time (causing multiple values to be created), or when one /// thread calls /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// while another is creating a value for the same /// key. /// </remarks> protected internal virtual V Create(K key) { return null; } private int SafeSizeOf(K key, V value) { int result = SizeOf(key, value); if (result < 0) { throw new InvalidOperationException("Negative size: " + key + "=" + value); } return result; } /// <summary> /// Returns the size of the entry for /// <code>key</code> /// and /// <code>value</code> /// in /// user-defined units. The default implementation returns 1 so that size /// is the number of entries and max size is the maximum number of entries. /// <p>An entry's size must not change while it is in the cache. /// </summary> protected internal virtual int SizeOf(K key, V value) { return 1; } /// <summary> /// Clear the cache, calling /// <see cref="LruCache{K, V}.EntryRemoved(bool, object, object, object)">LruCache&lt;K, V&gt;.EntryRemoved(bool, object, object, object) /// </see> /// on each removed entry. /// </summary> public void EvictAll() { TrimToSize(-1); } // -1 will evict 0-sized elements /// <summary> /// For caches that do not override /// <see cref="LruCache{K, V}.SizeOf(object, object)">LruCache&lt;K, V&gt;.SizeOf(object, object) /// </see> /// , this returns the number /// of entries in the cache. For all other caches, this returns the sum of /// the sizes of the entries in this cache. /// </summary> public int Size() { lock (this) { return size; } } /// <summary> /// For caches that do not override /// <see cref="LruCache{K, V}.SizeOf(object, object)">LruCache&lt;K, V&gt;.SizeOf(object, object) /// </see> /// , this returns the maximum /// number of entries in the cache. For all other caches, this returns the /// maximum sum of the sizes of the entries in this cache. /// </summary> public int MaxSize() { lock (this) { return maxSize; } } /// <summary> /// Returns the number of times /// <see cref="LruCache{K, V}.Get(object)">LruCache&lt;K, V&gt;.Get(object)</see> /// returned a value that was /// already present in the cache. /// </summary> public int HitCount() { lock (this) { return hitCount; } } /// <summary> /// Returns the number of times /// <see cref="LruCache{K, V}.Get(object)">LruCache&lt;K, V&gt;.Get(object)</see> /// returned null or required a new /// value to be created. /// </summary> public int MissCount() { lock (this) { return missCount; } } /// <summary> /// Returns the number of times /// <see cref="LruCache{K, V}.Create(object)">LruCache&lt;K, V&gt;.Create(object)</see> /// returned a value. /// </summary> public int CreateCount() { lock (this) { return createCount; } } /// <summary> /// Returns the number of times /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// was called. /// </summary> public int PutCount() { lock (this) { return putCount; } } /// <summary>Returns the number of values that have been evicted.</summary> /// <remarks>Returns the number of values that have been evicted.</remarks> public int EvictionCount() { lock (this) { return evictionCount; } } /// <summary> /// Returns a copy of the current contents of the cache, ordered from least /// recently accessed to most recently accessed. /// </summary> /// <remarks> /// Returns a copy of the current contents of the cache, ordered from least /// recently accessed to most recently accessed. /// </remarks> public IDictionary<K, V> Snapshot() { lock (this) { return new LinkedHashMap<K, V>(map); } } public sealed override string ToString() { lock (this) { int accesses = hitCount + missCount; int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0; return string.Format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]", maxSize , hitCount, missCount, hitPercent); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CocosSharp; namespace tests { public class BaseDrawNodeTest : TestNavigationLayer { #region Properties public override string Title { get { return "Draw Demo"; } } #endregion Properties #region Constructors public BaseDrawNodeTest() { } #endregion Constructors #region Setup content public virtual void Setup() { } #endregion Setup content #region Callbacks public override void RestartCallback(object sender) { CCScene s = new DrawPrimitivesTestScene(); s.AddChild(DrawPrimitivesTestScene.restartTestAction()); Director.ReplaceScene(s); } public override void NextCallback(object sender) { CCScene s = new DrawPrimitivesTestScene(); s.AddChild(DrawPrimitivesTestScene.nextTestAction()); Director.ReplaceScene(s); } public override void BackCallback(object sender) { CCScene s = new DrawPrimitivesTestScene(); s.AddChild(DrawPrimitivesTestScene.backTestAction()); Director.ReplaceScene(s); } #endregion Callbacks } public class DrawNodeWithRenderTextureTest : BaseDrawNodeTest { #region Setup content public override string Subtitle { get { return "RenderTarget CCDrawNode Visit"; } } public override void OnEnter() { base.OnEnter(); var windowSize = Layer.VisibleBoundsWorldspace.Size; CCRenderTexture text = new CCRenderTexture(windowSize,windowSize); text.Sprite.Position = windowSize.Center; AddChild(text.Sprite, 24); CCDrawNode draw = new CCDrawNode(); // Draw polygons CCPoint[] points = new CCPoint[] { new CCPoint(windowSize.Height / 4, 0), new CCPoint(windowSize.Width, windowSize.Height / 5), new CCPoint(windowSize.Width / 3 * 2, windowSize.Height) }; draw.DrawPolygon(points, points.Length, new CCColor4F(1, 0, 0, 0.5f), 4, new CCColor4F(0, 0, 1, 1)); draw.AnchorPoint = CCPoint.AnchorLowerLeft; text.Begin(); draw.Visit(); text.End(); } #endregion Setup content } public class DrawNodeWithRenderTextureTest1 : BaseDrawNodeTest { #region Setup content public override string Subtitle { get { return "Test RenderTarget Clipping with CCDrawNode as Child"; } } public override void OnEnter() { base.OnEnter(); CCDrawNode circle = new CCDrawNode(); circle.DrawSolidCircle(new CCPoint(150.0f, 150.0f), 75.0f, new CCColor4B(255, 255, 255, 255)); CCRenderTexture rtm = new CCRenderTexture(new CCSize(200.0f, 200.0f), new CCSize(200.0f, 200.0f), CCSurfaceFormat.Color, CCDepthFormat.Depth24Stencil8); rtm.BeginWithClear(CCColor4B.Orange); circle.Visit(); rtm.End(); // Make sure our children nodes get visited rtm.Sprite.Position = VisibleBoundsWorldspace.Center; rtm.Sprite.AnchorPoint = CCPoint.AnchorMiddle; AddChild(rtm.Sprite); } #endregion Setup content } public class DrawNodeWithRenderTextureTest2 : BaseDrawNodeTest { #region Setup content public override string Subtitle { get { return "Test RenderTarget Clipping with CCDrawNode Visit"; } } public override void OnEnter() { base.OnEnter(); CCDrawNode circle = new CCDrawNode(); circle.DrawSolidCircle(new CCPoint(150.0f, 150.0f), 75.0f, new CCColor4B(255, 255, 255, 255)); CCRenderTexture rtm = new CCRenderTexture(new CCSize(200.0f, 200.0f), new CCSize(200.0f, 200.0f), CCSurfaceFormat.Color, CCDepthFormat.Depth24Stencil8); rtm.BeginWithClear(CCColor4B.Orange); circle.Visit(); // Draw to rendertarget rtm.End(); rtm.Sprite.Position = VisibleBoundsWorldspace.Center; rtm.Sprite.AnchorPoint = CCPoint.AnchorMiddle; var sprite = rtm.Sprite; sprite.AnchorPoint = CCPoint.AnchorMiddle; sprite.Position = VisibleBoundsWorldspace.Center; AddChild(sprite); } #endregion Setup content } public class DrawNodeWithRenderTextureTest3 : BaseDrawNodeTest { #region Setup content public override string Subtitle { get { return "Test RenderTarget Clipping with CCDrawNode Visit to Sprite"; } } public override void OnEnter() { base.OnEnter(); CCDrawNode circle = new CCDrawNode(); circle.DrawSolidCircle(new CCPoint(150.0f, 150.0f), 75.0f, new CCColor4B(255, 255, 255, 255)); CCRenderTexture rtm = new CCRenderTexture(new CCSize(200.0f, 200.0f), new CCSize(200.0f, 200.0f), CCSurfaceFormat.Color, CCDepthFormat.Depth24Stencil8); rtm.BeginWithClear(CCColor4B.Orange); circle.Visit(); // Draw to rendertarget rtm.End(); // Create a new sprite from the render target texture var sprite = new CCSprite(rtm.Texture); sprite.Position = VisibleBoundsWorldspace.Center; AddChild(sprite); } #endregion Setup content } public class DrawPrimitivesTest : BaseDrawNodeTest { protected override void VisitRenderer(ref CCAffineTransform worldTransform) { Renderer.AddCommand(new CCCustomCommand(worldTransform.Tz, worldTransform, RenderDrawPrimTest)); } void RenderDrawPrimTest() { CCSize size = Layer.VisibleBoundsWorldspace.Size; var visibleRect = VisibleBoundsWorldspace; CCDrawingPrimitives.Begin(); // *NOTE* Using the Director.ContentScaleFactor for now until we work something out with the initialization // CCDrawPriitives should be able to do this converstion themselves. // draw a simple line // The default state is: // Line Width: 1 // color: 255,255,255,255 (white, non-transparent) // Anti-Aliased // glEnable(GL_LINE_SMOOTH); CCDrawingPrimitives.LineWidth = 1 ; CCDrawingPrimitives.DrawLine(visibleRect.LeftBottom(), visibleRect.RightTop()); // line: color, width, aliased CCDrawingPrimitives.LineWidth = 5 ; CCDrawingPrimitives.DrawColor = CCColor4B.Red; CCDrawingPrimitives.DrawLine(visibleRect.LeftTop(), visibleRect.RightBottom()); // TIP: // If you are going to use always thde same color or width, you don't // need to call it before every draw // // draw big point in the center CCDrawingPrimitives.PointSize = 64 ; CCDrawingPrimitives.DrawColor = new CCColor4B(0, 0, 255, 128); CCDrawingPrimitives.DrawPoint(visibleRect.Center()); // draw 4 small points CCPoint[] points = {new CCPoint(60, 60), new CCPoint(70, 70), new CCPoint(60, 70), new CCPoint(70, 60)}; CCDrawingPrimitives.PointSize = 8 ; CCDrawingPrimitives.DrawColor = new CCColor4B(0, 255, 255, 255); CCDrawingPrimitives.DrawPoints(points); // draw a green circle with 10 segments CCDrawingPrimitives.LineWidth = 16 ; CCDrawingPrimitives.DrawColor = CCColor4B.Green; CCDrawingPrimitives.DrawCircle(visibleRect.Center, 100, 0, 10, false); // draw a green circle with 50 segments with line to center CCDrawingPrimitives.LineWidth = 2 ; CCDrawingPrimitives.DrawColor = new CCColor4B(0, 255, 255, 255); CCDrawingPrimitives.DrawCircle(visibleRect.Center, 50, CCMacros.CCDegreesToRadians(45), 50, true); // draw a pink solid circle with 50 segments CCDrawingPrimitives.LineWidth = 2 ; CCDrawingPrimitives.DrawColor = new CCColor4B(255, 0, 255, 255); CCDrawingPrimitives.DrawSolidCircle(visibleRect.Center + new CCPoint(140, 0), 40, CCMacros.CCDegreesToRadians(90), 50); // draw an arc within rectangular region CCDrawingPrimitives.LineWidth = 5 ; CCDrawingPrimitives.DrawArc(new CCRect(200, 100, 100, 200), 0, 180, CCColor4B.AliceBlue); // draw an ellipse within rectangular region CCDrawingPrimitives.DrawEllipse(new CCRect(100, 100, 100, 200), CCColor4B.Red); // draw an arc within rectangular region CCDrawingPrimitives.DrawPie(new CCRect(350, 0, 100, 100), 20, 100, CCColor4B.AliceBlue); // draw an arc within rectangular region CCDrawingPrimitives.DrawPie(new CCRect(347, -5, 100, 100), 120, 260, CCColor4B.Aquamarine); // open yellow poly CCPoint[] vertices = { new CCPoint(0, 0), new CCPoint(50, 50), new CCPoint(100, 50), new CCPoint(100, 100), new CCPoint(50, 100) }; CCDrawingPrimitives.LineWidth = 10 ; CCDrawingPrimitives.DrawColor = CCColor4B.Yellow; CCDrawingPrimitives.DrawPoly(vertices, 5, false, new CCColor4B(255, 255, 0, 255)); // filled poly CCDrawingPrimitives.LineWidth = 1 ; CCPoint[] filledVertices = { new CCPoint(0, 120), new CCPoint(50, 120), new CCPoint(50, 170), new CCPoint(25, 200), new CCPoint(0, 170) }; CCDrawingPrimitives.DrawSolidPoly(filledVertices, new CCColor4F(0.5f, 0.5f, 1, 1 )); // closed purple poly CCDrawingPrimitives.LineWidth = 2 ; CCDrawingPrimitives.DrawColor = new CCColor4B(255, 0, 255, 255); CCPoint[] vertices2 = {new CCPoint(30, 130), new CCPoint(30, 230), new CCPoint(50, 200)}; CCDrawingPrimitives.DrawPoly(vertices2, true); // draw quad bezier path CCDrawingPrimitives.DrawQuadBezier(new CCPoint(0, size.Height), visibleRect.Center, (CCPoint)visibleRect.Size, 50, new CCColor4B(255, 0, 255, 255)); // draw cubic bezier path CCDrawingPrimitives.DrawCubicBezier(visibleRect.Center, new CCPoint(size.Width / 2 + 30, size.Height / 2 + 50), new CCPoint(size.Width / 2 + 60, size.Height / 2 - 50), new CCPoint(size.Width, size.Height / 2), 100); //draw a solid polygon CCPoint[] vertices3 = { new CCPoint(60, 160), new CCPoint(70, 190), new CCPoint(100, 190), new CCPoint(90, 160) }; CCDrawingPrimitives.DrawSolidPoly(vertices3, 4, new CCColor4F(1,1,0,1)); CCDrawingPrimitives.End(); } public override string Title { get { return "Draw Primitives"; } } public override string Subtitle { get { return "Drawing Primitives. Use DrawNode instead"; } } } public class GeometryBatchTest1 : BaseDrawNodeTest { CCTexture2D texture; CCGeometryNode geoBatch; public GeometryBatchTest1 () : base() { texture = CCTextureCache.SharedTextureCache.AddImage("Images/CyanSquare.png"); //texture = CCTextureCache.SharedTextureCache.AddImage("Images/BackGround.png"); } protected override void AddedToScene() { base.AddedToScene(); CreateGeom(); } void CreateGeom() { geoBatch = new CCGeometryNode(); AddChild(geoBatch); var visibleRect = VisibleBoundsWorldspace; var item = geoBatch.CreateGeometryInstance(3, 3); var vertices = item.GeometryPacket.Vertices; var windowSize = VisibleBoundsWorldspace.Size; var packet = item.GeometryPacket; packet.Texture = texture; item.GeometryPacket = packet; // Draw polygons vertices[0].Colors = CCColor4B.White; vertices[1].Colors = CCColor4B.White; vertices[2].Colors = CCColor4B.White; // Texture coordinates use a normalzed value 0 to 1 vertices[0].TexCoords.U = 0; vertices[0].TexCoords.V = 0; vertices[1].TexCoords.U = 1; vertices[1].TexCoords.V = 0; vertices[2].TexCoords.U = 1; vertices[2].TexCoords.V = 1; vertices[0].Vertices.X = 0; vertices[0].Vertices.Y = 0; vertices[1].Vertices.X = texture.PixelsWide; vertices[1].Vertices.Y = 0; vertices[2].Vertices.X = texture.PixelsWide; vertices[2].Vertices.Y = texture.PixelsHigh; item.GeometryPacket.Indicies = new int[] { 2, 1, 0 }; var rotation = CCAffineTransform.Identity; rotation.Rotation = (float)Math.PI / 4.0f; rotation.Tx = windowSize.Center.X - texture.PixelsWide / 2; rotation.Ty = windowSize.Center.Y - texture.PixelsHigh / 2; item.InstanceAttributes.AdditionalTransform = rotation; } public override string Title { get { return "Geometry Node"; } } public override string Subtitle { get { return "Auto Clear of instances and transform"; } } } public class GeometryBatchTest2 : BaseDrawNodeTest { CCTexture2D texture; CCGeometryNode geoBatch = new CCGeometryNode(); public GeometryBatchTest2 () : base() { texture = CCTextureCache.SharedTextureCache.AddImage("Images/CyanSquare.png"); //texture = CCTextureCache.SharedTextureCache.AddImage("Images/BackGround.png"); AddChild(geoBatch); } protected override void AddedToScene() { base.AddedToScene(); var visibleRect = VisibleBoundsWorldspace; var item = geoBatch.CreateGeometryInstance(3, 3); var vertices = item.GeometryPacket.Vertices; var windowSize = VisibleBoundsWorldspace.Size; var packet = item.GeometryPacket; packet.Texture = texture; item.GeometryPacket = packet; // Draw polygons vertices[0].Colors = CCColor4B.White; vertices[1].Colors = CCColor4B.White; vertices[2].Colors = CCColor4B.White; // Texture coordinates use a normalzed value 0 to 1 vertices[0].TexCoords.U = 0; vertices[0].TexCoords.V = 0; vertices[1].TexCoords.U = 1; vertices[1].TexCoords.V = 0; vertices[2].TexCoords.U = 1; vertices[2].TexCoords.V = 1; vertices[0].Vertices.X = 0; vertices[0].Vertices.Y = 0; vertices[1].Vertices.X = texture.PixelsWide; vertices[1].Vertices.Y = 0; vertices[2].Vertices.X = texture.PixelsWide; vertices[2].Vertices.Y = texture.PixelsHigh; item.GeometryPacket.Indicies = new int[] { 2, 1, 0 }; var rotation = CCAffineTransform.Identity; rotation.Rotation = (float)Math.PI / 4.0f; rotation.Tx = windowSize.Center.X - texture.PixelsWide / 2; rotation.Ty = windowSize.Center.Y - texture.PixelsHigh / 2; item.InstanceAttributes.AdditionalTransform = rotation; } public override void OnExit() { geoBatch.ClearInstances(); base.OnExit(); } public override string Title { get { return "Geometry Batch"; } } public override string Subtitle { get { return "No Auto Clear of instances"; } } } public class DrawNodeTest : BaseDrawNodeTest { #region Setup content CCDrawNode draw; public DrawNodeTest() { draw = new CCDrawNode(); draw.BlendFunc = CCBlendFunc.NonPremultiplied; AddChild(draw, 10); } public override void OnEnter() { base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size; CCDrawNode draw = new CCDrawNode(); AddChild(draw, 10); var s = windowSize; // Draw 10 circles for (int i = 0; i < 10; i++) { draw.DrawSolidCircle(s.Center, 10 * (10 - i), new CCColor4F(CCRandom.Float_0_1(), CCRandom.Float_0_1(), CCRandom.Float_0_1(), 1)); } // Draw polygons CCPoint[] points = new CCPoint[] { new CCPoint(windowSize.Height / 4, 0), new CCPoint(windowSize.Width, windowSize.Height / 5), new CCPoint(windowSize.Width / 3 * 2, windowSize.Height) }; draw.DrawPolygon(points, points.Length, new CCColor4F(1.0f, 0, 0, 0.5f), 4, new CCColor4F(0, 0, 1, 1)); // star poly (triggers buggs) { const float o = 80; const float w = 20; const float h = 50; CCPoint[] star = new CCPoint[] { new CCPoint(o + w, o - h), new CCPoint(o + w * 2, o), // lower spike new CCPoint(o + w * 2 + h, o + w), new CCPoint(o + w * 2, o + w * 2), // right spike }; draw.DrawPolygon(star, star.Length, new CCColor4F(1, 0, 0, 0.5f), 1, new CCColor4F(0, 0, 1, 1)); } // star poly (doesn't trigger bug... order is important un tesselation is supported. { const float o = 180; const float w = 20; const float h = 50; var star = new CCPoint[] { new CCPoint(o, o), new CCPoint(o + w, o - h), new CCPoint(o + w * 2, o), // lower spike new CCPoint(o + w * 2 + h, o + w), new CCPoint(o + w * 2, o + w * 2), // right spike new CCPoint(o + w, o + w * 2 + h), new CCPoint(o, o + w * 2), // top spike new CCPoint(o - h, o + w), // left spike }; draw.DrawPolygon(star, star.Length, new CCColor4F(1, 0, 0, 0.5f), 1, new CCColor4F(0, 0, 1, 1)); } // Draw segment draw.DrawLine(new CCPoint(20, windowSize.Height), new CCPoint(20, windowSize.Height / 2), 10, new CCColor4F(0, 1, 0, 1), CCLineCap.Round); draw.DrawLine(new CCPoint(10, windowSize.Height / 2), new CCPoint(windowSize.Width / 2, windowSize.Height / 2), 40, new CCColor4F(1, 0, 1, 0.5f), CCLineCap.Round); CCSize size = Layer.VisibleBoundsWorldspace.Size; var visibleRect = VisibleBoundsWorldspace; // draw quad bezier path draw.DrawQuadBezier(new CCPoint(0, size.Height), visibleRect.Center, (CCPoint)visibleRect.Size, 50, 3, new CCColor4B(255, 0, 255, 255)); // draw cubic bezier path draw.DrawCubicBezier(visibleRect.Center, new CCPoint(size.Width / 2 + 30, size.Height / 2 + 50), new CCPoint(size.Width / 2 + 60, size.Height / 2 - 50), new CCPoint(size.Width, size.Height / 2), 100, 2, CCColor4B.Green); // draw an ellipse within rectangular region draw.DrawEllipse(new CCRect(100, 300, 100, 200), 8, CCColor4B.AliceBlue); var splinePoints = new List<CCPoint>(); splinePoints.Add(new CCPoint(0, 0)); splinePoints.Add(new CCPoint(50, 70)); splinePoints.Add(new CCPoint(0, 140)); splinePoints.Add(new CCPoint(100, 210)); splinePoints.Add(new CCPoint(0, 280)); splinePoints.Add(new CCPoint(150, 350)); int numberOfSegments = 64; float tension = .05f; draw.DrawCardinalSpline(splinePoints, tension, numberOfSegments); draw.DrawSolidArc( pos: new CCPoint(350, windowSize.Height * 0.75f), radius: 100, startAngle: CCMathHelper.ToRadians(45), sweepAngle: CCMathHelper.Pi / 2, // this is in radians, clockwise color: CCColor4B.Aquamarine); } #endregion Setup content } public class DrawNodeTest1 : BaseDrawNodeTest { #region Setup content CCDrawNode draw; public DrawNodeTest1() { draw = new CCDrawNode(); draw.BlendFunc = CCBlendFunc.NonPremultiplied; AddChild(draw, 10); } public override string Subtitle { get { return "Using DrawTriangleList user defined geometry"; } } public override void OnEnter() { base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size; CCDrawNode draw = new CCDrawNode(); AddChild(draw, 10); var s = windowSize; // Draw 10 circles for (int i = 0; i < 10; i++) { draw.DrawSolidCircle(s.Center, 10 * (10 - i), new CCColor4F(CCRandom.Float_0_1(), CCRandom.Float_0_1(), CCRandom.Float_0_1(), 1)); } // Draw polygons CCV3F_C4B[] points = new CCV3F_C4B[3]; points[0].Colors = CCColor4B.Red; points[0].Colors.A = 127; points[1].Colors = CCColor4B.Green; points[1].Colors.A = 127; points[2].Colors = CCColor4B.Blue; points[2].Colors.A = 127; points[0].Vertices.X = windowSize.Height / 4; points[0].Vertices.Y = 0; points[1].Vertices.X = windowSize.Width; points[1].Vertices.Y = windowSize.Height / 5; points[2].Vertices.X = windowSize.Width / 3 * 2; points[2].Vertices.Y = windowSize.Height; draw.DrawTriangleList(points); // star poly (triggers buggs) { const float o = 80; const float w = 20; const float h = 50; CCPoint[] star = new CCPoint[] { new CCPoint(o + w, o - h), new CCPoint(o + w * 2, o), // lower spike new CCPoint(o + w * 2 + h, o + w), new CCPoint(o + w * 2, o + w * 2), // right spike }; draw.DrawPolygon(star, star.Length, new CCColor4F(1, 0, 0, 0.5f), 1, new CCColor4F(0, 0, 1, 1)); } // star poly (doesn't trigger bug... order is important un tesselation is supported. { const float o = 180; const float w = 20; const float h = 50; var star = new CCPoint[] { new CCPoint(o, o), new CCPoint(o + w, o - h), new CCPoint(o + w * 2, o), // lower spike new CCPoint(o + w * 2 + h, o + w), new CCPoint(o + w * 2, o + w * 2), // right spike new CCPoint(o + w, o + w * 2 + h), new CCPoint(o, o + w * 2), // top spike new CCPoint(o - h, o + w), // left spike }; draw.DrawPolygon(star, star.Length, new CCColor4F(1, 0, 0, 0.5f), 1, new CCColor4F(0, 0, 1, 1)); } // Draw segment draw.DrawLine(new CCPoint(20, windowSize.Height), new CCPoint(20, windowSize.Height / 2), 10, new CCColor4F(0, 1, 0, 1), CCLineCap.Round); draw.DrawLine(new CCPoint(10, windowSize.Height / 2), new CCPoint(windowSize.Width / 2, windowSize.Height / 2), 40, new CCColor4F(1, 0, 1, 0.5f), CCLineCap.Round); } #endregion Setup content } public class DrawNodeTestBlend : BaseDrawNodeTest { #region Setup content CCDrawNode triangleList1; CCDrawNode triangleList2; public DrawNodeTestBlend() { triangleList1 = new CCDrawNode(); triangleList1.BlendFunc = CCBlendFunc.NonPremultiplied; AddChild(triangleList1, 10); triangleList2 = new CCDrawNode(); // The default BlendFunc is CCBlendFunc.AlphaBlend //triangleList2.BlendFunc = CCBlendFunc.AlphaBlend; AddChild(triangleList2, 10); } public override string Subtitle { get { return "Using DrawTriangleList With BlendFunc"; } } public override void OnEnter() { base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size; var line = new CCDrawNode(); line.DrawLine(new CCPoint(0, windowSize.Height / 2), new CCPoint(windowSize.Width, windowSize.Height / 2), 10); AddChild(line, 0); byte alpha = 100; // 255 is full opacity var green = new CCColor4B(0, 255, 0, alpha); CCV3F_C4B[] verts = new CCV3F_C4B[] { new CCV3F_C4B( new CCPoint(0,0), green), new CCV3F_C4B( new CCPoint(30,60), green), new CCV3F_C4B( new CCPoint(60,0), green) }; triangleList1.DrawTriangleList (verts); triangleList1.Position = windowSize.Center; triangleList1.PositionX -= windowSize.Width / 4; triangleList1.PositionY -= triangleList1.ContentSize.Center.Y; // Because the default BlendFunc of our DrawNode is AlphaBlend we need // to pass the colors as pre multiplied alpha. var greenPreMultiplied = green; greenPreMultiplied.G = (byte)(greenPreMultiplied.G * alpha / 255.0f); verts[0].Colors = greenPreMultiplied; verts[1].Colors = greenPreMultiplied; verts[2].Colors = greenPreMultiplied; triangleList2.DrawTriangleList (verts); triangleList2.Position = windowSize.Center; triangleList2.PositionX += windowSize.Width / 4; triangleList2.PositionY -= triangleList2.BoundingRect.Size.Height / 2; } #endregion Setup content } // Forum Post https://forums.xamarin.com/discussion/comment/145878/#Comment_145878 public class DrawNodeTriangleVertex : BaseDrawNodeTest { CCDrawNode drawTriangles; CCDrawNode backGround; public DrawNodeTriangleVertex() { Color = new CCColor3B(127, 127, 127); Opacity = 255; drawTriangles = new CCDrawNode(); drawTriangles.BlendFunc = CCBlendFunc.NonPremultiplied; AddChild(drawTriangles, 10); backGround = new CCDrawNode(); } public override string Subtitle { get { return "Using AddTriangleVertex for Custom Geometry"; } } #region Setup content public override void OnEnter() { base.OnEnter(); CCSize windowSize = VisibleBoundsWorldspace.Size; var move = new CCMoveBy(4, new CCPoint(windowSize.Width / 2, 0)); backGround.Position = VisibleBoundsWorldspace.Left(); backGround.PositionX += windowSize.Width / 4; // Run background animation backGround.RepeatForever(move, move.Reverse()); backGround.DrawSolidCircle(CCPoint.Zero, 220, CCColor4B.White); AddChild(backGround); var color = CCColor4B.Red; color.A = (byte)(255 * 0.3f); // Draw polygons //P1: 380:-160 P2: 200:-240 P3: 160:-420 CCPoint[] points = new CCPoint[] { //P1: 380:-160 P2: 200:-240 P3: 160:-420 new CCPoint(380,-160), new CCPoint(200,-240), new CCPoint(160,-420), }; //P1: 160:-420 P2: 200:-520 P3: 360:-540 CCPoint[] pointss = new CCPoint[] { new CCPoint(160,-420), new CCPoint(200,-520), new CCPoint(360,-540) }; //P1: 360:-540 P2: 420:-600 P3: 520:-520 CCPoint[] pointss2 = new CCPoint[] { new CCPoint(360,-540), new CCPoint(420,-600), new CCPoint(530,-520) }; //P1: 520:-520 P2: 380:-160 P3: 160:-420 CCPoint[] pointss3 = new CCPoint[] { new CCPoint(520,-520), new CCPoint(380,-160), new CCPoint(160,-420) }; // P1: 160:-420 P2: 360:-540 P3: 520:-520 CCPoint[] pointss4 = new CCPoint[] { new CCPoint(160,-420), new CCPoint(360,-540), new CCPoint(520,-520) }; DrawSolidPolygon(points, color); DrawSolidPolygon(pointss, color); DrawSolidPolygon(pointss2, color); DrawSolidPolygon(pointss3, color); DrawSolidPolygon(pointss4, color); drawTriangles.Position = windowSize.Center; // Offset by the bounds of the polygons to more or less center it drawTriangles.PositionX -= 370; drawTriangles.PositionY += 440; } #endregion Setup content void DrawSolidPolygon(CCPoint[] points, CCColor4B color) { for (int i = 0; i < points.Length - 2; i++) { drawTriangles.AddTriangleVertex(new CCV3F_C4B(points[0], color)); drawTriangles.AddTriangleVertex(new CCV3F_C4B(points[i + 1], color)); drawTriangles.AddTriangleVertex(new CCV3F_C4B(points[i + 2], color)); } } } // Forum Post https://forums.xamarin.com/discussion/comment/145878/#Comment_145878 // Issue #287 : https://github.com/mono/CocosSharp/issues/287 public class DrawNodeDrawPolygon : BaseDrawNodeTest { CCDrawNode drawTriangles; CCDrawNode backGround; public DrawNodeDrawPolygon() { Color = new CCColor3B(127, 127, 127); Opacity = 255; drawTriangles = new CCDrawNode(); AddChild(drawTriangles, 10); backGround = new CCDrawNode(); } public override string Subtitle { get { return "Using DrawPolygon - Issue #287"; } } #region Setup content public override void OnEnter() { base.OnEnter(); CCSize windowSize = VisibleBoundsWorldspace.Size; var move = new CCMoveBy(4, new CCPoint(windowSize.Width / 2, 0)); backGround.Position = VisibleBoundsWorldspace.Left(); backGround.PositionX += windowSize.Width / 4; // Run background animation backGround.RepeatForever(move, move.Reverse()); backGround.DrawSolidCircle(CCPoint.Zero, 220, CCColor4B.White); AddChild(backGround); var color = CCColor4B.Red; var alpha = (byte)(255 * 0.3f); color.A = alpha; // Draw polygons //P1: 380:-160 P2: 200:-240 P3: 160:-420 CCPoint[] points = new CCPoint[] { //P1: 380:-160 P2: 200:-240 P3: 160:-420 new CCPoint(380,-160), new CCPoint(200,-240), new CCPoint(160,-420), }; DrawSolidPolygon(points, color); //P1: 160:-420 P2: 200:-520 P3: 360:-540 points[0] = new CCPoint(160, -420); points[1] = new CCPoint(200, -520); points[2] = new CCPoint(360, -540); DrawSolidPolygon(points, color); //P1: 360:-540 P2: 420:-600 P3: 520:-520 points[0] = new CCPoint(360, -540); points[1] = new CCPoint(420, -600); points[2] = new CCPoint(530, -520); DrawSolidPolygon(points, color); //P1: 520:-520 P2: 380:-160 P3: 160:-420 points[0] = new CCPoint(520, -520); points[1] = new CCPoint(380, -160); points[2] = new CCPoint(160, -420); DrawSolidPolygon(points, color); // P1: 160:-420 P2: 360:-540 P3: 520:-520 points[0] = new CCPoint(160, -420); points[1] = new CCPoint(360, -540); points[2] = new CCPoint(520, -520); DrawSolidPolygon(points, color); drawTriangles.Position = windowSize.Center; // Offset by the bounds of the polygons to more or less center it drawTriangles.PositionX -= 370; drawTriangles.PositionY += 440; } #endregion Setup content void DrawSolidPolygon(CCPoint[] points, CCColor4B color) { drawTriangles.DrawPolygon(points, points.Length, color, 0, CCColor4B.Transparent); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the sdb-2009-04-15.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.SimpleDB.Model; using Amazon.SimpleDB.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.SimpleDB { /// <summary> /// Implementation for accessing SimpleDB /// /// Amazon SimpleDB is a web service providing the core database functions of data indexing /// and querying in the cloud. By offloading the time and effort associated with building /// and operating a web-scale database, SimpleDB provides developers the freedom to focus /// on application development. /// <para> /// A traditional, clustered relational database requires a sizable upfront capital outlay, /// is complex to design, and often requires extensive and repetitive database administration. /// Amazon SimpleDB is dramatically simpler, requiring no schema, automatically indexing /// your data and providing a simple API for storage and access. This approach eliminates /// the administrative burden of data modeling, index maintenance, and performance tuning. /// Developers gain access to this functionality within Amazon's proven computing environment, /// are able to scale instantly, and pay only for what they use. /// </para> /// /// <para> /// Visit <a href="http://aws.amazon.com/simpledb/">http://aws.amazon.com/simpledb/</a> /// for more information. /// </para> /// </summary> public partial class AmazonSimpleDBClient : AmazonServiceClient, IAmazonSimpleDB { #region Constructors /// <summary> /// Constructs AmazonSimpleDBClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonSimpleDBClient(AWSCredentials credentials) : this(credentials, new AmazonSimpleDBConfig()) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonSimpleDBClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonSimpleDBConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Credentials and an /// AmazonSimpleDBClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonSimpleDBClient Configuration Object</param> public AmazonSimpleDBClient(AWSCredentials credentials, AmazonSimpleDBConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonSimpleDBConfig()) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonSimpleDBConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID, AWS Secret Key and an /// AmazonSimpleDBClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonSimpleDBClient Configuration Object</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonSimpleDBConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSimpleDBConfig()) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonSimpleDBConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonSimpleDBClient with AWS Access Key ID, AWS Secret Key and an /// AmazonSimpleDBClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonSimpleDBClient Configuration Object</param> public AmazonSimpleDBClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonSimpleDBConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides protected override AbstractAWSSigner CreateSigner() { return new QueryStringSigner(); } #endregion #region Dispose protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region BatchDeleteAttributes internal BatchDeleteAttributesResponse BatchDeleteAttributes(BatchDeleteAttributesRequest request) { var marshaller = new BatchDeleteAttributesRequestMarshaller(); var unmarshaller = BatchDeleteAttributesResponseUnmarshaller.Instance; return Invoke<BatchDeleteAttributesRequest,BatchDeleteAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the BatchDeleteAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the BatchDeleteAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<BatchDeleteAttributesResponse> BatchDeleteAttributesAsync(BatchDeleteAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new BatchDeleteAttributesRequestMarshaller(); var unmarshaller = BatchDeleteAttributesResponseUnmarshaller.Instance; return InvokeAsync<BatchDeleteAttributesRequest,BatchDeleteAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region BatchPutAttributes internal BatchPutAttributesResponse BatchPutAttributes(BatchPutAttributesRequest request) { var marshaller = new BatchPutAttributesRequestMarshaller(); var unmarshaller = BatchPutAttributesResponseUnmarshaller.Instance; return Invoke<BatchPutAttributesRequest,BatchPutAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the BatchPutAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the BatchPutAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<BatchPutAttributesResponse> BatchPutAttributesAsync(BatchPutAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new BatchPutAttributesRequestMarshaller(); var unmarshaller = BatchPutAttributesResponseUnmarshaller.Instance; return InvokeAsync<BatchPutAttributesRequest,BatchPutAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateDomain internal CreateDomainResponse CreateDomain(CreateDomainRequest request) { var marshaller = new CreateDomainRequestMarshaller(); var unmarshaller = CreateDomainResponseUnmarshaller.Instance; return Invoke<CreateDomainRequest,CreateDomainResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateDomainResponse> CreateDomainAsync(CreateDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateDomainRequestMarshaller(); var unmarshaller = CreateDomainResponseUnmarshaller.Instance; return InvokeAsync<CreateDomainRequest,CreateDomainResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteAttributes internal DeleteAttributesResponse DeleteAttributes(DeleteAttributesRequest request) { var marshaller = new DeleteAttributesRequestMarshaller(); var unmarshaller = DeleteAttributesResponseUnmarshaller.Instance; return Invoke<DeleteAttributesRequest,DeleteAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteAttributesResponse> DeleteAttributesAsync(DeleteAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteAttributesRequestMarshaller(); var unmarshaller = DeleteAttributesResponseUnmarshaller.Instance; return InvokeAsync<DeleteAttributesRequest,DeleteAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteDomain internal DeleteDomainResponse DeleteDomain(DeleteDomainRequest request) { var marshaller = new DeleteDomainRequestMarshaller(); var unmarshaller = DeleteDomainResponseUnmarshaller.Instance; return Invoke<DeleteDomainRequest,DeleteDomainResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteDomain operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDomain operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteDomainResponse> DeleteDomainAsync(DeleteDomainRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteDomainRequestMarshaller(); var unmarshaller = DeleteDomainResponseUnmarshaller.Instance; return InvokeAsync<DeleteDomainRequest,DeleteDomainResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DomainMetadata internal DomainMetadataResponse DomainMetadata(DomainMetadataRequest request) { var marshaller = new DomainMetadataRequestMarshaller(); var unmarshaller = DomainMetadataResponseUnmarshaller.Instance; return Invoke<DomainMetadataRequest,DomainMetadataResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DomainMetadata operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DomainMetadata operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DomainMetadataResponse> DomainMetadataAsync(DomainMetadataRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DomainMetadataRequestMarshaller(); var unmarshaller = DomainMetadataResponseUnmarshaller.Instance; return InvokeAsync<DomainMetadataRequest,DomainMetadataResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetAttributes internal GetAttributesResponse GetAttributes(GetAttributesRequest request) { var marshaller = new GetAttributesRequestMarshaller(); var unmarshaller = GetAttributesResponseUnmarshaller.Instance; return Invoke<GetAttributesRequest,GetAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetAttributesResponse> GetAttributesAsync(GetAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetAttributesRequestMarshaller(); var unmarshaller = GetAttributesResponseUnmarshaller.Instance; return InvokeAsync<GetAttributesRequest,GetAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListDomains internal ListDomainsResponse ListDomains() { return ListDomains(new ListDomainsRequest()); } internal ListDomainsResponse ListDomains(ListDomainsRequest request) { var marshaller = new ListDomainsRequestMarshaller(); var unmarshaller = ListDomainsResponseUnmarshaller.Instance; return Invoke<ListDomainsRequest,ListDomainsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListDomains operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDomains operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListDomainsResponse> ListDomainsAsync(ListDomainsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListDomainsRequestMarshaller(); var unmarshaller = ListDomainsResponseUnmarshaller.Instance; return InvokeAsync<ListDomainsRequest,ListDomainsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region PutAttributes internal PutAttributesResponse PutAttributes(PutAttributesRequest request) { var marshaller = new PutAttributesRequestMarshaller(); var unmarshaller = PutAttributesResponseUnmarshaller.Instance; return Invoke<PutAttributesRequest,PutAttributesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PutAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<PutAttributesResponse> PutAttributesAsync(PutAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new PutAttributesRequestMarshaller(); var unmarshaller = PutAttributesResponseUnmarshaller.Instance; return InvokeAsync<PutAttributesRequest,PutAttributesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region Select internal SelectResponse Select(SelectRequest request) { var marshaller = new SelectRequestMarshaller(); var unmarshaller = SelectResponseUnmarshaller.Instance; return Invoke<SelectRequest,SelectResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the Select operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Select operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<SelectResponse> SelectAsync(SelectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new SelectRequestMarshaller(); var unmarshaller = SelectResponseUnmarshaller.Instance; return InvokeAsync<SelectRequest,SelectResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
//--------------------------------------------------------------------- // <copyright file="AtomConstants.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData.Core.Atom { /// <summary> /// Constant values related to the ATOM format. /// </summary> internal static class AtomConstants { #region Xml constants ----------------------------------------------------------------------------------------- /// <summary>'http://www.w3.org/2000/xmlns/' - namespace for namespace declarations.</summary> internal const string XmlNamespacesNamespace = "http://www.w3.org/2000/xmlns/"; /// <summary>Attribute use to add xml: namespaces specific attributes.</summary> internal const string XmlNamespace = "http://www.w3.org/XML/1998/namespace"; /// <summary> Schema Namespace prefix For xmlns.</summary> internal const string XmlnsNamespacePrefix = "xmlns"; /// <summary> Schema Namespace prefix For xml.</summary> internal const string XmlNamespacePrefix = "xml"; /// <summary>XML attribute value to indicate the base URI for a document or element.</summary> internal const string XmlBaseAttributeName = "base"; /// <summary>Name of the xml:space attribute.</summary> internal const string XmlSpaceAttributeName = "space"; /// <summary>'preserve' value for the xml:space attribute.</summary> internal const string XmlPreserveSpaceAttributeValue = "preserve"; #endregion Xml constants #region OData constants --------------------------------------------------------------------------------------- /// <summary>XML namespace for data service annotations.</summary> internal const string ODataMetadataNamespace = "http://docs.oasis-open.org/odata/ns/metadata"; /// <summary>XML namespace prefix for data service annotations.</summary> internal const string ODataMetadataNamespacePrefix = "m"; /// <summary>XML namespace for data services.</summary> internal const string ODataNamespace = "http://docs.oasis-open.org/odata/ns/data"; /// <summary>Prefix for data services namespace.</summary> internal const string ODataNamespacePrefix = "d"; /// <summary>OData attribute which indicates the etag value for the declaring entry element.</summary> internal const string ODataETagAttributeName = "etag"; /// <summary>OData attribute which indicates the null value for the element.</summary> internal const string ODataNullAttributeName = "null"; /// <summary>OData element name for the 'count' element</summary> internal const string ODataCountElementName = "count"; /// <summary>OData element name for the 'value' element</summary> internal const string ODataValueElementName = "value"; /// <summary>OData scheme namespace for data services category scheme in atom:category elements.</summary> internal const string ODataSchemeNamespace = "http://docs.oasis-open.org/odata/ns/scheme"; /// <summary>OData stream property prefix for named stream 'mediaresource' related link relations.</summary> internal const string ODataStreamPropertyMediaResourceRelatedLinkRelationPrefix = "http://docs.oasis-open.org/odata/ns/mediaresource/"; /// <summary>OData stream property prefix for named stream 'edit-media' related link relations.</summary> internal const string ODataStreamPropertyEditMediaRelatedLinkRelationPrefix = "http://docs.oasis-open.org/odata/ns/edit-media/"; /// <summary>OData navigation properties prefix for navigation link relations.</summary> internal const string ODataNavigationPropertiesRelatedLinkRelationPrefix = "http://docs.oasis-open.org/odata/ns/related/"; /// <summary>OData association link prefix for relation attribute.</summary> internal const string ODataNavigationPropertiesAssociationLinkRelationPrefix = "http://docs.oasis-open.org/odata/ns/relatedlinks/"; /// <summary>'Inline' - wrapping element for inlined entry/feed content.</summary> internal const string ODataInlineElementName = "inline"; /// <summary>Name of the error element for Xml error responses.</summary> internal const string ODataErrorElementName = "error"; /// <summary>Name of the error code element for Xml error responses.</summary> internal const string ODataErrorCodeElementName = "code"; /// <summary>Name of the error message element for Xml error responses.</summary> internal const string ODataErrorMessageElementName = "message"; /// <summary>Name of the inner error message element for Xml error responses.</summary> internal const string ODataInnerErrorElementName = "innererror"; /// <summary>Name of the message element in inner errors for Xml error responses.</summary> internal const string ODataInnerErrorMessageElementName = "message"; /// <summary>Name of the type element in inner errors for Xml error responses.</summary> internal const string ODataInnerErrorTypeElementName = "type"; /// <summary>Name of the stack trace element in inner errors for Xml error responses.</summary> internal const string ODataInnerErrorStackTraceElementName = "stacktrace"; /// <summary>Name of the inner error element nested in inner errors for Xml error responses.</summary> internal const string ODataInnerErrorInnerErrorElementName = "internalexception"; /// <summary>Element name for the items in a collection.</summary> internal const string ODataCollectionItemElementName = "element"; /// <summary>Element name for m:action.</summary> internal const string ODataActionElementName = "action"; /// <summary>Element name for m:function.</summary> internal const string ODataFunctionElementName = "function"; /// <summary>Attribute name for m:action|m:function/@metadata.</summary> internal const string ODataOperationMetadataAttribute = "metadata"; /// <summary>Attribute name for m:action|m:function/@title.</summary> internal const string ODataOperationTitleAttribute = "title"; /// <summary>Attribute name for m:action|m:function/@target.</summary> internal const string ODataOperationTargetAttribute = "target"; /// <summary>XML element name for the wrapper 'ref' element around a sequence of Uris in response to a ref request.</summary> internal const string ODataRefElementName = "ref"; /// <summary>XML element name for an Id response to a $ref request.</summary> internal const string ODataIdElementName = "id"; /// <summary>XML element name for a next link in a response to a $ref request.</summary> internal const string ODataNextLinkElementName = "next"; /// <summary>XML element name for an annotation in an ATOM payload.</summary> internal const string ODataAnnotationElementName = "annotation"; /// <summary>Attribute name for m:annotation/@target.</summary> internal const string ODataAnnotationTargetAttribute = "target"; /// <summary>Attribute name for m:annotation/@term.</summary> internal const string ODataAnnotationTermAttribute = "term"; /// <summary>Attribute name for m:annotation/@string.</summary> internal const string ODataAnnotationStringAttribute = "string"; /// <summary>Attribute name for m:annotation/@bool.</summary> internal const string ODataAnnotationBoolAttribute = "bool"; /// <summary>Attribute name for m:annotation/@decimal.</summary> internal const string ODataAnnotationDecimalAttribute = "decimal"; /// <summary>Attribute name for m:annotation/@int.</summary> internal const string ODataAnnotationIntAttribute = "int"; /// <summary>Attribute name for m:annotation/@float.</summary> internal const string ODataAnnotationFloatAttribute = "float"; /// <summary>Attribute name for m:name.</summary> internal const string ODataNameAttribute = "name"; #endregion OData constants #region Atom Format constants --------------------------------------------------------------------------------- /// <summary>Schema namespace for Atom.</summary> internal const string AtomNamespace = "http://www.w3.org/2005/Atom"; /// <summary>Prefix for the Atom namespace - empty since it is the default namespace.</summary> internal const string AtomNamespacePrefix = ""; /// <summary>Prefix for the Atom namespace used in cases where we need a non-empty prefix.</summary> internal const string NonEmptyAtomNamespacePrefix = "atom"; /// <summary>XML element name to mark entry element in Atom.</summary> internal const string AtomEntryElementName = "entry"; /// <summary>XML element name to mark feed element in Atom.</summary> internal const string AtomFeedElementName = "feed"; /// <summary>XML element name to mark content element in Atom.</summary> internal const string AtomContentElementName = "content"; /// <summary>XML element name to mark type attribute in Atom.</summary> internal const string AtomTypeAttributeName = "type"; /// <summary>Element containing property values when 'content' is used for media link entries</summary> internal const string AtomPropertiesElementName = "properties"; /// <summary>XML element name to mark id element in Atom.</summary> internal const string AtomIdElementName = "id"; /// <summary>Format for Atom transient id</summary> internal const string AtomTransientIdFormat = @"odata:transient:{{{0}}}"; /// <summary>Regular expression for Atom transient id</summary> internal const string AtomTransientIdRegularExpression = @"^odata:transient:{([\s\S]*)}$"; /// <summary>XML element name to mark title element in Atom.</summary> internal const string AtomTitleElementName = "title"; /// <summary>XML element name to mark the subtitle element in Atom.</summary> internal const string AtomSubtitleElementName = "subtitle"; /// <summary>XML element name to mark the summary element in Atom.</summary> internal const string AtomSummaryElementName = "summary"; /// <summary>XML element name to mark the 'published' element in Atom.</summary> internal const string AtomPublishedElementName = "published"; /// <summary>XML element name to mark the 'source' element in Atom.</summary> internal const string AtomSourceElementName = "source"; /// <summary>XML element name to mark the 'rights' element in Atom.</summary> internal const string AtomRightsElementName = "rights"; /// <summary>XML element name to mark the 'logo' element in Atom.</summary> internal const string AtomLogoElementName = "logo"; /// <summary>XML element name to mark the 'author' element in Atom.</summary> internal const string AtomAuthorElementName = "author"; /// <summary>XML element name to mark the 'author name' element in Atom.</summary> internal const string AtomAuthorNameElementName = "name"; /// <summary>XML element name to mark the 'contributor' element in Atom.</summary> internal const string AtomContributorElementName = "contributor"; /// <summary>XML element name to mark the 'generator' element in Atom.</summary> internal const string AtomGeneratorElementName = "generator"; /// <summary>XML attribute name of the 'uri' attribute of a 'generator' element in Atom.</summary> internal const string AtomGeneratorUriAttributeName = "uri"; /// <summary>XML attribute name of the 'version' attribute of a 'generator' element in Atom.</summary> internal const string AtomGeneratorVersionAttributeName = "version"; /// <summary>XML element name to mark the 'icon' element in Atom.</summary> internal const string AtomIconElementName = "icon"; /// <summary>XML element name to mark the 'name' element in an Atom person construct.</summary> internal const string AtomPersonNameElementName = "name"; /// <summary>XML element name to mark the 'uri' element in an Atom person construct.</summary> internal const string AtomPersonUriElementName = "uri"; /// <summary>XML element name to mark the 'email' element in an Atom person construct.</summary> internal const string AtomPersonEmailElementName = "email"; /// <summary>The name of the 'singleton' element when writing service documents in Xml format.</summary> internal const string AtomServiceDocumentSingletonElementName = "singleton"; /// <summary>The name of the 'function-import' element when writing service documents in Xml format.</summary> internal const string AtomServiceDocumentFunctionImportElementName = "function-import"; /// <summary>'updated' - XML element name for ATOM 'updated' element for entries.</summary> internal const string AtomUpdatedElementName = "updated"; /// <summary>'category' - XML element name for ATOM 'category' element for entries.</summary> internal const string AtomCategoryElementName = "category"; /// <summary>'term' - XML attribute name for ATOM 'term' attribute for categories.</summary> internal const string AtomCategoryTermAttributeName = "term"; /// <summary>'scheme' - XML attribute name for ATOM 'scheme' attribute for categories.</summary> internal const string AtomCategorySchemeAttributeName = "scheme"; /// <summary>'scheme' - XML attribute name for ATOM 'label' attribute for categories.</summary> internal const string AtomCategoryLabelAttributeName = "label"; /// <summary> Atom link relation attribute value for edit links.</summary> internal const string AtomEditRelationAttributeValue = "edit"; /// <summary> Atom link relation attribute value for self links.</summary> internal const string AtomSelfRelationAttributeValue = "self"; /// <summary> Atom context attribute value for specifying context URLs.</summary> internal const string AtomContextAttributeValue = "context"; /// <summary>XML element name to mark link element in Atom.</summary> internal const string AtomLinkElementName = "link"; /// <summary>XML attribute name of the link relation attribute in Atom.</summary> internal const string AtomLinkRelationAttributeName = "rel"; /// <summary>XML attribute name of the type attribute of a link in Atom.</summary> internal const string AtomLinkTypeAttributeName = "type"; /// <summary>XML attribute name of the href attribute of a link in Atom.</summary> internal const string AtomLinkHrefAttributeName = "href"; /// <summary>XML attribute name of the hreflang attribute of a link in Atom.</summary> internal const string AtomLinkHrefLangAttributeName = "hreflang"; /// <summary>XML attribute name of the title attribute of a link in Atom.</summary> internal const string AtomLinkTitleAttributeName = "title"; /// <summary>XML attribute name of the length attribute of a link in Atom.</summary> internal const string AtomLinkLengthAttributeName = "length"; /// <summary>XML element name to mark href attribute element in Atom.</summary> internal const string AtomHRefAttributeName = "href"; /// <summary>Atom source attribute name for the content of media link entries.</summary> internal const string MediaLinkEntryContentSourceAttributeName = "src"; /// <summary>Atom link relation attribute value for edit-media links.</summary> internal const string AtomEditMediaRelationAttributeValue = "edit-media"; /// <summary>XML attribute value of the link relation attribute for next page links in Atom.</summary> internal const string AtomNextRelationAttributeValue = "next"; /// <summary>XML attribute value of the link relation attribute for delta links in Atom.</summary> internal const string AtomDeltaRelationAttributeValue = "http://docs.oasis-open.org/odata/ns/delta"; /// <summary>Link relation: alternate - refers to a substitute for this context.</summary> internal const string AtomAlternateRelationAttributeValue = "alternate"; /// <summary>Link relation: related - identifies a related resource.</summary> internal const string AtomRelatedRelationAttributeValue = "related"; /// <summary>Link relation: enclosure - identifies a related resource that is potentially large and might require special handling.</summary> internal const string AtomEnclosureRelationAttributeValue = "enclosure"; /// <summary>Link relation: via - identifies a resource that is the source of the information in the link's context.</summary> internal const string AtomViaRelationAttributeValue = "via"; /// <summary>Link relation: describedby - refers to a resource providing information about the link's context.</summary> internal const string AtomDescribedByRelationAttributeValue = "describedby"; /// <summary>Link relation: service - indicates a URI that can be used to retrieve a service document.</summary> internal const string AtomServiceRelationAttributeValue = "service"; /// <summary>Atom metadata text construct kind: plain text</summary> internal const string AtomTextConstructTextKind = "text"; /// <summary>Atom metadata text construct kind: html</summary> internal const string AtomTextConstructHtmlKind = "html"; /// <summary>Atom metadata text construct kind: xhtml</summary> internal const string AtomTextConstructXHtmlKind = "xhtml"; /// <summary>Default title for service document workspaces.</summary> internal const string AtomWorkspaceDefaultTitle = "Default"; /// <summary>'true' literal</summary> internal const string AtomTrueLiteral = "true"; /// <summary>'false' literal</summary> internal const string AtomFalseLiteral = "false"; /// <summary>IANA link relations namespace.</summary> internal const string IanaLinkRelationsNamespace = "http://www.iana.org/assignments/relation/"; #endregion Atom Format constants #region Atom Publishing Protocol constants ------------------------------------------------------------ /// <summary>The Atom Publishing Protocol (APP) namespace: 'http://www.w3.org/2007/app'.</summary> internal const string AtomPublishingNamespace = "http://www.w3.org/2007/app"; /// <summary>The name of the top-level 'service' element when writing service documents in Xml format.</summary> internal const string AtomPublishingServiceElementName = "service"; /// <summary>The name of the 'workspace' element when writing service documents in Xml format.</summary> internal const string AtomPublishingWorkspaceElementName = "workspace"; /// <summary>The name of the 'collection' element when writing service documents in Xml format.</summary> internal const string AtomPublishingCollectionElementName = "collection"; /// <summary>The name of the 'categories' element encountered while reading a service document in XML format.</summary> internal const string AtomPublishingCategoriesElementName = "categories"; /// <summary>The name of the 'accept' element encountered while reading a service document in XML format.</summary> internal const string AtomPublishingAcceptElementName = "accept"; /// <summary>The name of the 'fixed' attribute of an inline categories element in APP.</summary> internal const string AtomPublishingFixedAttributeName = "fixed"; /// <summary>The value 'yes' of the 'fixed' attribute of an inline categories element in APP.</summary> internal const string AtomPublishingFixedYesValue = "yes"; /// <summary>The value 'no' of the 'fixed' attribute of an inline categories element in APP.</summary> internal const string AtomPublishingFixedNoValue = "no"; #endregion #region Spatial constants ------------------------------------------------------------------------------------- /// <summary>XML namespace for GeoRss format</summary> internal const string GeoRssNamespace = "http://www.georss.org/georss"; /// <summary>XML namespace prefix for GeoRss format</summary> internal const string GeoRssPrefix = "georss"; /// <summary>XML namespace for GML format</summary> internal const string GmlNamespace = "http://www.opengis.net/gml"; /// <summary>XML namespace prefix for GML format</summary> internal const string GmlPrefix = "gml"; #endregion } }
#region license // Copyright (c) 2006 Stephan D. Cote' - All rights reserved. // // This program and the accompanying materials are made available under the // terms of the MIT License which accompanies this distribution, and is // available at http://creativecommons.org/licenses/MIT/ // * // Contributors: // Stephan D. Cote // - Initial API and implementation #endregion using System; using System.IO; namespace Coyote.DataFrame.JSON { public class JsonWriter { public readonly TextWriter writer; private const int CONTROL_CHARACTERS_END = 0x001f; private static readonly char[] QUOT_CHARS = { '\\', '"' }; private static readonly char[] BS_CHARS = { '\\', '\\' }; private static readonly char[] LF_CHARS = { '\\', 'n' }; private static readonly char[] CR_CHARS = { '\\', 'r' }; private static readonly char[] TAB_CHARS = { '\\', 't' }; private static readonly char[] UNICODE_2028_CHARS = { '\\', 'u', '2', '0', '2', '8' }; private static readonly char[] UNICODE_2029_CHARS = { '\\', 'u', '2', '0', '2', '9' }; private static readonly char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private static char[] getReplacementChars(char ch) { if (ch > '\\') { if ((ch < '\u2028') || (ch > '\u2029')) { // The lower range contains 'a' .. 'z'. Only 2 checks required. return null; } return ch == '\u2028' ? UNICODE_2028_CHARS : UNICODE_2029_CHARS; } if (ch == '\\') { return BS_CHARS; } if (ch > '"') { // This range contains '0' .. '9' and 'A' .. 'Z'. Need 3 checks to get here. return null; } if (ch == '"') { return QUOT_CHARS; } if (ch > CONTROL_CHARACTERS_END) { return null; } if (ch == '\n') { return LF_CHARS; } if (ch == '\r') { return CR_CHARS; } if (ch == '\t') { return TAB_CHARS; } return new char[] { '\\', 'u', '0', '0', HEX_DIGITS[(ch >> 4) & 0x000f], HEX_DIGITS[ch & 0x000f] }; } internal JsonWriter(TextWriter writer) { this.writer = writer; } public virtual void writeArrayClose() { writer.Write(']'); } public virtual void writeArrayOpen() { writer.Write('['); } public virtual void writeArraySeparator() { writer.Write(','); } /// <summary> /// Write the string replacing any non-standard characters as necessary. /// </summary> /// <param name="str"></param> public virtual void writeJsonString(string str) { int length = str.Length; int Start = 0; for (int index = 0; index < length; index++) { char[] replacement = getReplacementChars(str[index]); if (replacement != null) { writer.Write(str, Start, index - Start); writer.Write(replacement); Start = index + 1; } } writer.Write(str, Start, length - Start); } /// <summary> /// Writes the string to the underlying writer with no additional formatting. /// </summary> /// <param name="value">the value to write</param> public virtual void writeLiteral(string @value) { writer.Write(@value); } public virtual void writeMemberName(string name) { writer.Write('"'); writeJsonString(name); writer.Write('"'); } public virtual void writeMemberSeparator() { writer.Write(':'); } /// <summary> /// Writes the number to the underlying writer with no additional formatting. /// </summary> /// <param name="value">the value to write</param> /// <exception cref="IOException">If writing encountered an error</exception> public virtual void writeNumber(string @value) { writer.Write(@value); } public virtual void writeObjectClose() { writer.Write('}'); } public virtual void writeObjectOpen() { writer.Write('{'); } public virtual void writeObjectSeparator() { writer.Write(','); } public virtual void writeString(string @string) { writer.Write('"'); writeJsonString(@string); writer.Write('"'); } } }
/* Genuine Channels product. * * Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved. * * This source code comes under and must be used and distributed according to the Genuine Channels license agreement. */ using System; using System.Collections; using System.IO; using System.Runtime.InteropServices; using System.Threading; using Belikov.GenuineChannels.Connection; using Belikov.GenuineChannels.DotNetRemotingLayer; using Belikov.GenuineChannels.Logbook; using Belikov.GenuineChannels.Messaging; using Belikov.GenuineChannels.Parameters; using Belikov.GenuineChannels.Security; using Belikov.GenuineChannels.TransportContext; namespace Belikov.GenuineChannels.GenuineSharedMemory { /// <summary> /// Represents a Shared Memory connection. /// </summary> internal class SharedMemoryConnection : Stream, IDisposable { /// <summary> /// Constructs an instance of the SharedMemoryConnection class. /// </summary> /// <param name="iTransportContext">The transport context.</param> /// <param name="name">The name of the shared chunk.</param> /// <param name="isServer">The role.</param> /// <param name="setCloseStatusOnExit">Indicates whether it is necessary to set the "closed" status on exit.</param> internal SharedMemoryConnection(ITransportContext iTransportContext, string name, bool isServer, bool setCloseStatusOnExit) { this.ITransportContext = iTransportContext; this.ShareName = "GenuineChannels_GShMem_" + name; this.IsServer = isServer; this._setCloseStatusOnExit = setCloseStatusOnExit; this._shareSize = (int) iTransportContext.IParameterProvider[GenuineParameter.SMShareSize]; this._pingTimeOut = GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.PersistentConnectionSendPingAfterInactivity]); this._closeAfterInactivity = GenuineUtility.ConvertToMilliseconds(iTransportContext.IParameterProvider[GenuineParameter.ClosePersistentConnectionAfterInactivity]); string localSideName = (isServer ? "Server" : "Client"); string remoteSideName = (isServer ? "Client" : "Server"); IParameterProvider parameters = this.ITransportContext.IParameterProvider; // construct shared object names for the local side string readCompletedEventName = GenuineSharedMemoryChannel.ConstructSharedObjectName( this.ShareName + localSideName + "ReadCompleted", parameters); string writeCompletedEventName = GenuineSharedMemoryChannel.ConstructSharedObjectName( this.ShareName + localSideName + "WriteCompleted", parameters); // construct shared object names for the remote side string remoteReadCompletedEventName = GenuineSharedMemoryChannel.ConstructSharedObjectName( this.ShareName + remoteSideName + "ReadCompleted", parameters); string remoteWriteCompletedEventName = GenuineSharedMemoryChannel.ConstructSharedObjectName( this.ShareName + remoteSideName + "WriteCompleted", parameters); if (isServer) { if (this._shareSize < MIN_SHARE_SIZE || this._shareSize > MAX_SHARE_SIZE) throw GenuineExceptions.Get_Channel_InvalidParameter("SMShareSize"); this.LowLevel_CreateSharedMemory(); this._closed = 0; this._writtenShareSize = this._shareSize; this._receiveOffset = 5; this._sendOffset = (this._shareSize - 5) / 2; this._receiveSpaceSize = this._sendOffset - 5 - 8; this._sendSpaceSize = this._shareSize - this._sendOffset - 8; this._namedEventReadCompleted = NamedEvent.CreateNamedEvent(readCompletedEventName, false, true); this._namedEventWriteCompleted = NamedEvent.CreateNamedEvent(writeCompletedEventName, false, true); this._namedEventRemoteReadCompleted = NamedEvent.CreateNamedEvent(remoteReadCompletedEventName, false, true); this._namedEventRemoteWriteCompleted = NamedEvent.CreateNamedEvent(remoteWriteCompletedEventName, false, true); } else { this.OpenSharedMemory(); if (this._closed != 0) throw GenuineExceptions.Get_Connect_CanNotConnectToRemoteHost(name, "Remote host has already closed the connection."); this._shareSize = this._writtenShareSize; if (this._shareSize < MIN_SHARE_SIZE || this._shareSize > MAX_SHARE_SIZE) throw GenuineExceptions.Get_Channel_InvalidParameter("SMShareSize"); this._receiveOffset = (this._shareSize - 5) / 2; this._sendOffset = 5; this._receiveSpaceSize = this._shareSize - this._receiveOffset - 8; this._sendSpaceSize = this._receiveOffset - 5 - 8; this._namedEventReadCompleted = NamedEvent.OpenNamedEvent(readCompletedEventName); this._namedEventWriteCompleted = NamedEvent.OpenNamedEvent(writeCompletedEventName); this._namedEventRemoteReadCompleted = NamedEvent.OpenNamedEvent(remoteReadCompletedEventName); this._namedEventRemoteWriteCompleted = NamedEvent.OpenNamedEvent(remoteWriteCompletedEventName); } this._sendBuffer = new byte[this._sendSpaceSize]; } /// <summary> /// To guarantee atomic access to local members. /// </summary> private object _accessToLocalMembers = new object(); /// <summary> /// Whether to set the "closed" status of the share on exit. /// </summary> private bool _setCloseStatusOnExit; /// <summary> /// Releases resources. /// </summary> ~SharedMemoryConnection() { this.ReleaseUnmanagedResources(); } /// <summary> /// Releases unmanaged resources. /// </summary> public void ReleaseUnmanagedResources() { if (this._pointer != IntPtr.Zero) { if (_setCloseStatusOnExit) this._closed = 1; WindowsAPI.UnmapViewOfFile(this._pointer); WindowsAPI.CloseHandle(this._mapHandle); this._pointer = IntPtr.Zero; this._mapHandle = IntPtr.Zero; } } /// <summary> /// The name of the share. /// </summary> public string ShareName; /// <summary> /// The transport context. /// </summary> public ITransportContext ITransportContext; /// <summary> /// The role. /// </summary> public bool IsServer; /// <summary> /// Whether this connection is valid. /// </summary> public bool IsValid { get { return this._isValid; } set { this._isValid = value; } } private object _isValidLock = new object(); private bool _isValid = true; /// <summary> /// Connection-level Security Session. /// </summary> public SecuritySession ConnectionLevelSecurity; /// <summary> /// The unique connection identifier, which is used for debugging purposes only. /// </summary> public int DbgConnectionId = ConnectionManager.GetUniqueConnectionId(); /// <summary> /// The remote host. /// </summary> public HostInformation Remote; /// <summary> /// Writer must acquire a lock on this object in order to send something. /// </summary> public object WriteAccess = new object(); /// <summary> /// Size of the share in bytes. /// </summary> private int _shareSize; /// <summary> /// Minimum size of the share. /// </summary> private const int MIN_SHARE_SIZE = 20000; /// <summary> /// Maximum size of the share. /// </summary> private const int MAX_SHARE_SIZE = 2000000; /// <summary> /// The size of the share header. /// </summary> private const int SHARE_CONTENT_OFFSET = 8; /// <summary> /// File mapping handle. /// </summary> private IntPtr _mapHandle = IntPtr.Zero; /// <summary> /// Unmanaged pointer to memory share. /// </summary> private IntPtr _pointer = IntPtr.Zero; internal NamedEvent _namedEventReadCompleted; private NamedEvent _namedEventRemoteReadCompleted; private NamedEvent _namedEventWriteCompleted; private NamedEvent _namedEventRemoteWriteCompleted; private int _receiveOffset; private int _receiveSpaceSize; private int _sendOffset; private int _sendSpaceSize; /// <summary> /// It's impossible to write stream content to the share directly. /// </summary> private byte[] _sendBuffer; #region -- Memory projections -------------------------------------------------------------- /// <summary> /// Indicates whether the connection was closed. /// </summary> private byte _closed { get { return Marshal.ReadByte(this._pointer); } set { Marshal.WriteByte(this._pointer, value); } } /// <summary> /// The size of the share. /// </summary> private int _writtenShareSize { get { return Marshal.ReadInt32(this._pointer, 1); } set { Marshal.WriteInt32(this._pointer, 1, value); } } private int _MessageToSendTotalSize { set { Marshal.WriteInt32(this._pointer, this._sendOffset, value); } } private int _MessageToSendFinishFlag { set { Marshal.WriteInt32(this._pointer, this._sendOffset + 4, value); } } private int _MessageToReceiveTotalSize { get { return Marshal.ReadInt32(this._pointer, this._receiveOffset); } } private int _MessageToReceiveFinishFlag { get { return Marshal.ReadInt32(this._pointer, this._receiveOffset + 4); } } #endregion #region -- Low level operations ------------------------------------------------------------ /// <summary> /// Creates shared memory object. /// </summary> public void LowLevel_CreateSharedMemory() { if (WindowsAPI.FailureReason != null) throw OperationException.WrapException(WindowsAPI.FailureReason); IParameterProvider parameters = this.ITransportContext.IParameterProvider; string fileMappingName = GenuineSharedMemoryChannel.ConstructSharedObjectName( this.ShareName, parameters); this._mapHandle = WindowsAPI.CreateFileMapping((IntPtr) (int) -1, WindowsAPI.AttributesWithNullDACL, WindowsAPI.PAGE_READWRITE, 0, (uint) this._shareSize, fileMappingName); if (this._mapHandle == IntPtr.Zero) throw GenuineExceptions.Get_Windows_CanNotCreateOrOpenSharedMemory(Marshal.GetLastWin32Error()); this._pointer = WindowsAPI.MapViewOfFile(this._mapHandle, WindowsAPI.SECTION_MAP_READ | WindowsAPI.SECTION_MAP_WRITE, 0, 0, 0); if (this._pointer == IntPtr.Zero) { int lastWinError = Marshal.GetLastWin32Error(); WindowsAPI.CloseHandle(this._mapHandle); throw GenuineExceptions.Get_Windows_SharedMemoryError(lastWinError); } } /// <summary> /// Opens the handle of an existent share. /// </summary> public void OpenSharedMemory() { IParameterProvider parameters = this.ITransportContext.IParameterProvider; string fileMappingName = GenuineSharedMemoryChannel.ConstructSharedObjectName( this.ShareName, parameters); this._mapHandle = WindowsAPI.OpenFileMapping(WindowsAPI.FILE_MAP_ALL_ACCESS, 0, fileMappingName); if (this._mapHandle == IntPtr.Zero) throw GenuineExceptions.Get_Windows_CanNotCreateOrOpenSharedMemory(Marshal.GetLastWin32Error()); this._pointer = WindowsAPI.MapViewOfFile(this._mapHandle, WindowsAPI.SECTION_MAP_READ | WindowsAPI.SECTION_MAP_WRITE, 0, 0, 0); if (this._pointer == IntPtr.Zero) { int lastWinError = Marshal.GetLastWin32Error(); WindowsAPI.CloseHandle(this._mapHandle); throw GenuineExceptions.Get_Windows_SharedMemoryError(lastWinError); } } /// <summary> /// Sends a message synchronously. Does not process exceptions! /// </summary> /// <param name="content">The content being sent to the remote host.</param> /// <param name="timeout">The sending must be completed before this moment.</param> public void LowLevel_SendSync(Stream content, int timeout) { // apply the connection-level security session if (this.ConnectionLevelSecurity != null) { GenuineChunkedStream outputStream = new GenuineChunkedStream(true); this.ConnectionLevelSecurity.Encrypt(content, outputStream); content = outputStream; } for ( ; ; ) { if (! this.IsValid) throw GenuineExceptions.Get_Processing_TransportConnectionFailed(); if (! GenuineUtility.WaitOne(_namedEventRemoteReadCompleted.ManualResetEvent, GenuineUtility.GetMillisecondsLeft(timeout)) ) throw GenuineExceptions.Get_Send_Timeout(); if (this._closed != 0) throw GenuineExceptions.Get_Receive_ConnectionClosed(); this._namedEventRemoteReadCompleted.ManualResetEvent.Reset(); // read the next portion int bytesRead = content.Read(this._sendBuffer, 0, this._sendSpaceSize); // LOG: BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "GenuineSaredMemoryConnection.LowLevel_SendSync", LogMessageType.LowLevelTransport_AsyncSendingInitiating, null, null, this.Remote, binaryLogWriter[LogCategory.LowLevelTransport] > 1 ? new MemoryStream(this._sendBuffer, 0, bytesRead) : null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, this.DbgConnectionId, bytesRead, null, null, null, "Content sending."); } Marshal.Copy( this._sendBuffer, 0, (IntPtr) (this._pointer.ToInt32() + this._sendOffset + SHARE_CONTENT_OFFSET), bytesRead ); this._MessageToSendTotalSize = bytesRead; this._MessageToSendFinishFlag = bytesRead < this._sendSpaceSize ? 1 : 0; this._namedEventWriteCompleted.ManualResetEvent.Set(); if (bytesRead < this._sendSpaceSize) { this.UpdateLastTimeAMessageWasSent(); return ; } } } /// <summary> /// Provides a stream reading synchronously from the given connection. /// </summary> /// <param name="finishTime">Read timeout.</param> /// <returns>A stream.</returns> public Stream LowLevel_ReadSync(int finishTime) { if (! this.IsValid) throw GenuineExceptions.Get_Processing_TransportConnectionFailed(); this._currentPosition = this._validLength; this._messageRead = false; this._readDeadline = finishTime; if (this.ConnectionLevelSecurity != null) return this.ConnectionLevelSecurity.Decrypt(this); return this; } #endregion #region -- Synchronous reading ------------------------------------------------------------- private int _readDeadline; private int _validLength; private int _currentPosition; private bool _messageRead; /// <summary> /// Reads a sequence of bytes from the current connection. /// </summary> /// <param name="buffer">An array of bytes.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer.</returns> public override int Read(byte[] buffer, int offset, int count) { int size = 0; int resultSize = 0; for ( ; ; ) { if (! this.IsValid) throw GenuineExceptions.Get_Processing_TransportConnectionFailed(); // check whether we have the next portion if (this._currentPosition < this._validLength) { size = Math.Min(this._validLength - this._currentPosition, count); Marshal.Copy( (IntPtr) (this._pointer.ToInt32() + this._receiveOffset + this._currentPosition + SHARE_CONTENT_OFFSET), buffer, offset, size); this._currentPosition += size; count -= size; resultSize += size; offset += size; } if (count <= 0 || this._messageRead) return resultSize; ReadNextPortion(); } } /// <summary> /// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream. /// </summary> /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns> public override int ReadByte() { // get a byte if (this._currentPosition < this._validLength) return Marshal.ReadByte(this._pointer, this._receiveOffset + this._currentPosition++ + SHARE_CONTENT_OFFSET); ReadNextPortion(); if (this._currentPosition < this._validLength) return Marshal.ReadByte(this._pointer, this._receiveOffset + this._currentPosition++ + SHARE_CONTENT_OFFSET); return -1; } /// <summary> /// Synchronously reads the next network packet if it is available. /// </summary> private void ReadNextPortion() { if (! this.IsValid) throw GenuineExceptions.Get_Processing_TransportConnectionFailed(); this._namedEventReadCompleted.ManualResetEvent.Set(); if (! GenuineUtility.WaitOne(this._namedEventRemoteWriteCompleted.ManualResetEvent, GenuineUtility.GetMillisecondsLeft(this._readDeadline)) ) throw GenuineExceptions.Get_Send_Timeout(); this._namedEventRemoteWriteCompleted.ManualResetEvent.Reset(); this._validLength = this._MessageToReceiveTotalSize; this._currentPosition = 0; this._messageRead = this._MessageToReceiveFinishFlag != 0; // LOG: BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter; if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 ) { bool writeContent = binaryLogWriter[LogCategory.LowLevelTransport] > 1; byte[] receivedData = new byte[this._validLength]; Marshal.Copy( (IntPtr) (this._pointer.ToInt32() + this._receiveOffset + this._currentPosition + SHARE_CONTENT_OFFSET), receivedData, 0, this._validLength); binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "GenuineSaredMemoryConnection.ReadNextPortion", LogMessageType.LowLevelTransport_SyncReceivingCompleted, null, null, this.Remote, writeContent ? new MemoryStream(receivedData, 0, this._validLength) : null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, this.DbgConnectionId, this._validLength, null, null, null, "Content received."); } } /// <summary> /// Closes the current stream and releases any resources associated with the current stream. /// </summary> public override void Close() { this.SkipMessage(); } /// <summary> /// Skip the current message in the transport stream. /// </summary> public void SkipMessage() { // GenuineUtility.CopyStreamToStream(this, Stream.Null); while (! this._messageRead) ReadNextPortion(); this._validLength = 0; } #endregion #region -- Insignificant stream members ---------------------------------------------------- /// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> public override bool CanRead { get { return true; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// Gets the length in bytes of the stream. /// </summary> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// Gets or sets the position within the current stream. /// Always fires NotSupportedException exception. /// </summary> public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// <summary> /// Begins an asynchronous read operation. /// </summary> /// <param name="buffer">The buffer to read the data into.</param> /// <param name="offset">The byte offset in buffer at which to begin writing data read from the stream.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <param name="callback">An optional asynchronous callback, to be called when the read is complete.</param> /// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param> /// <returns>An IAsyncResult that represents the asynchronous read, which could still be pending.</returns> public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException(); } /// <summary> /// Begins an asynchronous write operation. /// </summary> /// <param name="buffer">The buffer to write data from.</param> /// <param name="offset">The byte offset in buffer from which to begin writing.</param> /// <param name="count">The maximum number of bytes to write.</param> /// <param name="callback">An optional asynchronous callback, to be called when the write is complete.</param> /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param> /// <returns>An IAsyncResult that represents the asynchronous write, which could still be pending.</returns> public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException(); } /// <summary> /// Waits for the pending asynchronous read to complete. /// </summary> /// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param> /// <returns>The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams only return zero (0) at the end of the stream, otherwise, they should block until at least one byte is available.</returns> public override int EndRead(IAsyncResult asyncResult) { throw new NotSupportedException(); } /// <summary> /// Ends an asynchronous write operation. /// </summary> /// <param name="asyncResult">A reference to the outstanding asynchronous I/O request.</param> public override void EndWrite(IAsyncResult asyncResult) { throw new NotSupportedException(); } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> public override void Flush() { } /// <summary> /// Sets the position within the current stream. /// </summary> /// <param name="offset">A byte offset relative to the origin parameter.</param> /// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Sets the length of the current stream. /// </summary> /// <param name="val">The desired length of the current stream in bytes.</param> public override void SetLength(long val) { throw new NotSupportedException(); } #endregion #region -- Connection state ---------------------------------------------------------------- /// <summary> /// The state controller. /// </summary> private ConnectionStateSignaller _connectionStateSignaller; /// <summary> /// The state controller lock. /// </summary> private object _connectionStateSignallerLock = new object(); /// <summary> /// Sets the state of the connection. /// </summary> /// <param name="genuineEventType">The state of the connection.</param> /// <param name="reason">The exception.</param> /// <param name="additionalInfo">The additional info.</param> public void SignalState(GenuineEventType genuineEventType, Exception reason, object additionalInfo) { lock (this._connectionStateSignallerLock) { if (this._connectionStateSignaller == null) this._connectionStateSignaller = new ConnectionStateSignaller(this.Remote, this.ITransportContext.IGenuineEventProvider); this._connectionStateSignaller.SetState(genuineEventType, reason, additionalInfo); } } #endregion #region -- Lifetime and ping Management ---------------------------------------------------- /// <summary> /// A time span value indicating how often Connect Manager should check the connection. /// </summary> internal int _pingTimeOut; /// <summary> /// Time span during which the remote host must send at least one valid message. /// </summary> internal int _closeAfterInactivity; /// <summary> /// Renews connection activity for the CloseConnectionAfterInactivity value. /// </summary> public void Renew() { this.Remote.Renew(this._closeAfterInactivity, true); } /// <summary> /// Gets a DateTime representing a moment when last message was sent to the remote host. /// </summary> public int LastTimeAMessageWasSent { get { lock (this._accessToLocalMembers) return this._lastTimeAMessageWasSent; } } private int _lastTimeAMessageWasSent; /// <summary> /// Updates the DateTime when last message was sent. /// </summary> public void UpdateLastTimeAMessageWasSent() { lock (this._accessToLocalMembers) this._lastTimeAMessageWasSent = GenuineUtility.TickCount; } #endregion } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Runtime.InteropServices; using ESRI.ArcGIS.ADF.BaseClasses; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.Framework; using ESRI.ArcGIS.ArcMapUI; using ESRI.ArcGIS.Carto; namespace CustomMenus { /// <summary> /// Summary description for AddShapefile. /// </summary> [Guid("6f8f48fe-bfbc-4b2a-b1e7-25eced548743")] [ClassInterface(ClassInterfaceType.None)] [ProgId("CustomMenus.AddShapefile")] public sealed class AddShapefile : BaseCommand { #region COM Registration Function(s) [ComRegisterFunction()] [ComVisible(false)] static void RegisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType); } [ComUnregisterFunction()] [ComVisible(false)] static void UnregisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType); } #region ArcGIS Component Category Registrar generated code /// <summary> /// Required method for ArcGIS Component Category registration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryRegistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); MxCommands.Register(regKey); } /// <summary> /// Required method for ArcGIS Component Category unregistration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryUnregistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); MxCommands.Unregister(regKey); } #endregion #endregion private IApplication m_application; public AddShapefile() { base.m_category = "Developer Samples"; base.m_caption = "Add Shapefile"; base.m_message = "Adds a shapefile to the focus map"; base.m_toolTip = "Adds a shapefile"; base.m_name = "CustomMenus_AddShapefile"; try { string bitmapResourceName = GetType().Name + ".bmp"; base.m_bitmap = new Bitmap(GetType(), bitmapResourceName); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap"); } } #region Overriden Class Methods /// <summary> /// Occurs when this command is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { if (hook == null) return; m_application = hook as IApplication; //Disable if it is not ArcMap if (hook is IMxApplication) base.m_enabled = true; else base.m_enabled = false; } /// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { IMxDocument mxDocument = m_application.Document as IMxDocument; AddShapefileUsingOpenFileDialog(mxDocument.ActiveView); } #endregion //#### ArcGIS Snippets #### #region "Add Shapefile Using OpenFileDialog" ///<summary>Add a shapefile to the ActiveView using the Windows.Forms.OpenFileDialog control.</summary> /// ///<param name="activeView">An IActiveView interface</param> /// ///<remarks></remarks> public void AddShapefileUsingOpenFileDialog(ESRI.ArcGIS.Carto.IActiveView activeView) { //parameter check if (activeView == null) { return; } // Use the OpenFileDialog Class to choose which shapefile to load. System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog(); openFileDialog.InitialDirectory = "c:\\"; openFileDialog.Filter = "Shapefiles (*.shp)|*.shp"; openFileDialog.FilterIndex = 2; openFileDialog.RestoreDirectory = true; openFileDialog.Multiselect = false; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { // The user chose a particular shapefile. // The returned string will be the full path, filename and file-extension for the chosen shapefile. Example: "C:\test\cities.shp" string shapefileLocation = openFileDialog.FileName; if (shapefileLocation != "") { // Ensure the user chooses a shapefile // Create a new ShapefileWorkspaceFactory CoClass to create a new workspace ESRI.ArcGIS.Geodatabase.IWorkspaceFactory workspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactory(); // System.IO.Path.GetDirectoryName(shapefileLocation) returns the directory part of the string. Example: "C:\test\" ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(shapefileLocation), 0); // Explicit Cast // System.IO.Path.GetFileNameWithoutExtension(shapefileLocation) returns the base filename (without extension). Example: "cities" ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(shapefileLocation)); ESRI.ArcGIS.Carto.IFeatureLayer featureLayer = new ESRI.ArcGIS.Carto.FeatureLayer(); featureLayer.FeatureClass = featureClass; featureLayer.Name = featureClass.AliasName; featureLayer.Visible = true; activeView.FocusMap.AddLayer(featureLayer); // Zoom the display to the full extent of all layers in the map activeView.Extent = activeView.FullExtent; activeView.PartialRefresh(ESRI.ArcGIS.Carto.esriViewDrawPhase.esriViewGeography, null, null); } else { // The user did not choose a shapefile. // Do whatever remedial actions as necessary // System.Windows.Forms.MessageBox.Show("No shapefile chosen", "No Choice #1", // System.Windows.Forms.MessageBoxButtons.OK, // System.Windows.Forms.MessageBoxIcon.Exclamation); } } else { // The user did not choose a shapefile. They clicked Cancel or closed the dialog by the "X" button. // Do whatever remedial actions as necessary. // System.Windows.Forms.MessageBox.Show("No shapefile chosen", "No Choice #2", // System.Windows.Forms.MessageBoxButtons.OK, // System.Windows.Forms.MessageBoxIcon.Exclamation); } } #endregion } }
namespace Python.Test { /// <summary> /// Supports units tests for indexer access. /// </summary> public class PublicArrayTest { public int[] items; public PublicArrayTest() { items = new int[5] { 0, 1, 2, 3, 4 }; } } public class ProtectedArrayTest { protected int[] items; public ProtectedArrayTest() { items = new int[5] { 0, 1, 2, 3, 4 }; } } public class InternalArrayTest { internal int[] items; public InternalArrayTest() { items = new int[5] { 0, 1, 2, 3, 4 }; } } public class PrivateArrayTest { private int[] items; public PrivateArrayTest() { items = new int[5] { 0, 1, 2, 3, 4 }; } } public class BooleanArrayTest { public bool[] items; public BooleanArrayTest() { items = new bool[5] { true, false, true, false, true }; } } public class ByteArrayTest { public byte[] items; public ByteArrayTest() { items = new byte[5] { 0, 1, 2, 3, 4 }; } } public class SByteArrayTest { public sbyte[] items; public SByteArrayTest() { items = new sbyte[5] { 0, 1, 2, 3, 4 }; } } public class CharArrayTest { public char[] items; public CharArrayTest() { items = new char[5] { 'a', 'b', 'c', 'd', 'e' }; } } public class Int16ArrayTest { public short[] items; public Int16ArrayTest() { items = new short[5] { 0, 1, 2, 3, 4 }; } } public class Int32ArrayTest { public int[] items; public Int32ArrayTest() { items = new int[5] { 0, 1, 2, 3, 4 }; } } public class Int64ArrayTest { public long[] items; public Int64ArrayTest() { items = new long[5] { 0, 1, 2, 3, 4 }; } } public class UInt16ArrayTest { public ushort[] items; public UInt16ArrayTest() { items = new ushort[5] { 0, 1, 2, 3, 4 }; } } public class UInt32ArrayTest { public uint[] items; public UInt32ArrayTest() { items = new uint[5] { 0, 1, 2, 3, 4 }; } } public class UInt64ArrayTest { public ulong[] items; public UInt64ArrayTest() { items = new ulong[5] { 0, 1, 2, 3, 4 }; } } public class SingleArrayTest { public float[] items; public SingleArrayTest() { items = new float[5] { 0.0F, 1.0F, 2.0F, 3.0F, 4.0F }; } } public class DoubleArrayTest { public double[] items; public DoubleArrayTest() { items = new double[5] { 0.0, 1.0, 2.0, 3.0, 4.0 }; } } public class DecimalArrayTest { public decimal[] items; public DecimalArrayTest() { items = new decimal[5] { 0, 1, 2, 3, 4 }; } } public class StringArrayTest { public string[] items; public StringArrayTest() { items = new string[5] { "0", "1", "2", "3", "4" }; } } public class EnumArrayTest { public ShortEnum[] items; public EnumArrayTest() { items = new ShortEnum[5] { ShortEnum.Zero, ShortEnum.One, ShortEnum.Two, ShortEnum.Three, ShortEnum.Four }; } } public class NullArrayTest { public object[] items; public object[] empty; public NullArrayTest() { items = new object[5] { null, null, null, null, null }; empty = new object[0] { }; } } public class ObjectArrayTest { public object[] items; public ObjectArrayTest() { items = new object[5]; items[0] = new Spam("0"); items[1] = new Spam("1"); items[2] = new Spam("2"); items[3] = new Spam("3"); items[4] = new Spam("4"); } } public class InterfaceArrayTest { public ISpam[] items; public InterfaceArrayTest() { items = new ISpam[5]; items[0] = new Spam("0"); items[1] = new Spam("1"); items[2] = new Spam("2"); items[3] = new Spam("3"); items[4] = new Spam("4"); } } public class TypedArrayTest { public Spam[] items; public TypedArrayTest() { items = new Spam[5]; items[0] = new Spam("0"); items[1] = new Spam("1"); items[2] = new Spam("2"); items[3] = new Spam("3"); items[4] = new Spam("4"); } } public class MultiDimensionalArrayTest { public int[,] items; public MultiDimensionalArrayTest() { items = new int[5, 5] { { 0, 1, 2, 3, 4 }, { 5, 6, 7, 8, 9 }, { 10, 11, 12, 13, 14 }, { 15, 16, 17, 18, 19 }, { 20, 21, 22, 23, 24 } }; } } public class ArrayConversionTest { public static Spam[] EchoRange(Spam[] items) { return items; } public static Spam[,] EchoRangeMD(Spam[,] items) { return items; } public static Spam[][] EchoRangeAA(Spam[][] items) { return items; } } public struct Point { public Point(float x, float y) { X = x; Y = y; } public float X { get; set; } public float Y { get; set; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.V2.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAgentsClientTest { [xunit::FactAttribute] public void GetAgentRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.GetAgent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.GetAgentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.GetAgentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAgent() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.GetAgent(request.Parent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.GetAgentAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.GetAgentAsync(request.Parent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAgentResourceNames1() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.GetAgent(request.ParentAsProjectName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentResourceNames1Async() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.GetAgentAsync(request.ParentAsProjectName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.GetAgentAsync(request.ParentAsProjectName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetAgentResourceNames2() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.GetAgent(request.ParentAsLocationName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAgentResourceNames2Async() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetAgentRequest request = new GetAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.GetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.GetAgentAsync(request.ParentAsLocationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.GetAgentAsync(request.ParentAsLocationName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetAgentRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetAgentRequest request = new SetAgentRequest { Agent = new Agent(), UpdateMask = new wkt::FieldMask(), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.SetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.SetAgent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetAgentRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetAgentRequest request = new SetAgentRequest { Agent = new Agent(), UpdateMask = new wkt::FieldMask(), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.SetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.SetAgentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.SetAgentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetAgent() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetAgentRequest request = new SetAgentRequest { Agent = new Agent(), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.SetAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent response = client.SetAgent(request.Agent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetAgentAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetAgentRequest request = new SetAgentRequest { Agent = new Agent(), }; Agent expectedResponse = new Agent { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", DefaultLanguageCode = "default_language_codee612e130", SupportedLanguageCodes = { "supported_language_codesbcd806b9", }, TimeZone = "time_zone73f23b20", Description = "description2cf9da67", AvatarUri = "avatar_urie1767db7", EnableLogging = false, #pragma warning disable CS0612 MatchMode = Agent.Types.MatchMode.MlOnly, #pragma warning restore CS0612 ClassificationThreshold = -7.6869614E+17F, ApiVersion = Agent.Types.ApiVersion.V2Beta1, Tier = Agent.Types.Tier.Standard, }; mockGrpcClient.Setup(x => x.SetAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Agent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); Agent responseCallSettings = await client.SetAgentAsync(request.Agent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Agent responseCancellationToken = await client.SetAgentAsync(request.Agent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAgentRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); client.DeleteAgent(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAgentRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); await client.DeleteAgentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAgentAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAgent() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); client.DeleteAgent(request.Parent); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAgentAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); await client.DeleteAgentAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAgentAsync(request.Parent, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAgentResourceNames1() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); client.DeleteAgent(request.ParentAsProjectName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAgentResourceNames1Async() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); await client.DeleteAgentAsync(request.ParentAsProjectName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAgentAsync(request.ParentAsProjectName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteAgentResourceNames2() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); client.DeleteAgent(request.ParentAsLocationName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteAgentResourceNames2Async() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); DeleteAgentRequest request = new DeleteAgentRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteAgentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); await client.DeleteAgentAsync(request.ParentAsLocationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteAgentAsync(request.ParentAsLocationName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetValidationResultRequestObject() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetValidationResultRequest request = new GetValidationResultRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), LanguageCode = "language_code2f6c7160", }; ValidationResult expectedResponse = new ValidationResult { ValidationErrors = { new ValidationError(), }, }; mockGrpcClient.Setup(x => x.GetValidationResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); ValidationResult response = client.GetValidationResult(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetValidationResultRequestObjectAsync() { moq::Mock<Agents.AgentsClient> mockGrpcClient = new moq::Mock<Agents.AgentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetValidationResultRequest request = new GetValidationResultRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), LanguageCode = "language_code2f6c7160", }; ValidationResult expectedResponse = new ValidationResult { ValidationErrors = { new ValidationError(), }, }; mockGrpcClient.Setup(x => x.GetValidationResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ValidationResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AgentsClient client = new AgentsClientImpl(mockGrpcClient.Object, null); ValidationResult responseCallSettings = await client.GetValidationResultAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ValidationResult responseCancellationToken = await client.GetValidationResultAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.IO; using System.Text; using System.Xml; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.ComponentModel; namespace Dalssoft.DiagramNet { public class Designer : System.Windows.Forms.UserControl { private System.ComponentModel.IContainer components; #region Designer Control Initialization //Document private Document document = new Document(); // Drag and Drop MoveAction moveAction = null; // Selection BaseElement selectedElement; private bool isMultiSelection = false; private RectangleElement selectionArea = new RectangleElement(0,0,0,0); private IController[] controllers; private BaseElement mousePointerElement; // Resize private ResizeAction resizeAction = null; // Add Element private bool isAddSelection = false; // Link private bool isAddLink = false; private ConnectorElement connStart; private ConnectorElement connEnd; private BaseLinkElement linkLine; // Label private bool isEditLabel = false; private LabelElement selectedLabel; private System.Windows.Forms.TextBox labelTextBox = new TextBox(); private EditLabelAction editLabelAction = null; //Undo [NonSerialized] private UndoManager undo = new UndoManager(5); private bool changed = false; public Designer() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // This change control to not flick this.SetStyle(ControlStyles.UserPaint, true); this.SetStyle(ControlStyles.ResizeRedraw, true); this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.DoubleBuffer, true); // Selection Area Properties selectionArea.Opacity = 40; selectionArea.FillColor1 = SystemColors.Control; selectionArea.FillColor2 = Color.Empty; selectionArea.BorderColor = SystemColors.Control; // Link Line Properties //linkLine.BorderColor = Color.FromArgb(127, Color.DarkGray); //linkLine.BorderWidth = 4; // Label Edit labelTextBox.BorderStyle = BorderStyle.FixedSingle; labelTextBox.Multiline = true; labelTextBox.Hide(); this.Controls.Add(labelTextBox); //EventsHandlers RecreateEventsHandlers(); } #endregion /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if( components != null ) components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { // // Designer // this.AutoScroll = true; this.BackColor = System.Drawing.SystemColors.Window; this.Name = "Designer"; } #endregion public new void Invalidate() { if (document.Elements.Count > 0) { for (int i = 0; i <= document.Elements.Count - 1; i++) { BaseElement el = document.Elements[i]; Invalidate(el); if (el is ILabelElement) Invalidate(((ILabelElement) el).Label); } } else base.Invalidate(); if ((moveAction != null) && (moveAction.IsMoving)) this.AutoScrollMinSize = new Size((int) ((document.Location.X + document.Size.Width) * document.Zoom), (int) ((document.Location.Y + document.Size.Height) * document.Zoom)); } private void Invalidate(BaseElement el) { this.Invalidate(el, false); } private void Invalidate(BaseElement el, bool force) { if (el == null) return; if ((force) || (el.IsInvalidated)) { Rectangle invalidateRec = Goc2Gsc(el.invalidateRec); invalidateRec.Inflate(10, 10); base.Invalidate(invalidateRec); } } #region Events Overrides protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; GraphicsContainer gc; Matrix mtx; g.PageUnit = GraphicsUnit.Pixel; Point scrollPoint = this.AutoScrollPosition; g.TranslateTransform(scrollPoint.X, scrollPoint.Y); //Zoom mtx = g.Transform; gc = g.BeginContainer(); g.SmoothingMode = document.SmoothingMode; g.PixelOffsetMode = document.PixelOffsetMode; g.CompositingQuality = document.CompositingQuality; g.ScaleTransform(document.Zoom, document.Zoom); Rectangle clipRectangle = Gsc2Goc(e.ClipRectangle); document.DrawElements(g, clipRectangle); if (!((resizeAction != null) && (resizeAction.IsResizing))) document.DrawSelections(g, e.ClipRectangle); if ((isMultiSelection) || (isAddSelection)) DrawSelectionRectangle(g); if (isAddLink) { linkLine.CalcLink(); linkLine.Draw(g); } if ((resizeAction != null) && ( !((moveAction != null) && (moveAction.IsMoving)))) resizeAction.DrawResizeCorner(g); if (mousePointerElement != null) { if (mousePointerElement is IControllable) { IController ctrl = ((IControllable) mousePointerElement).GetController(); ctrl.DrawSelection(g); } } g.EndContainer(gc); g.Transform = mtx; base.OnPaint(e); } protected override void OnPaintBackground(PaintEventArgs e) { base.OnPaintBackground (e); Graphics g = e.Graphics; GraphicsContainer gc; Matrix mtx; g.PageUnit = GraphicsUnit.Pixel; mtx = g.Transform; gc = g.BeginContainer(); Rectangle clipRectangle = Gsc2Goc(e.ClipRectangle); document.DrawGrid(g, clipRectangle); g.EndContainer(gc); g.Transform = mtx; } protected override void OnKeyDown(KeyEventArgs e) { //Delete element if (e.KeyCode == Keys.Delete) { DeleteSelectedElements(); EndGeneralAction(); base.Invalidate(); } //Undo if (e.Control && e.KeyCode == Keys.Z) { if (undo.CanUndo) Undo(); } //Copy if ((e.Control) && (e.KeyCode == Keys.C)) { this.Copy(); } //Paste if ((e.Control) && (e.KeyCode == Keys.V)) { this.Paste(); } //Cut if ((e.Control) && (e.KeyCode == Keys.X)) { this.Cut(); } base.OnKeyDown (e); } protected override void OnResize(EventArgs e) { base.OnResize (e); document.WindowSize = this.Size; } #region Mouse Events protected override void OnMouseDown(MouseEventArgs e) { Point mousePoint; //ShowSelectionCorner((document.Action==DesignerAction.Select)); switch (document.Action) { // SELECT case DesignerAction.Connect: case DesignerAction.Select: if (e.Button == MouseButtons.Left) { mousePoint = Gsc2Goc(new Point(e.X, e.Y)); //Verify resize action StartResizeElement(mousePoint); if ((resizeAction != null) && (resizeAction.IsResizing)) break; //Verify label editing if (isEditLabel) { EndEditLabel(); } // Search element by click selectedElement = document.FindElement(mousePoint); if (selectedElement != null) { //Events ElementMouseEventArgs eventMouseDownArg = new ElementMouseEventArgs(selectedElement, e.X, e.Y); OnElementMouseDown(eventMouseDownArg); // Double-click to edit Label if ((e.Clicks == 2) && (selectedElement is ILabelElement)) { selectedLabel = ((ILabelElement) selectedElement).Label; StartEditLabel(); break; } // Element selected if (selectedElement is ConnectorElement) { StartAddLink((ConnectorElement) selectedElement, mousePoint); selectedElement = null; } else StartSelectElements(selectedElement, mousePoint); } else { // If click is on neutral area, clear selection document.ClearSelection(); Point p = Gsc2Goc(new Point(e.X, e.Y));; isMultiSelection = true; selectionArea.Visible = true; selectionArea.Location = p; selectionArea.Size = new Size(0, 0); if (resizeAction != null) resizeAction.ShowResizeCorner(false); } base.Invalidate(); } break; // ADD case DesignerAction.Add: if (e.Button == MouseButtons.Left) { mousePoint = Gsc2Goc(new Point(e.X, e.Y)); StartAddElement(mousePoint); } break; // DELETE case DesignerAction.Delete: if (e.Button == MouseButtons.Left) { mousePoint = Gsc2Goc(new Point(e.X, e.Y)); DeleteElement(mousePoint); } break; } base.OnMouseDown (e); } protected override void OnMouseMove(MouseEventArgs e) { if (e.Button == MouseButtons.None) { this.Cursor = Cursors.Arrow; Point mousePoint = Gsc2Goc(new Point(e.X, e.Y)); if ((resizeAction != null) && ((document.Action == DesignerAction.Select) || ((document.Action == DesignerAction.Connect) && (resizeAction.IsResizingLink)))) { this.Cursor = resizeAction.UpdateResizeCornerCursor(mousePoint); } if (document.Action == DesignerAction.Connect) { BaseElement mousePointerElementTMP = document.FindElement(mousePoint); if (mousePointerElement != mousePointerElementTMP) { if (mousePointerElementTMP is ConnectorElement) { mousePointerElement = mousePointerElementTMP; mousePointerElement.Invalidate(); this.Invalidate(mousePointerElement, true); } else if (mousePointerElement != null) { mousePointerElement.Invalidate(); this.Invalidate(mousePointerElement, true); mousePointerElement = null; } } } else { this.Invalidate(mousePointerElement, true); mousePointerElement = null; } } if (e.Button == MouseButtons.Left) { Point dragPoint = Gsc2Goc(new Point(e.X, e.Y)); if ((resizeAction != null) && (resizeAction.IsResizing)) { resizeAction.Resize(dragPoint); this.Invalidate(); } if ((moveAction != null) && (moveAction.IsMoving)) { moveAction.Move(dragPoint); this.Invalidate(); } if ((isMultiSelection) || (isAddSelection)) { Point p = Gsc2Goc(new Point(e.X, e.Y)); selectionArea.Size = new Size (p.X - selectionArea.Location.X, p.Y - selectionArea.Location.Y); selectionArea.Invalidate(); this.Invalidate(selectionArea, true); } if (isAddLink) { selectedElement = document.FindElement(dragPoint); if ((selectedElement is ConnectorElement) && (document.CanAddLink(connStart, (ConnectorElement) selectedElement))) linkLine.Connector2 = (ConnectorElement) selectedElement; else linkLine.Connector2 = connEnd; IMoveController ctrl = (IMoveController) ((IControllable) connEnd).GetController(); ctrl.Move(dragPoint); //this.Invalidate(linkLine, true); //TODO base.Invalidate(); } } base.OnMouseMove (e); } protected override void OnMouseUp(MouseEventArgs e) { Rectangle selectionRectangle = selectionArea.GetUnsignedRectangle(); if ((moveAction != null) && (moveAction.IsMoving)) { ElementEventArgs eventClickArg = new ElementEventArgs(selectedElement); OnElementClick(eventClickArg); moveAction.End(); moveAction = null; ElementMouseEventArgs eventMouseUpArg = new ElementMouseEventArgs(selectedElement, e.X, e.Y); OnElementMouseUp(eventMouseUpArg); if (changed) AddUndo(); } // Select if (isMultiSelection) { EndSelectElements(selectionRectangle); } // Add element else if (isAddSelection) { EndAddElement(selectionRectangle); } // Add link else if (isAddLink) { Point mousePoint = Gsc2Goc(new Point(e.X, e.Y)); EndAddLink(); AddUndo(); } // Resize if (resizeAction != null) { if (resizeAction.IsResizing) { Point mousePoint = Gsc2Goc(new Point(e.X, e.Y)); resizeAction.End(mousePoint); AddUndo(); } resizeAction.UpdateResizeCorner(); } RestartInitValues(); base.Invalidate(); base.OnMouseUp (e); } #endregion #endregion #region Events Raising // element handler public delegate void ElementEventHandler(object sender, ElementEventArgs e); #region Element Mouse Events // CLICK [Category("Element")] public event ElementEventHandler ElementClick; protected virtual void OnElementClick(ElementEventArgs e) { if (ElementClick != null) { ElementClick(this, e); } } // mouse handler public delegate void ElementMouseEventHandler(object sender, ElementMouseEventArgs e); // MOUSE DOWN [Category("Element")] public event ElementMouseEventHandler ElementMouseDown; protected virtual void OnElementMouseDown(ElementMouseEventArgs e) { if (ElementMouseDown != null) { ElementMouseDown(this, e); } } // MOUSE UP [Category("Element")] public event ElementMouseEventHandler ElementMouseUp; protected virtual void OnElementMouseUp(ElementMouseEventArgs e) { if (ElementMouseUp != null) { ElementMouseUp(this, e); } } #endregion #region Element Move Events // Before Move [Category("Element")] public event ElementEventHandler ElementMoving; protected virtual void OnElementMoving(ElementEventArgs e) { if (ElementMoving != null) { ElementMoving(this, e); } } // After Move [Category("Element")] public event ElementEventHandler ElementMoved; protected virtual void OnElementMoved(ElementEventArgs e) { if (ElementMoved != null) { ElementMoved(this, e); } } #endregion #region Element Resize Events // Before Resize [Category("Element")] public event ElementEventHandler ElementResizing; protected virtual void OnElementResizing(ElementEventArgs e) { if (ElementResizing != null) { ElementResizing(this, e); } } // After Resize [Category("Element")] public event ElementEventHandler ElementResized; protected virtual void OnElementResized(ElementEventArgs e) { if (ElementResized != null) { ElementResized(this, e); } } #endregion #region Element Connect Events // connect handler public delegate void ElementConnectEventHandler(object sender, ElementConnectEventArgs e); // Before Connect [Category("Element")] public event ElementConnectEventHandler ElementConnecting; protected virtual void OnElementConnecting(ElementConnectEventArgs e) { if (ElementConnecting != null) { ElementConnecting(this, e); } } // After Connect [Category("Element")] public event ElementConnectEventHandler ElementConnected; protected virtual void OnElementConnected(ElementConnectEventArgs e) { if (ElementConnected != null) { ElementConnected(this, e); } } #endregion #region Element Selection Events // connect handler public delegate void ElementSelectionEventHandler(object sender, ElementSelectionEventArgs e); // Selection [Category("Element")] public event ElementSelectionEventHandler ElementSelection; protected virtual void OnElementSelection(ElementSelectionEventArgs e) { if (ElementSelection != null) { ElementSelection(this, e); } } #endregion #endregion #region Events Handling private void document_PropertyChanged(object sender, EventArgs e) { if (!IsChanging()) { base.Invalidate(); } } private void document_AppearancePropertyChanged(object sender, EventArgs e) { if (!IsChanging()) { AddUndo(); base.Invalidate(); } } private void document_ElementPropertyChanged(object sender, EventArgs e) { changed = true; if (!IsChanging()) { AddUndo(); base.Invalidate(); } } private void document_ElementSelection(object sender, ElementSelectionEventArgs e) { OnElementSelection(e); } #endregion #region Properties public Document Document { get { return document; } } public bool CanUndo { get { return undo.CanUndo; } } public bool CanRedo { get { return undo.CanRedo; } } private bool IsChanging() { return ( ((moveAction != null) && (moveAction.IsMoving)) //isDragging || isAddLink || isMultiSelection || ((resizeAction != null) && (resizeAction.IsResizing)) //isResizing ); } #endregion #region Draw Methods /// <summary> /// Graphic surface coordinates to graphic object coordinates. /// </summary> /// <param name="p">Graphic surface point.</param> /// <returns></returns> public Point Gsc2Goc(Point gsp) { float zoom = document.Zoom; gsp.X = (int) ((gsp.X - this.AutoScrollPosition.X) / zoom); gsp.Y = (int) ((gsp.Y - this.AutoScrollPosition.Y) / zoom); return gsp; } public Rectangle Gsc2Goc(Rectangle gsr) { float zoom = document.Zoom; gsr.X = (int) ((gsr.X - this.AutoScrollPosition.X) / zoom); gsr.Y = (int) ((gsr.Y - this.AutoScrollPosition.Y) / zoom); gsr.Width = (int) (gsr.Width / zoom); gsr.Height = (int) (gsr.Height / zoom); return gsr; } public Rectangle Goc2Gsc(Rectangle gsr) { float zoom = document.Zoom; gsr.X = (int) ((gsr.X + this.AutoScrollPosition.X) * zoom); gsr.Y = (int) ((gsr.Y + this.AutoScrollPosition.Y) * zoom); gsr.Width = (int) (gsr.Width * zoom); gsr.Height = (int) (gsr.Height * zoom); return gsr; } internal void DrawSelectionRectangle(Graphics g) { selectionArea.Draw(g); } #endregion #region Open/Save File public void Save(string fileName) { IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, document); stream.Close(); } public void Open(string fileName) { IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); document = (Document) formatter.Deserialize(stream); stream.Close(); RecreateEventsHandlers(); } #endregion #region Copy/Paste public void Copy() { if (document.SelectedElements.Count == 0) return; IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); formatter.Serialize(stream, document.SelectedElements.GetArray()); DataObject data = new DataObject(DataFormats.GetFormat("Diagram.NET Element Collection").Name, stream); Clipboard.SetDataObject(data); } public void Paste() { const int pasteStep = 20; undo.Enabled = false; IDataObject iData = Clipboard.GetDataObject(); DataFormats.Format format = DataFormats.GetFormat("Diagram.NET Element Collection"); if (iData.GetDataPresent(format.Name)) { IFormatter formatter = new BinaryFormatter(); Stream stream = (MemoryStream) iData.GetData(format.Name); BaseElement[] elCol = (BaseElement[]) formatter.Deserialize(stream); stream.Close(); foreach(BaseElement el in elCol) { el.Location = new Point(el.Location.X + pasteStep, el.Location.Y + pasteStep); } document.AddElements(elCol); document.ClearSelection(); document.SelectElements(elCol); } undo.Enabled = true; AddUndo(); EndGeneralAction(); } public void Cut() { this.Copy(); DeleteSelectedElements(); EndGeneralAction(); } #endregion #region Start/End Actions and General Functions #region General private void EndGeneralAction() { RestartInitValues(); if (resizeAction != null) resizeAction.ShowResizeCorner(false); } private void RestartInitValues() { // Reinitialize status moveAction = null; isMultiSelection = false; isAddSelection = false; isAddLink = false; changed = false; connStart = null; selectionArea.FillColor1 = SystemColors.Control; selectionArea.BorderColor = SystemColors.Control; selectionArea.Visible = false; document.CalcWindow(true); } #endregion #region Selection private void StartSelectElements(BaseElement selectedElement, Point mousePoint) { // Vefiry if element is in selection if (!document.SelectedElements.Contains(selectedElement)) { //Clear selection and add new element to selection document.ClearSelection(); document.SelectElement(selectedElement); } changed = false; moveAction = new MoveAction(); MoveAction.OnElementMovingDelegate onElementMovingDelegate = new Dalssoft.DiagramNet.MoveAction.OnElementMovingDelegate(OnElementMoving); moveAction.Start(mousePoint, document, onElementMovingDelegate); // Get Controllers controllers = new IController[document.SelectedElements.Count]; for(int i = document.SelectedElements.Count - 1; i >= 0; i--) { if (document.SelectedElements[i] is IControllable) { // Get General Controller controllers[i] = ((IControllable) document.SelectedElements[i]).GetController(); } else { controllers[i] = null; } } resizeAction = new ResizeAction(); resizeAction.Select(document); } private void EndSelectElements(Rectangle selectionRectangle) { document.SelectElements(selectionRectangle); } #endregion #region Resize private void StartResizeElement(Point mousePoint) { if ((resizeAction != null) && ((document.Action == DesignerAction.Select) || ((document.Action == DesignerAction.Connect) && (resizeAction.IsResizingLink)))) { ResizeAction.OnElementResizingDelegate onElementResizingDelegate = new ResizeAction.OnElementResizingDelegate(OnElementResizing); resizeAction.Start(mousePoint, onElementResizingDelegate); if (!resizeAction.IsResizing) resizeAction = null; } } #endregion #region Link private void StartAddLink(ConnectorElement connStart, Point mousePoint) { if (document.Action == DesignerAction.Connect) { this.connStart = connStart; this.connEnd = new ConnectorElement(connStart.ParentElement); connEnd.Location = connStart.Location; IMoveController ctrl = (IMoveController) ((IControllable) connEnd).GetController(); ctrl.Start(mousePoint); isAddLink = true; switch(document.LinkType) { case (LinkType.Straight): linkLine = new StraightLinkElement(connStart, connEnd); break; case (LinkType.RightAngle): linkLine = new RightAngleLinkElement(connStart, connEnd); break; } linkLine.Visible = true; linkLine.BorderColor = Color.FromArgb(150, Color.Black); linkLine.BorderWidth = 1; this.Invalidate(linkLine, true); OnElementConnecting(new ElementConnectEventArgs(connStart.ParentElement, null, linkLine)); } } private void EndAddLink() { if (connEnd != linkLine.Connector2) { linkLine.Connector1.RemoveLink(linkLine); linkLine = document.AddLink(linkLine.Connector1, linkLine.Connector2); OnElementConnected(new ElementConnectEventArgs(linkLine.Connector1.ParentElement, linkLine.Connector2.ParentElement, linkLine)); } connStart = null; connEnd = null; linkLine = null; } #endregion #region Add Element private void StartAddElement(Point mousePoint) { document.ClearSelection(); //Change Selection Area Color selectionArea.FillColor1 = Color.LightSteelBlue; selectionArea.BorderColor = Color.WhiteSmoke; isAddSelection = true; selectionArea.Visible = true; selectionArea.Location = mousePoint; selectionArea.Size = new Size(0, 0); } private void EndAddElement(Rectangle selectionRectangle) { BaseElement el; switch (document.ElementType) { case ElementType.Rectangle: el = new RectangleElement(selectionRectangle); break; case ElementType.RectangleNode: el = new RectangleNode(selectionRectangle); break; case ElementType.Elipse: el = new ElipseElement(selectionRectangle); break; case ElementType.ElipseNode: el = new ElipseNode(selectionRectangle); break; case ElementType.CommentBox: el = new CommentBoxElement(selectionRectangle); break; default: el = new RectangleNode(selectionRectangle); break; } document.AddElement(el); document.Action = DesignerAction.Select; } #endregion #region Edit Label private void StartEditLabel() { isEditLabel = true; // Disable resize if (resizeAction != null) { resizeAction.ShowResizeCorner(false); resizeAction = null; } editLabelAction = new EditLabelAction(); editLabelAction.StartEdit(selectedElement, labelTextBox); } private void EndEditLabel() { if (editLabelAction != null) { editLabelAction.EndEdit(); editLabelAction = null; } isEditLabel = false; } #endregion #region Delete private void DeleteElement(Point mousePoint) { document.DeleteElement(mousePoint); selectedElement = null; document.Action = DesignerAction.Select; } private void DeleteSelectedElements() { document.DeleteSelectedElements(); } #endregion #endregion #region Undo/Redo public void Undo() { document = (Document) undo.Undo(); RecreateEventsHandlers(); if (resizeAction != null) resizeAction.UpdateResizeCorner(); base.Invalidate(); } public void Redo() { document = (Document) undo.Redo(); RecreateEventsHandlers(); if (resizeAction != null) resizeAction.UpdateResizeCorner(); base.Invalidate(); } private void AddUndo() { undo.AddUndo(document); } #endregion private void RecreateEventsHandlers() { document.PropertyChanged += new EventHandler(document_PropertyChanged); document.AppearancePropertyChanged+=new EventHandler(document_AppearancePropertyChanged); document.ElementPropertyChanged += new EventHandler(document_ElementPropertyChanged); document.ElementSelection += new Document.ElementSelectionEventHandler(document_ElementSelection); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel.Composition.Hosting; using System.Linq; using Xunit; namespace System.ComponentModel.Composition.Registration.Tests { public interface IController { } public interface IAuthentication { } public interface IFormsAuthenticationService { } public interface IMembershipService { } public class FormsAuthenticationServiceImpl : IFormsAuthenticationService { } public class MembershipServiceImpl : IMembershipService { } public class SpecificMembershipServiceImpl : IMembershipService { } public class HttpDigestAuthentication : IAuthentication { } public class AmbiguousConstructors { public AmbiguousConstructors(string first, int second) { StringArg = first; IntArg = second; } public AmbiguousConstructors(int first, string second) { IntArg = first; StringArg = second; } public int IntArg { get; set; } public string StringArg { get; set; } } public class AmbiguousConstructorsWithAttribute { [ImportingConstructorAttribute] public AmbiguousConstructorsWithAttribute(string first, int second) { StringArg = first; IntArg = second; } public AmbiguousConstructorsWithAttribute(int first, string second) { IntArg = first; StringArg = second; } public int IntArg { get; set; } public string StringArg { get; set; } } public class LongestConstructorWithAttribute { [ImportingConstructorAttribute] public LongestConstructorWithAttribute(string first, int second) { StringArg = first; IntArg = second; } public LongestConstructorWithAttribute(int first) { IntArg = first; } public int IntArg { get; set; } public string StringArg { get; set; } } public class LongestConstructorShortestWithAttribute { public LongestConstructorShortestWithAttribute(string first, int second) { StringArg = first; IntArg = second; } [ImportingConstructorAttribute] public LongestConstructorShortestWithAttribute(int first) { IntArg = first; } public int IntArg { get; set; } public string StringArg { get; set; } } public class ConstructorArgs { public ConstructorArgs() { IntArg = 10; StringArg = "Hello, World"; } public int IntArg { get; set; } public string StringArg { get; set; } } public class AccountController : IController { public IMembershipService MembershipService { get; private set; } public AccountController(IMembershipService membershipService) { MembershipService = membershipService; } public AccountController(IAuthentication auth) { } } public class HttpRequestValidator { public IAuthentication authenticator; public HttpRequestValidator(IAuthentication authenticator) { } } public class ManyConstructorsController : IController { public IFormsAuthenticationService FormsService { get; set; } public IMembershipService MembershipService { get; set; } public HttpRequestValidator Validator { get; set; } public ManyConstructorsController() { } public ManyConstructorsController( IFormsAuthenticationService formsService) { FormsService = formsService; } public ManyConstructorsController( IFormsAuthenticationService formsService, IMembershipService membershipService) { FormsService = formsService; MembershipService = MembershipService; } public ManyConstructorsController( IFormsAuthenticationService formsService, IMembershipService membershipService, HttpRequestValidator validator) { FormsService = formsService; MembershipService = membershipService; Validator = validator; } } public class PartBuilderUnitTests { [Fact] public void ManyConstructorsControllerFindLongestConstructor_ShouldSucceed() { var ctx = new RegistrationBuilder(); ctx.ForType<FormsAuthenticationServiceImpl>().Export<IFormsAuthenticationService>(); ctx.ForType<HttpDigestAuthentication>().Export<IAuthentication>(); ctx.ForType<MembershipServiceImpl>().Export<IMembershipService>(); ctx.ForType<HttpRequestValidator>().Export(); ctx.ForType<ManyConstructorsController>().Export(); var catalog = new TypeCatalog(new[] { typeof(FormsAuthenticationServiceImpl), typeof(HttpDigestAuthentication), typeof(MembershipServiceImpl), typeof(HttpRequestValidator), typeof(ManyConstructorsController) }, ctx); Assert.True(catalog.Parts.Count() == 5); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); ManyConstructorsController item = container.GetExportedValue<ManyConstructorsController>(); Assert.True(item.Validator != null); Assert.True(item.FormsService != null); Assert.True(item.MembershipService != null); } [Fact] public void ManyConstructorsControllerFindLongestConstructorAndImportByName_ShouldSucceed() { var ctx = new RegistrationBuilder(); ctx.ForType<FormsAuthenticationServiceImpl>().Export<IFormsAuthenticationService>(); ctx.ForType<HttpDigestAuthentication>().Export<IAuthentication>(); ctx.ForType<MembershipServiceImpl>().Export<IMembershipService>(); ctx.ForType<SpecificMembershipServiceImpl>().Export<IMembershipService>((c) => c.AsContractName("membershipService")); ctx.ForType<HttpRequestValidator>().Export(); ctx.ForType<ManyConstructorsController>().SelectConstructor(null, (pi, import) => { if (typeof(IMembershipService).IsAssignableFrom(pi.ParameterType)) { import.AsContractName("membershipService"); } }).Export(); var catalog = new TypeCatalog(new[] { typeof(FormsAuthenticationServiceImpl), typeof(HttpDigestAuthentication), typeof(MembershipServiceImpl), typeof(SpecificMembershipServiceImpl), typeof(HttpRequestValidator), typeof(ManyConstructorsController) }, ctx); Assert.True(catalog.Parts.Count() == 6); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); ManyConstructorsController item = container.GetExportedValue<ManyConstructorsController>(); Assert.True(item.Validator != null); Assert.True(item.FormsService != null); Assert.True(item.MembershipService != null); Assert.True(item.MembershipService.GetType() == typeof(SpecificMembershipServiceImpl)); } [Fact] public void LongestConstructorWithAttribute_ShouldSucceed() { var ctx = new RegistrationBuilder(); ctx.ForType<LongestConstructorWithAttribute>().Export(); ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "IntArg"); ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "StringArg"); var catalog = new TypeCatalog(new[] { typeof(LongestConstructorWithAttribute), typeof(ConstructorArgs) }, ctx); Assert.Equal(2, catalog.Parts.Count()); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); LongestConstructorWithAttribute item = container.GetExportedValue<LongestConstructorWithAttribute>(); Assert.Equal(10, item.IntArg); Assert.Equal("Hello, World", item.StringArg); } [Fact] public void LongestConstructorShortestWithAttribute_ShouldSucceed() { var ctx = new RegistrationBuilder(); ctx.ForType<LongestConstructorShortestWithAttribute>().Export(); ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "IntArg"); ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "StringArg"); var catalog = new TypeCatalog(new[] { typeof(LongestConstructorShortestWithAttribute), typeof(ConstructorArgs) }, ctx); Assert.Equal(2, catalog.Parts.Count()); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); LongestConstructorShortestWithAttribute item = container.GetExportedValue<LongestConstructorShortestWithAttribute>(); Assert.Equal(10, item.IntArg); Assert.Null(item.StringArg); } [Fact] public void AmbiguousConstructorWithAttributeAppliedToOne_ShouldSucceed() { var ctx = new RegistrationBuilder(); ctx.ForType<AmbiguousConstructorsWithAttribute>().Export(); ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "IntArg"); ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "StringArg"); var catalog = new TypeCatalog(new[] { typeof(AmbiguousConstructorsWithAttribute), typeof(ConstructorArgs) }, ctx); Assert.Equal(2, catalog.Parts.Count()); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); AmbiguousConstructorsWithAttribute item = container.GetExportedValue<AmbiguousConstructorsWithAttribute>(); Assert.Equal(10, item.IntArg); Assert.Equal("Hello, World", item.StringArg); } [Fact] public void AmbiguousConstructor_ShouldFail() { var ctx = new RegistrationBuilder(); ctx.ForType<AmbiguousConstructors>().Export(); ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "IntArg"); ctx.ForType<ConstructorArgs>().ExportProperties((m) => m.Name == "StringArg"); var catalog = new TypeCatalog(new[] { typeof(AmbiguousConstructors), typeof(ConstructorArgs) }, ctx); Assert.Equal(2, catalog.Parts.Count()); var container = new CompositionContainer(catalog, CompositionOptions.DisableSilentRejection); Assert.Throws<CompositionException>(() => container.GetExportedValue<AmbiguousConstructors>()); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Runtime.ExceptionServices; using Microsoft.PowerShell.Commands; namespace System.Management.Automation { /// <summary> /// Defines the types of commands that MSH can execute /// </summary> [Flags] public enum CommandTypes { /// <summary> /// Aliases create a name that refers to other command types /// </summary> /// /// <remarks> /// Aliases are only persisted within the execution of a single engine. /// </remarks> Alias = 0x0001, /// <summary> /// Script functions that are defined by a script block /// </summary> /// /// <remarks> /// Functions are only persisted within the execution of a single engine. /// </remarks> Function = 0x0002, /// <summary> /// Script filters that are defined by a script block. /// </summary> /// /// <remarks> /// Filters are only persisted within the execution of a single engine. /// </remarks> Filter = 0x0004, /// <summary> /// A cmdlet. /// </summary> Cmdlet = 0x0008, /// <summary> /// An MSH script (*.ps1 file) /// </summary> ExternalScript = 0x0010, /// <summary> /// Any existing application (can be console or GUI). /// </summary> /// /// <remarks> /// An application can have any extension that can be executed either directly through CreateProcess /// or indirectly through ShellExecute. /// </remarks> Application = 0x0020, /// <summary> /// A script that is built into the runspace configuration /// </summary> Script = 0x0040, /// <summary> /// A workflow /// </summary> Workflow = 0x0080, /// <summary> /// A Configuration /// </summary> Configuration = 0x0100, /// <summary> /// All possible command types. /// </summary> /// /// <remarks> /// Note, a CommandInfo instance will never specify /// All as its CommandType but All can be used when filtering the CommandTypes. /// </remarks> All = Alias | Function | Filter | Cmdlet | Script | ExternalScript | Application | Workflow | Configuration, } /// <summary> /// The base class for the information about commands. Contains the basic information about /// the command, like name and type. /// </summary> public abstract class CommandInfo : IHasSessionStateEntryVisibility { #region ctor /// <summary> /// Creates an instance of the CommandInfo class with the specified name and type /// </summary> /// /// <param name="name"> /// The name of the command. /// </param> /// /// <param name="type"> /// The type of the command. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="name"/> is null. /// </exception> /// internal CommandInfo(string name, CommandTypes type) { // The name can be empty for functions and filters but it // can't be null if (name == null) { throw new ArgumentNullException("name"); } Name = name; CommandType = type; } // CommandInfo ctor /// <summary> /// Creates an instance of the CommandInfo class with the specified name and type /// </summary> /// /// <param name="name"> /// The name of the command. /// </param> /// /// <param name="type"> /// The type of the command. /// </param> /// /// <param name="context"> /// The execution context for the command. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="name"/> is null. /// </exception> /// internal CommandInfo(string name, CommandTypes type, ExecutionContext context) : this(name, type) { this.Context = context; } // CommandInfo ctor /// <summary> /// This is a copy constructor, used primarily for get-command. /// </summary> internal CommandInfo(CommandInfo other) { // Computed fields not copied: //this._externalCommandMetadata = other._externalCommandMetadata; //this._moduleName = other._moduleName; //this.parameterSets = other.parameterSets; this.Module = other.Module; _visibility = other._visibility; Arguments = other.Arguments; this.Context = other.Context; Name = other.Name; CommandType = other.CommandType; CopiedCommand = other; this.DefiningLanguageMode = other.DefiningLanguageMode; } /// <summary> /// This is a copy constructor, used primarily for get-command. /// </summary> internal CommandInfo(string name, CommandInfo other) : this(other) { Name = name; } #endregion ctor /// <summary> /// Gets the name of the command. /// </summary> public string Name { get; private set; } = String.Empty; // Name /// <summary> /// Gets the type of the command /// </summary> public CommandTypes CommandType { get; private set; } = CommandTypes.Application; // CommandType /// <summary> /// Gets the source of the command (shown by default in Get-Command) /// </summary> public virtual string Source { get { return this.ModuleName; } } /// <summary> /// Gets the source version (shown by default in Get-Command) /// </summary> public virtual Version Version { get { if (_version == null) { if (Module != null) { if (Module.Version.Equals(new Version(0, 0))) { if (Module.Path.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { // Manifest module (.psd1) Module.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(Module.Path)); } else if (Module.Path.EndsWith(StringLiterals.DependentWorkflowAssemblyExtension, StringComparison.OrdinalIgnoreCase)) { // Binary module (.dll) Module.SetVersion(ClrFacade.GetAssemblyName(Module.Path).Version); } } _version = Module.Version; } } return _version; } } private Version _version; /// <summary> /// The execution context this command will run in. /// </summary> internal ExecutionContext Context { get { return _context; } set { _context = value; if ((value != null) && !this.DefiningLanguageMode.HasValue) { this.DefiningLanguageMode = value.LanguageMode; } } } private ExecutionContext _context; /// <summary> /// The language mode that was in effect when this alias was defined. /// </summary> internal PSLanguageMode? DefiningLanguageMode { get; set; } internal virtual HelpCategory HelpCategory { get { return HelpCategory.None; } } internal CommandInfo CopiedCommand { get; set; } /// <summary> /// Internal interface to change the type of a CommandInfo object. /// </summary> /// <param name="newType"></param> internal void SetCommandType(CommandTypes newType) { CommandType = newType; } internal const int HasWorkflowKeyWord = 0x0008; internal const int IsCimCommand = 0x0010; internal const int IsFile = 0x0020; /// <summary> /// A string representing the definition of the command. /// </summary> /// /// <remarks> /// This is overridden by derived classes to return specific /// information for the command type. /// </remarks> public abstract string Definition { get; } /// <summary> /// This is required for renaming aliases, functions, and filters /// </summary> /// /// <param name="newName"> /// The new name for the command. /// </param> /// /// <exception cref="ArgumentException"> /// If <paramref name="newName"/> is null or empty. /// </exception> /// internal void Rename(string newName) { if (String.IsNullOrEmpty(newName)) { throw new ArgumentNullException("newName"); } Name = newName; } /// <summary> /// for diagnostic purposes /// </summary> /// <returns></returns> public override string ToString() { return ModuleCmdletBase.AddPrefixToCommandName(Name, Prefix); } /// <summary> /// Indicates if the command is to be allowed to be executed by a request /// external to the runspace. /// </summary> public virtual SessionStateEntryVisibility Visibility { get { return CopiedCommand == null ? _visibility : CopiedCommand.Visibility; } set { if (CopiedCommand == null) { _visibility = value; } else { CopiedCommand.Visibility = value; } if (value == SessionStateEntryVisibility.Private && Module != null) { Module.ModuleHasPrivateMembers = true; } } } private SessionStateEntryVisibility _visibility = SessionStateEntryVisibility.Public; /// <summary> /// Return a CommandMetadata instance that is never exposed publicly. /// </summary> internal virtual CommandMetadata CommandMetadata { get { throw new InvalidOperationException(); } } /// <summary> /// Returns the syntax of a command /// </summary> internal virtual string Syntax { get { return Definition; } } /// <summary> /// The module name of this command. It will be empty for commands /// not imported from either a module or snapin. /// </summary> public string ModuleName { get { string moduleName = null; if (Module != null && !string.IsNullOrEmpty(Module.Name)) { moduleName = Module.Name; } else { CmdletInfo cmdlet = this as CmdletInfo; if (cmdlet != null && cmdlet.PSSnapIn != null) { moduleName = cmdlet.PSSnapInName; } } if (moduleName == null) return string.Empty; return moduleName; } } /// <summary> /// The module that defines this cmdlet. This will be null for commands /// that are not defined in the context of a module. /// </summary> public PSModuleInfo Module { get; internal set; } /// <summary> /// The remoting capabilities of this cmdlet, when exposed in a context /// with ambient remoting. /// </summary> public RemotingCapability RemotingCapability { get { try { return ExternalCommandMetadata.RemotingCapability; } catch (PSNotSupportedException) { // Thrown on an alias that hasn't been resolved yet (i.e.: in a module that // hasn't been loaded.) Assume the default. return RemotingCapability.PowerShell; } } } /// <summary> /// True if the command has dynamic parameters, false otherwise. /// </summary> internal virtual bool ImplementsDynamicParameters { get { return false; } } /// <summary> /// Constructs the MergedCommandParameterMetadata, using any arguments that /// may have been specified so that dynamic parameters can be determined, if any. /// </summary> /// <returns></returns> private MergedCommandParameterMetadata GetMergedCommandParameterMetadataSafely() { if (_context == null) return null; MergedCommandParameterMetadata result; if (_context != LocalPipeline.GetExecutionContextFromTLS()) { // In the normal case, _context is from the thread we're on, and we won't get here. // But, if it's not, we can't safely get the parameter metadata without running on // on the correct thread, because that thread may be busy doing something else. // One of the things we do here is change the current scope in execution context, // that can mess up the runspace our CommandInfo object came from. var runspace = (RunspaceBase)_context.CurrentRunspace; if (!runspace.RunActionIfNoRunningPipelinesWithThreadCheck( () => GetMergedCommandParameterMetadata(out result))) { _context.Events.SubscribeEvent( source: null, eventName: PSEngineEvent.GetCommandInfoParameterMetadata, sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata, data: null, handlerDelegate: new PSEventReceivedEventHandler(OnGetMergedCommandParameterMetadataSafelyEventHandler), supportEvent: true, forwardEvent: false, shouldQueueAndProcessInExecutionThread: true, maxTriggerCount: 1); var eventArgs = new GetMergedCommandParameterMetadataSafelyEventArgs(); _context.Events.GenerateEvent( sourceIdentifier: PSEngineEvent.GetCommandInfoParameterMetadata, sender: null, args: new[] { eventArgs }, extraData: null, processInCurrentThread: true, waitForCompletionInCurrentThread: true); if (eventArgs.Exception != null) { // An exception happened on a different thread, rethrow it here on the correct thread. eventArgs.Exception.Throw(); } return eventArgs.Result; } } GetMergedCommandParameterMetadata(out result); return result; } private class GetMergedCommandParameterMetadataSafelyEventArgs : EventArgs { public MergedCommandParameterMetadata Result; public ExceptionDispatchInfo Exception; } private void OnGetMergedCommandParameterMetadataSafelyEventHandler(object sender, PSEventArgs args) { var eventArgs = args.SourceEventArgs as GetMergedCommandParameterMetadataSafelyEventArgs; if (eventArgs != null) { try { // Save the result in our event args as the return value. GetMergedCommandParameterMetadata(out eventArgs.Result); } catch (Exception e) { // Save the exception so we can throw it on the correct thread. eventArgs.Exception = ExceptionDispatchInfo.Capture(e); } } } private void GetMergedCommandParameterMetadata(out MergedCommandParameterMetadata result) { // MSFT:652277 - When invoking cmdlets or advanced functions, MyInvocation.MyCommand.Parameters do not contain the dynamic parameters // When trying to get parameter metadata for a CommandInfo that has dynamic parameters, a new CommandProcessor will be // created out of this CommandInfo and the parameter binding algorithm will be invoked. However, when this happens via // 'MyInvocation.MyCommand.Parameter', it's actually retrieving the parameter metadata of the same cmdlet that is currently // running. In this case, information about the specified parameters are not kept around in 'MyInvocation.MyCommand', so // going through the binding algorithm again won't give us the metadata about the dynamic parameters that should have been // discovered already. // The fix is to check if the CommandInfo is actually representing the currently running cmdlet. If so, the retrieval of parameter // metadata actually stems from the running of the same cmdlet. In this case, we can just use the current CommandProcessor to // retrieve all bindable parameters, which should include the dynamic parameters that have been discovered already. CommandProcessor processor; if (Context.CurrentCommandProcessor != null && Context.CurrentCommandProcessor.CommandInfo == this) { // Accessing the parameters within the invocation of the same cmdlet/advanced function. processor = (CommandProcessor)Context.CurrentCommandProcessor; } else { IScriptCommandInfo scriptCommand = this as IScriptCommandInfo; processor = scriptCommand != null ? new CommandProcessor(scriptCommand, _context, useLocalScope: true, fromScriptFile: false, sessionState: scriptCommand.ScriptBlock.SessionStateInternal ?? Context.EngineSessionState) : new CommandProcessor((CmdletInfo)this, _context) { UseLocalScope = true }; ParameterBinderController.AddArgumentsToCommandProcessor(processor, Arguments); CommandProcessorBase oldCurrentCommandProcessor = Context.CurrentCommandProcessor; try { Context.CurrentCommandProcessor = processor; processor.SetCurrentScopeToExecutionScope(); processor.CmdletParameterBinderController.BindCommandLineParametersNoValidation(processor.arguments); } catch (ParameterBindingException) { // Ignore the binding exception if no argument is specified if (processor.arguments.Count > 0) { throw; } } finally { Context.CurrentCommandProcessor = oldCurrentCommandProcessor; processor.RestorePreviousScope(); } } result = processor.CmdletParameterBinderController.BindableParameters; } /// <summary> /// Return the parameters for this command. /// </summary> public virtual Dictionary<string, ParameterMetadata> Parameters { get { Dictionary<string, ParameterMetadata> result = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase); if (ImplementsDynamicParameters && Context != null) { MergedCommandParameterMetadata merged = GetMergedCommandParameterMetadataSafely(); foreach (KeyValuePair<string, MergedCompiledCommandParameter> pair in merged.BindableParameters) { result.Add(pair.Key, new ParameterMetadata(pair.Value.Parameter)); } // Don't cache this data... return result; } return ExternalCommandMetadata.Parameters; } } internal CommandMetadata ExternalCommandMetadata { get { return _externalCommandMetadata ?? (_externalCommandMetadata = new CommandMetadata(this, true)); } set { _externalCommandMetadata = value; } } private CommandMetadata _externalCommandMetadata; /// <summary> /// Resolves a full, shortened, or aliased parameter name to the actual /// cmdlet parameter name, using PowerShell's standard parameter resolution /// algorithm. /// </summary> /// <param name="name">The name of the parameter to resolve.</param> /// <returns>The parameter that matches this name</returns> public ParameterMetadata ResolveParameter(string name) { MergedCommandParameterMetadata merged = GetMergedCommandParameterMetadataSafely(); MergedCompiledCommandParameter result = merged.GetMatchingParameter(name, true, true, null); return this.Parameters[result.Parameter.Name]; } /// <summary> /// Gets the information about the parameters and parameter sets for /// this command. /// </summary> public ReadOnlyCollection<CommandParameterSetInfo> ParameterSets { get { if (_parameterSets == null) { Collection<CommandParameterSetInfo> parameterSetInfo = GenerateCommandParameterSetInfo(); _parameterSets = new ReadOnlyCollection<CommandParameterSetInfo>(parameterSetInfo); } return _parameterSets; } } // ParameterSets internal ReadOnlyCollection<CommandParameterSetInfo> _parameterSets; /// <summary> /// A possibly incomplete or even incorrect list of types the command could return. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public abstract ReadOnlyCollection<PSTypeName> OutputType { get; } /// <summary> /// Specifies whether this command was imported from a module or not. /// This is used in Get-Command to figure out which of the commands in module session state were imported. /// </summary> internal bool IsImported { get; set; } = false; /// <summary> /// The prefix that was used when importing this command /// </summary> internal string Prefix { get; set; } = ""; /// <summary> /// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter /// sets based on an argument list (so we can get the dynamic parameters.) /// </summary> internal virtual CommandInfo CreateGetCommandCopy(object[] argumentList) { throw new InvalidOperationException(); } /// <summary> /// Generates the parameter and parameter set info from the cmdlet metadata /// </summary> /// /// <returns> /// A collection of CommandParameterSetInfo representing the cmdlet metadata. /// </returns> /// /// <exception cref="ArgumentException"> /// The type name is invalid or the length of the type name /// exceeds 1024 characters. /// </exception> /// /// <exception cref="System.Security.SecurityException"> /// The caller does not have the required permission to load the assembly /// or create the type. /// </exception> /// /// <exception cref="ParsingMetadataException"> /// If more than int.MaxValue parameter-sets are defined for the command. /// </exception> /// /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> /// internal Collection<CommandParameterSetInfo> GenerateCommandParameterSetInfo() { Collection<CommandParameterSetInfo> result; if (IsGetCommandCopy && ImplementsDynamicParameters) { result = GetParameterMetadata(CommandMetadata, GetMergedCommandParameterMetadataSafely()); } else { result = GetCacheableMetadata(CommandMetadata); } return result; } /// <summary> /// Gets or sets whether this CmdletInfo instance is a copy used for get-command. /// If true, and the cmdlet supports dynamic parameters, it means that the dynamic /// parameter metadata will be merged into the parameter set information. /// </summary> internal bool IsGetCommandCopy { get; set; } /// <summary> /// Gets or sets the command line arguments/parameters that were specified /// which will allow for the dynamic parameters to be retrieved and their /// metadata merged into the parameter set information. /// </summary> internal object[] Arguments { get; set; } internal static Collection<CommandParameterSetInfo> GetCacheableMetadata(CommandMetadata metadata) { return GetParameterMetadata(metadata, metadata.StaticCommandParameterMetadata); } internal static Collection<CommandParameterSetInfo> GetParameterMetadata(CommandMetadata metadata, MergedCommandParameterMetadata parameterMetadata) { Collection<CommandParameterSetInfo> result = new Collection<CommandParameterSetInfo>(); if (parameterMetadata != null) { if (parameterMetadata.ParameterSetCount == 0) { const string parameterSetName = ParameterAttribute.AllParameterSets; result.Add( new CommandParameterSetInfo( parameterSetName, false, uint.MaxValue, parameterMetadata)); } else { int parameterSetCount = parameterMetadata.ParameterSetCount; for (int index = 0; index < parameterSetCount; ++index) { uint currentFlagPosition = (uint)0x1 << index; // Get the parameter set name string parameterSetName = parameterMetadata.GetParameterSetName(currentFlagPosition); // Is the parameter set the default? bool isDefaultParameterSet = (currentFlagPosition & metadata.DefaultParameterSetFlag) != 0; result.Add( new CommandParameterSetInfo( parameterSetName, isDefaultParameterSet, currentFlagPosition, parameterMetadata)); } } } return result; } // GetParameterMetadata } // CommandInfo /// <summary> /// Represents <see cref="System.Type"/>, but can be used where a real type /// might not be available, in which case the name of the type can be used. /// </summary> public class PSTypeName { /// <summary> /// This constructor is used when the type exists and is currently loaded. /// </summary> /// <param name="type">The type</param> public PSTypeName(Type type) { _type = type; if (_type != null) { Name = _type.FullName; } } /// <summary> /// This constructor is used when the type may not exist, or is not loaded. /// </summary> /// <param name="name">The name of the type</param> public PSTypeName(string name) { Name = name; _type = null; } /// <summary> /// This constructor is used when the type is defined in PowerShell. /// </summary> /// <param name="typeDefinitionAst">The type definition from the ast.</param> public PSTypeName(TypeDefinitionAst typeDefinitionAst) { if (typeDefinitionAst == null) { throw PSTraceSource.NewArgumentNullException("typeDefinitionAst"); } TypeDefinitionAst = typeDefinitionAst; Name = typeDefinitionAst.Name; } /// <summary> /// This constructor creates a type from a ITypeName. /// </summary> public PSTypeName(ITypeName typeName) { if (typeName == null) { throw PSTraceSource.NewArgumentNullException("typeName"); } _type = typeName.GetReflectionType(); if (_type != null) { Name = _type.FullName; } else { var t = typeName as TypeName; if (t != null && t._typeDefinitionAst != null) { TypeDefinitionAst = t._typeDefinitionAst; Name = TypeDefinitionAst.Name; } else { _type = null; Name = typeName.FullName; } } } /// <summary> /// Return the name of the type /// </summary> public string Name { get; } /// <summary> /// Return the type with metadata, or null if the type is not loaded. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public Type Type { get { if (!_typeWasCalculated) { if (_type == null) { if (TypeDefinitionAst != null) { _type = TypeDefinitionAst.Type; } else { TypeResolver.TryResolveType(Name, out _type); } } if (_type == null) { // We ignore the exception. if (Name != null && Name.StartsWith("[", StringComparison.OrdinalIgnoreCase) && Name.EndsWith("]", StringComparison.OrdinalIgnoreCase)) { string tmp = Name.Substring(1, Name.Length - 2); TypeResolver.TryResolveType(tmp, out _type); } } _typeWasCalculated = true; } return _type; } } private Type _type; /// <summary> /// When a type is defined by PowerShell, the ast for that type. /// </summary> public TypeDefinitionAst TypeDefinitionAst { get; private set; } private bool _typeWasCalculated; /// <summary> /// Returns a String that represents the current PSTypeName. /// </summary> /// <returns> String that represents the current PSTypeName.</returns> public override string ToString() { return Name ?? string.Empty; } } internal interface IScriptCommandInfo { ScriptBlock ScriptBlock { get; } } } // namespace System.Management.Automation
/* * 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.Collections; using System.Collections.Generic; using System.Net; using OpenMetaverse; using Nwc.XmlRpc; namespace OpenSim.Framework.Communications.Clients { public class GridClient { const int DEFAULT_TIMEOUT = 5000; public bool RegisterRegion(string gridServerURL, string sendKey, string receiveKey, RegionInfo regionInfo, out bool forcefulBanLines) { forcefulBanLines = true; Hashtable GridParams = new Hashtable(); // Login / Authentication GridParams["authkey"] = sendKey; GridParams["recvkey"] = receiveKey; GridParams["UUID"] = regionInfo.RegionID.ToString(); GridParams["sim_ip"] = regionInfo.ExternalHostName; GridParams["sim_port"] = regionInfo.InternalEndPoint.Port.ToString(); GridParams["region_locx"] = regionInfo.RegionLocX.ToString(); GridParams["region_locy"] = regionInfo.RegionLocY.ToString(); GridParams["sim_name"] = regionInfo.RegionName; GridParams["http_port"] = regionInfo.HttpPort.ToString(); GridParams["remoting_port"] = ConfigSettings.DefaultRegionRemotingPort.ToString(); GridParams["map-image-id"] = regionInfo.RegionSettings.TerrainImageID.ToString(); GridParams["originUUID"] = regionInfo.originRegionID.ToString(); GridParams["region_secret"] = regionInfo.regionSecret; GridParams["major_interface_version"] = VersionInfo.MajorInterfaceVersion.ToString(); GridParams["product"] = Convert.ToInt32(regionInfo.Product).ToString(); if (regionInfo.OutsideIP != null) GridParams["outside_ip"] = regionInfo.OutsideIP; if (regionInfo.MasterAvatarAssignedUUID != UUID.Zero) GridParams["master_avatar_uuid"] = regionInfo.MasterAvatarAssignedUUID.ToString(); else GridParams["master_avatar_uuid"] = regionInfo.EstateSettings.EstateOwner.ToString(); // Package into an XMLRPC Request ArrayList SendParams = new ArrayList(); SendParams.Add(GridParams); // Send Request string methodName = "simulator_login"; XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams); XmlRpcResponse GridResp; try { // The timeout should always be significantly larger than the timeout for the grid server to request // the initial status of the region before confirming registration. // GridResp = GridReq.Send(gridServerURL, 90000); GridResp = GridReq.Send(Util.XmlRpcRequestURI(gridServerURL, methodName), 90000); } catch (Exception e) { Exception e2 = new Exception( String.Format( "Unable to register region with grid at {0}. Grid service not running?", gridServerURL), e); throw e2; } Hashtable GridRespData = (Hashtable)GridResp.Value; // Hashtable griddatahash = GridRespData; // Process Response if (GridRespData.ContainsKey("error")) { string errorstring = (string)GridRespData["error"]; Exception e = new Exception( String.Format("Unable to connect to grid at {0}: {1}", gridServerURL, errorstring)); throw e; } else { if (GridRespData.ContainsKey("allow_forceful_banlines")) { if ((string)GridRespData["allow_forceful_banlines"] != "TRUE") { forcefulBanLines = false; } } } return true; } public bool DeregisterRegion(string gridServerURL, string sendKey, string receiveKey, RegionInfo regionInfo, out string errorMsg) { errorMsg = String.Empty; Hashtable GridParams = new Hashtable(); GridParams["UUID"] = regionInfo.RegionID.ToString(); // Package into an XMLRPC Request ArrayList SendParams = new ArrayList(); SendParams.Add(GridParams); // Send Request string methodName = "simulator_after_region_moved"; XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams); XmlRpcResponse GridResp = null; try { GridResp = GridReq.Send(Util.XmlRpcRequestURI(gridServerURL, methodName), 10000); } catch (Exception e) { Exception e2 = new Exception( String.Format( "Unable to deregister region with grid at {0}. Grid service not running?", gridServerURL), e); throw e2; } Hashtable GridRespData = (Hashtable)GridResp.Value; // Hashtable griddatahash = GridRespData; // Process Response if (GridRespData != null && GridRespData.ContainsKey("error")) { errorMsg = (string)GridRespData["error"]; return false; } return true; } public bool RequestNeighborInfo(string gridServerURL, string sendKey, string receiveKey, UUID regionUUID, out RegionInfo regionInfo, out string errorMsg) { // didn't find it so far, we have to go the long way regionInfo = null; errorMsg = String.Empty; Hashtable requestData = new Hashtable(); requestData["region_UUID"] = regionUUID.ToString(); requestData["authkey"] = sendKey; ArrayList SendParams = new ArrayList(); SendParams.Add(requestData); string methodName = "simulator_data_request"; XmlRpcRequest gridReq = new XmlRpcRequest(methodName, SendParams); XmlRpcResponse gridResp = null; try { gridResp = gridReq.Send(Util.XmlRpcRequestURI(gridServerURL, methodName), DEFAULT_TIMEOUT); } catch (Exception e) { errorMsg = e.Message; return false; } Hashtable responseData = (Hashtable)gridResp.Value; if (responseData.ContainsKey("error")) { errorMsg = (string)responseData["error"]; return false; ; } regionInfo = BuildRegionInfo(responseData, String.Empty); return true; } public bool RequestNeighborInfo(string gridServerURL, string sendKey, string receiveKey, ulong regionHandle, out RegionInfo regionInfo, out string errorMsg) { // didn't find it so far, we have to go the long way regionInfo = null; errorMsg = String.Empty; try { Hashtable requestData = new Hashtable(); requestData["region_handle"] = regionHandle.ToString(); requestData["authkey"] = sendKey; ArrayList SendParams = new ArrayList(); SendParams.Add(requestData); string methodName = "simulator_data_request"; XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams); XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(gridServerURL, methodName), DEFAULT_TIMEOUT); Hashtable responseData = (Hashtable)GridResp.Value; if (responseData.ContainsKey("error")) { errorMsg = (string)responseData["error"]; return false; } uint regX = Convert.ToUInt32((string)responseData["region_locx"]); uint regY = Convert.ToUInt32((string)responseData["region_locy"]); string externalHostName = (string)responseData["sim_ip"]; uint simPort = Convert.ToUInt32(responseData["sim_port"]); string regionName = (string)responseData["region_name"]; UUID regionID = new UUID((string)responseData["region_UUID"]); uint remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); uint httpPort = 9000; if (responseData.ContainsKey("http_port")) { httpPort = Convert.ToUInt32((string)responseData["http_port"]); } if (responseData.ContainsKey("product")) regionInfo.Product = (ProductRulesUse)Convert.ToInt32(responseData["product"]); else regionInfo.Product = ProductRulesUse.UnknownUse; string outsideIp = null; if (responseData.ContainsKey("outside_ip")) regionInfo.OutsideIP = (string)responseData["outside_ip"]; regionInfo = RegionInfo.Create(regionID, regionName, regX, regY, externalHostName, httpPort, simPort, remotingPort, outsideIp); } catch (Exception e) { errorMsg = e.Message; return false; } return true; } public bool RequestClosestRegion(string gridServerURL, string sendKey, string receiveKey, string regionName, out RegionInfo regionInfo, out string errorMsg) { regionInfo = null; errorMsg = String.Empty; try { Hashtable requestData = new Hashtable(); requestData["region_name_search"] = regionName; requestData["authkey"] = sendKey; ArrayList SendParams = new ArrayList(); SendParams.Add(requestData); string methodName = "simulator_data_request"; XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams); XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(gridServerURL, methodName), DEFAULT_TIMEOUT); Hashtable responseData = (Hashtable)GridResp.Value; if (responseData.ContainsKey("error")) { errorMsg = (string)responseData["error"]; return false; } regionInfo = BuildRegionInfo(responseData, String.Empty); } catch (Exception e) { errorMsg = e.Message; return false; } return true; } /// <summary> /// Performs a XML-RPC query against the grid server returning mapblock information in the specified coordinates /// </summary> /// <remarks>REDUNDANT - OGS1 is to be phased out in favour of OGS2</remarks> /// <param name="minX">Minimum X value</param> /// <param name="minY">Minimum Y value</param> /// <param name="maxX">Maximum X value</param> /// <param name="maxY">Maximum Y value</param> /// <returns>Hashtable of hashtables containing map data elements</returns> public bool MapBlockQuery(string gridServerURL, int minX, int minY, int maxX, int maxY, out Hashtable respData, out string errorMsg) { respData = new Hashtable(); errorMsg = String.Empty; Hashtable param = new Hashtable(); param["xmin"] = minX; param["ymin"] = minY; param["xmax"] = maxX; param["ymax"] = maxY; IList parameters = new ArrayList(); parameters.Add(param); try { string methodName = "map_block"; XmlRpcRequest req = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(gridServerURL, methodName), 10000); respData = (Hashtable)resp.Value; return true; } catch (Exception e) { errorMsg = e.Message; return false; } } public bool SearchRegionByName(string gridServerURL, IList parameters, out Hashtable respData, out string errorMsg) { respData = null; errorMsg = String.Empty; try { string methodName = "search_for_region_by_name"; XmlRpcRequest request = new XmlRpcRequest(methodName, parameters); XmlRpcResponse resp = request.Send(Util.XmlRpcRequestURI(gridServerURL, methodName), 10000); respData = (Hashtable)resp.Value; if (respData != null && respData.Contains("faultCode")) { errorMsg = (string)respData["faultString"]; return false; } return true; } catch (Exception e) { errorMsg = e.Message; return false; } } public RegionInfo BuildRegionInfo(Hashtable responseData, string prefix) { uint regX = Convert.ToUInt32((string)responseData[prefix + "region_locx"]); uint regY = Convert.ToUInt32((string)responseData[prefix + "region_locy"]); string internalIpStr = (string)responseData[prefix + "sim_ip"]; uint port = Convert.ToUInt32(responseData[prefix + "sim_port"]); IPEndPoint neighbourInternalEndPoint = new IPEndPoint(Util.GetHostFromDNS(internalIpStr), (int)port); RegionInfo regionInfo = new RegionInfo(regX, regY, neighbourInternalEndPoint, internalIpStr); regionInfo.RemotingPort = Convert.ToUInt32((string)responseData[prefix + "remoting_port"]); regionInfo.RemotingAddress = internalIpStr; if (responseData.ContainsKey(prefix + "http_port")) { regionInfo.HttpPort = Convert.ToUInt32((string)responseData[prefix + "http_port"]); } regionInfo.RegionID = new UUID((string)responseData[prefix + "region_UUID"]); regionInfo.RegionName = (string)responseData[prefix + "region_name"]; regionInfo.RegionSettings.TerrainImageID = new UUID((string)responseData[prefix + "map_UUID"]); if (responseData.ContainsKey("product")) regionInfo.Product = (ProductRulesUse)Convert.ToInt32(responseData["product"]); else regionInfo.Product = ProductRulesUse.UnknownUse; if (responseData.ContainsKey("outside_ip")) regionInfo.OutsideIP = (string)responseData["outside_ip"]; return regionInfo; } } }
// // TrackEditorDialog.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Mono.Addins; using Gtk; using Hyena.Gui; using Hyena.Widgets; using Banshee.Kernel; using Banshee.Sources; using Banshee.ServiceStack; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration.Schema; using Banshee.Widgets; using Banshee.Gui.Dialogs; using Banshee.Collection.Gui; namespace Banshee.Gui.TrackEditor { public class TrackEditorDialog : BansheeDialog { public delegate void EditorTrackOperationClosure (EditorTrackInfo track); private VBox main_vbox; private Frame header_image_frame; private Image header_image; private Label header_title_label; private Label header_artist_label; private Label header_album_label; private Label edit_notif_label; private object tooltip_host; private DateTime dialog_launch_datetime = DateTime.Now; private Notebook notebook; public Notebook Notebook { get { return notebook; } } private Button nav_backward_button; private Button nav_forward_button; private PulsingButton sync_all_button; private EditorMode mode; private List<ITrackEditorPage> pages = new List<ITrackEditorPage> (); public event EventHandler Navigated; private TrackEditorDialog (TrackListModel model, EditorMode mode) : base ( mode == EditorMode.Edit ? Catalog.GetString ("Track Editor") : Catalog.GetString ("Track Properties")) { this.mode = mode; LoadTrackModel (model); BorderWidth = 6; if (mode == EditorMode.Edit) { WidthRequest = 525; AddStockButton (Stock.Cancel, ResponseType.Cancel); AddStockButton (Stock.Save, ResponseType.Ok); } else { AddStockButton (Stock.Close, ResponseType.Close, true); SetSizeRequest (400, 500); } tooltip_host = TooltipSetter.CreateHost (); AddNavigationButtons (); main_vbox = new VBox (); main_vbox.Spacing = 10; main_vbox.BorderWidth = 6; main_vbox.Show (); VBox.PackStart (main_vbox, true, true, 0); BuildHeader (); BuildNotebook (); BuildFooter (); LoadModifiers (); LoadTrackToEditor (); } #region UI Building private void AddNavigationButtons () { if (TrackCount <= 1) { return; } nav_backward_button = new Button (Stock.GoBack); nav_backward_button.UseStock = true; nav_backward_button.Clicked += delegate { NavigateBackward (); }; nav_backward_button.Show (); TooltipSetter.Set (tooltip_host, nav_backward_button, Catalog.GetString ("Show the previous track")); nav_forward_button = new Button (Stock.GoForward); nav_forward_button.UseStock = true; nav_forward_button.Clicked += delegate { NavigateForward (); }; nav_forward_button.Show (); TooltipSetter.Set (tooltip_host, nav_forward_button, Catalog.GetString ("Show the next track")); ActionArea.PackStart (nav_backward_button, false, false, 0); ActionArea.PackStart (nav_forward_button, false, false, 0); ActionArea.SetChildSecondary (nav_backward_button, true); ActionArea.SetChildSecondary (nav_forward_button, true); } private void BuildHeader () { Table header = new Table (3, 3, false); header.ColumnSpacing = 5; header_image_frame = new Frame (); header_image = new Image (); header_image.IconName = "media-optical"; header_image.PixelSize = 64; header_image_frame.Add (header_image); header.Attach (header_image_frame, 0, 1, 0, 3, AttachOptions.Fill, AttachOptions.Expand, 0, 0); AddHeaderRow (header, 0, Catalog.GetString ("Title:"), out header_title_label); AddHeaderRow (header, 1, Catalog.GetString ("Artist:"), out header_artist_label); AddHeaderRow (header, 2, Catalog.GetString ("Album:"), out header_album_label); header.ShowAll (); main_vbox.PackStart (header, false, false, 0); } private void AddHeaderRow (Table header, uint row, string title, out Label label) { Label title_label = new Label (); title_label.Markup = String.Format ("<b>{0}</b>", GLib.Markup.EscapeText (title)); title_label.Xalign = 0.0f; header.Attach (title_label, 1, 2, row, row + 1, AttachOptions.Fill, AttachOptions.Expand, 0, 0); label = new Label (); label.Xalign = 0.0f; label.Ellipsize = Pango.EllipsizeMode.End; header.Attach (label, 2, 3, row, row + 1, AttachOptions.Fill | AttachOptions.Expand, AttachOptions.Expand, 0, 0); } private void BuildNotebook () { notebook = new Notebook (); notebook.Show (); foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/Gui/TrackEditor/NotebookPage")) { try { ITrackEditorPage page = (ITrackEditorPage)node.CreateInstance (); if ((mode == EditorMode.Edit && (page.PageType == PageType.Edit || page.PageType == PageType.View)) || (mode == EditorMode.View && (page.PageType == PageType.View || page.PageType == PageType.ViewOnly))) { pages.Add (page); page.Initialize (this); page.Widget.Show (); } } catch (Exception e) { Hyena.Log.Exception ("Failed to initialize NotebookPage extension node. Ensure it implements ITrackEditorPage.", e); } } pages.Sort (delegate (ITrackEditorPage a, ITrackEditorPage b) { return a.Order.CompareTo (b.Order); }); foreach (ITrackEditorPage page in pages) { Container container = page.Widget as Container; if (container == null) { VBox box = new VBox (); box.PackStart (page.Widget, true, true, 0); container = box; } container.BorderWidth = 12; notebook.AppendPage (container, page.TabWidget == null ? new Label (page.Title) : page.TabWidget); } main_vbox.PackStart (notebook, true, true, 0); } private void BuildFooter () { if (mode == EditorMode.View) { return; } HBox button_box = new HBox (); button_box.Spacing = 6; if (TrackCount > 1) { sync_all_button = new PulsingButton (); sync_all_button.FocusInEvent += delegate { ForeachWidget<SyncButton> (delegate (SyncButton button) { button.StartPulsing (); }); }; sync_all_button.FocusOutEvent += delegate { if (sync_all_button.State == StateType.Prelight) { return; } ForeachWidget<SyncButton> (delegate (SyncButton button) { button.StopPulsing (); }); }; sync_all_button.StateChanged += delegate { if (sync_all_button.HasFocus) { return; } ForeachWidget<SyncButton> (delegate (SyncButton button) { if (sync_all_button.State == StateType.Prelight) { button.StartPulsing (); } else { button.StopPulsing (); } }); }; sync_all_button.Clicked += delegate { InvokeFieldSync (); }; Alignment alignment = new Alignment (0.5f, 0.5f, 0.0f, 0.0f); HBox box = new HBox (); box.Spacing = 2; box.PackStart (new Image (Stock.Copy, IconSize.Button), false, false, 0); box.PackStart (new Label (Catalog.GetString ("Sync all field _values")), false, false, 0); alignment.Add (box); sync_all_button.Add (alignment); TooltipSetter.Set (tooltip_host, sync_all_button, Catalog.GetString ( "Apply the values of all common fields set for this track to all of the tracks selected in this editor")); button_box.PackStart (sync_all_button, false, false, 0); foreach (Widget child in ActionArea.Children) { child.SizeAllocated += OnActionAreaChildSizeAllocated; } edit_notif_label = new Label (); edit_notif_label.Xalign = 1.0f; button_box.PackEnd (edit_notif_label, false, false, 0); } main_vbox.PackStart (button_box, false, false, 0); button_box.ShowAll (); } private void LoadModifiers () { foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/Gui/TrackEditor/Modifier")) { try { ITrackEditorModifier mod = (ITrackEditorModifier)node.CreateInstance (); mod.Modify (this); } catch (Exception e) { Hyena.Log.Exception ("Failed to initialize TrackEditor/Modifier extension node. Ensure it implements ITrackEditorModifier.", e); } } } public void ForeachWidget<T> (WidgetAction<T> action) where T : class { for (int i = 0; i < notebook.NPages; i++) { GtkUtilities.ForeachWidget (notebook.GetNthPage (i) as Container, action); } } private void InvokeFieldSync () { ForeachWidget<SyncButton> (delegate (SyncButton button) { if (button.Sensitive) { button.Click (); } }); } private int action_area_children_allocated = 0; private void OnActionAreaChildSizeAllocated (object o, SizeAllocatedArgs args) { Widget [] children = ActionArea.Children; if (++action_area_children_allocated != children.Length) { return; } sync_all_button.WidthRequest = Math.Max (sync_all_button.Allocation.Width, (children[1].Allocation.X + children[1].Allocation.Width) - children[0].Allocation.X - 1); } #endregion #region Track Model/Changes API private CachedList<DatabaseTrackInfo> db_selection; private List<TrackInfo> memory_selection; private Dictionary<TrackInfo, EditorTrackInfo> edit_map = new Dictionary<TrackInfo, EditorTrackInfo> (); private int current_track_index; protected void LoadTrackModel (TrackListModel model) { DatabaseTrackListModel db_model = model as DatabaseTrackListModel; if (db_model != null) { db_selection = CachedList<DatabaseTrackInfo>.CreateFromModelSelection (db_model); } else { memory_selection = new List<TrackInfo> (); foreach (TrackInfo track in model.SelectedItems) { memory_selection.Add (track); } } } public void LoadTrackToEditor () { TrackInfo current_track = null; EditorTrackInfo editor_track = LoadTrack (current_track_index, out current_track); if (editor_track == null) { return; } // Update the Header header_title_label.Text = current_track.DisplayTrackTitle; header_artist_label.Text = current_track.DisplayArtistName; header_album_label.Text = current_track.DisplayAlbumTitle; if (edit_notif_label != null) { edit_notif_label.Markup = String.Format (Catalog.GetString ("<i>Editing {0} of {1} items</i>"), CurrentTrackIndex + 1, TrackCount); } ArtworkManager artwork = ServiceManager.Get<ArtworkManager> (); Gdk.Pixbuf cover_art = artwork.LookupScalePixbuf (current_track.ArtworkId, 64); header_image.Pixbuf = cover_art; if (cover_art == null) { header_image.IconName = "media-optical"; header_image.PixelSize = 64; header_image_frame.ShadowType = ShadowType.None; } else { header_image_frame.ShadowType = ShadowType.In; } // Disconnect all the undo adapters ForeachWidget<ICanUndo> (delegate (ICanUndo undoable) { undoable.DisconnectUndo (); }); foreach (ITrackEditorPage page in pages) { page.LoadTrack (editor_track); } // Connect all the undo adapters ForeachWidget<ICanUndo> (delegate (ICanUndo undoable) { undoable.ConnectUndo (editor_track); }); // Update Navigation if (TrackCount > 0 && nav_backward_button != null && nav_forward_button != null) { nav_backward_button.Sensitive = CanGoBackward; nav_forward_button.Sensitive = CanGoForward; } // If there was a widget focused already (eg the Title entry), GrabFocus on it, // which causes its text to be selected, ready for editing. Widget child = FocusChild; while (child != null) { Container container = child as Container; if (container != null) { child = container.FocusChild; } else if (child != null) { child.GrabFocus (); child = null; } } } public void ForeachNonCurrentTrack (EditorTrackOperationClosure closure) { for (int i = 0; i < TrackCount; i++) { if (i == current_track_index) { continue; } EditorTrackInfo track = LoadTrack (i); if (track != null) { closure (track); } } } public EditorTrackInfo LoadTrack (int index) { return LoadTrack (index, true); } public EditorTrackInfo LoadTrack (int index, bool alwaysLoad) { TrackInfo source_track; return LoadTrack (index, alwaysLoad, out source_track); } private EditorTrackInfo LoadTrack (int index, out TrackInfo sourceTrack) { return LoadTrack (index, true, out sourceTrack); } private EditorTrackInfo LoadTrack (int index, bool alwaysLoad, out TrackInfo sourceTrack) { sourceTrack = GetTrack (index); EditorTrackInfo editor_track = null; if (sourceTrack == null) { // Something bad happened here return null; } if (!edit_map.TryGetValue (sourceTrack, out editor_track) && alwaysLoad) { editor_track = new EditorTrackInfo (sourceTrack); editor_track.EditorIndex = index; editor_track.EditorCount = TrackCount; edit_map.Add (sourceTrack, editor_track); } return editor_track; } private TrackInfo GetTrack (int index) { return db_selection != null ? db_selection[index] : memory_selection[index]; } protected virtual void OnNavigated () { EventHandler handler = Navigated; if (handler != null) { handler (this, EventArgs.Empty); } } public void NavigateForward () { if (current_track_index < TrackCount - 1) { current_track_index++; LoadTrackToEditor (); OnNavigated (); } } public void NavigateBackward () { if (current_track_index > 0) { current_track_index--; LoadTrackToEditor (); OnNavigated (); } } public int TrackCount { get { return db_selection != null ? db_selection.Count : memory_selection.Count; } } public int CurrentTrackIndex { get { return current_track_index; } } public bool CanGoBackward { get { return current_track_index > 0; } } public bool CanGoForward { get { return current_track_index >= 0 && current_track_index < TrackCount - 1; } } #endregion #region Saving public void Save () { List<int> primary_sources = new List<int> (); // TODO: wrap in db transaction try { DatabaseTrackInfo.NotifySaved = false; for (int i = 0; i < TrackCount; i++) { // Save any tracks that were actually loaded into the editor EditorTrackInfo track = LoadTrack (i, false); if (track == null || track.SourceTrack == null) { continue; } SaveTrack (track); if (track.SourceTrack is DatabaseTrackInfo) { // If the source track is from the database, save its parent for notification later int id = (track.SourceTrack as DatabaseTrackInfo).PrimarySourceId; if (!primary_sources.Contains (id)) { primary_sources.Add (id); } } } // Finally, notify the affected primary sources foreach (int id in primary_sources) { PrimarySource psrc = PrimarySource.GetById (id); if (psrc != null) { psrc.NotifyTracksChanged (); } } } finally { DatabaseTrackInfo.NotifySaved = true; } } private void SaveTrack (EditorTrackInfo track) { TrackInfo.ExportableMerge (track, track.SourceTrack); track.SourceTrack.Save (); if (track.SourceTrack.TrackEqual (ServiceManager.PlayerEngine.CurrentTrack)) { TrackInfo.ExportableMerge (track, ServiceManager.PlayerEngine.CurrentTrack); ServiceManager.PlayerEngine.TrackInfoUpdated (); } } #endregion #region Static Helpers public static void RunEdit (TrackListModel model) { Run (model, EditorMode.Edit); } public static void RunView (TrackListModel model) { Run (model, EditorMode.View); } public static void Run (TrackListModel model, EditorMode mode) { TrackEditorDialog track_editor = new TrackEditorDialog (model, mode); track_editor.Response += delegate (object o, ResponseArgs args) { if (args.ResponseId == ResponseType.Ok) { track_editor.Save (); } else { int changed_count = 0; for (int i = 0; i < track_editor.TrackCount; i++) { EditorTrackInfo track = track_editor.LoadTrack (i, false); if (track != null) { track.GenerateDiff (); if (track.DiffCount > 0) { changed_count++; } } } if (changed_count == 0) { track_editor.Destroy (); return; } HigMessageDialog message_dialog = new HigMessageDialog ( track_editor, DialogFlags.Modal, MessageType.Warning, ButtonsType.None, String.Format (Catalog.GetPluralString ( "Save the changes made to the open track?", "Save the changes made to {0} of {1} open tracks?", track_editor.TrackCount), changed_count, track_editor.TrackCount), String.Empty ); UpdateCancelMessage (track_editor, message_dialog); uint timeout = 0; timeout = GLib.Timeout.Add (1000, delegate { bool result = UpdateCancelMessage (track_editor, message_dialog); if (!result) { timeout = 0; } return result; }); message_dialog.AddButton (Catalog.GetString ("Close _without Saving"), ResponseType.Close, false); message_dialog.AddButton (Stock.Cancel, ResponseType.Cancel, false); message_dialog.AddButton (Stock.Save, ResponseType.Ok, true); try { switch ((ResponseType)message_dialog.Run ()) { case ResponseType.Ok: track_editor.Save (); break; case ResponseType.Close: break; case ResponseType.Cancel: case ResponseType.DeleteEvent: return; } } finally { if (timeout > 0) { GLib.Source.Remove (timeout); } message_dialog.Destroy (); } } track_editor.Destroy (); }; track_editor.Run (); } private static bool UpdateCancelMessage (TrackEditorDialog trackEditor, HigMessageDialog messageDialog) { if (messageDialog == null) { return false; } messageDialog.MessageLabel.Text = String.Format (Catalog.GetString ( "If you don't save, changes from the last {0} will be permanently lost."), Banshee.Sources.DurationStatusFormatters.ApproximateVerboseFormatter ( DateTime.Now - trackEditor.dialog_launch_datetime ) ); return messageDialog.IsMapped; } #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.Collections.Generic; using Internal.IL; using Internal.Runtime; using Internal.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; using GenericVariance = Internal.Runtime.GenericVariance; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Given a type, EETypeNode writes an EEType data structure in the format expected by the runtime. /// /// Format of an EEType: /// /// Field Size | Contents /// ----------------+----------------------------------- /// UInt16 | Component Size. For arrays this is the element type size, for strings it is 2 (.NET uses /// | UTF16 character encoding), for generic type definitions it is the number of generic parameters, /// | and 0 for all other types. /// | /// UInt16 | EETypeKind (Normal, Array, Pointer type). Flags for: IsValueType, IsCrossModule, HasPointers, /// | HasOptionalFields, IsInterface, IsGeneric. Top 5 bits are used for enum CorElementType to /// | record whether it's back by an Int32, Int16 etc /// | /// Uint32 | Base size. /// | /// [Pointer Size] | Related type. Base type for regular types. Element type for arrays / pointer types. /// | /// UInt16 | Number of VTable slots (X) /// | /// UInt16 | Number of interfaces implemented by type (Y) /// | /// UInt32 | Hash code /// | /// [Pointer Size] | Pointer to containing TypeManager indirection cell /// | /// X * [Ptr Size] | VTable entries (optional) /// | /// Y * [Ptr Size] | Pointers to interface map data structures (optional) /// | /// [Pointer Size] | Pointer to finalizer method (optional) /// | /// [Pointer Size] | Pointer to optional fields (optional) /// | /// [Pointer Size] | Pointer to the generic type argument of a Nullable&lt;T&gt; (optional) /// | /// [Pointer Size] | Pointer to the generic type definition EEType (optional) /// | /// [Pointer Size] | Pointer to the generic argument and variance info (optional) /// </summary> public partial class EETypeNode : ObjectNode, IExportableSymbolNode, IEETypeNode, ISymbolDefinitionNode { protected TypeDesc _type; internal EETypeOptionalFieldsBuilder _optionalFieldsBuilder = new EETypeOptionalFieldsBuilder(); internal EETypeOptionalFieldsNode _optionalFieldsNode; public EETypeNode(NodeFactory factory, TypeDesc type) { if (type.IsCanonicalDefinitionType(CanonicalFormKind.Any)) Debug.Assert(this is CanonicalDefinitionEETypeNode); else if (type.IsCanonicalSubtype(CanonicalFormKind.Any)) Debug.Assert((this is CanonicalEETypeNode) || (this is NecessaryCanonicalEETypeNode)); Debug.Assert(!type.IsRuntimeDeterminedSubtype); _type = type; _optionalFieldsNode = new EETypeOptionalFieldsNode(this); // Note: The fact that you can't create invalid EETypeNode is used from many places that grab // an EETypeNode from the factory with the sole purpose of making sure the validation has run // and that the result of the positive validation is "cached" (by the presence of an EETypeNode). CheckCanGenerateEEType(factory, type); } protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public override bool ShouldSkipEmittingObjectNode(NodeFactory factory) { // If there is a constructed version of this node in the graph, emit that instead if (ConstructedEETypeNode.CreationAllowed(_type)) return factory.ConstructedTypeSymbol(_type).Marked; return false; } public override ObjectNode NodeForLinkage(NodeFactory factory) { return (ObjectNode)factory.NecessaryTypeSymbol(_type); } public ExportForm GetExportForm(NodeFactory factory) => factory.CompilationModuleGroup.GetExportTypeForm(Type); public TypeDesc Type => _type; public override ObjectNodeSection Section { get { if (_type.Context.Target.IsWindows) return ObjectNodeSection.ReadOnlyDataSection; else return ObjectNodeSection.DataSection; } } public int MinimumObjectSize => _type.Context.Target.PointerSize * 3; protected virtual bool EmitVirtualSlotsAndInterfaces => false; internal bool HasOptionalFields { get { return _optionalFieldsBuilder.IsAtLeastOneFieldUsed(); } } internal byte[] GetOptionalFieldsData() { return _optionalFieldsBuilder.GetBytes(); } public override bool StaticDependenciesAreComputed => true; public static string GetMangledName(TypeDesc type, NameMangler nameMangler) { return nameMangler.NodeMangler.EEType(type); } public virtual void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.NodeMangler.EEType(_type)); } int ISymbolNode.Offset => 0; int ISymbolDefinitionNode.Offset => GCDescSize; public override bool IsShareable => IsTypeNodeShareable(_type); private bool CanonFormTypeMayExist { get { if (!_type.HasInstantiation) return false; if (!_type.Context.SupportsCanon) return false; // If type is already in canon form, a canonically equivalent type cannot exist if (_type.IsCanonicalSubtype(CanonicalFormKind.Any)) return false; // If we reach here, a universal canon variant can exist (if universal canon is supported) if (_type.Context.SupportsUniversalCanon) return true; // Attempt to convert to canon. If the type changes, then the CanonForm exists return (_type.ConvertToCanonForm(CanonicalFormKind.Specific) != _type); } } public sealed override bool HasConditionalStaticDependencies { get { // If the type is can be converted to some interesting canon type, and this is the non-constructed variant of an EEType // we may need to trigger the fully constructed type to exist to make the behavior of the type consistent // in reflection and generic template expansion scenarios if (CanonFormTypeMayExist && ProjectNDependencyBehavior.EnableFullAnalysis) { return true; } if (!EmitVirtualSlotsAndInterfaces) return false; // Since the vtable is dependency driven, generate conditional static dependencies for // all possible vtable entries foreach (var method in _type.GetClosestDefType().GetAllMethods()) { if (method.IsVirtual) return true; } // If the type implements at least one interface, calls against that interface could result in this type's // implementation being used. if (_type.RuntimeInterfaces.Length > 0) return true; return false; } } public sealed override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory factory) { IEETypeNode maximallyConstructableType = factory.MaximallyConstructableType(_type); if (maximallyConstructableType != this) { // EEType upgrading from necessary to constructed if some template instantation exists that matches up if (CanonFormTypeMayExist) { yield return new CombinedDependencyListEntry(maximallyConstructableType, factory.MaximallyConstructableType(_type.ConvertToCanonForm(CanonicalFormKind.Specific)), "Trigger full type generation if canonical form exists"); if (_type.Context.SupportsUniversalCanon) yield return new CombinedDependencyListEntry(maximallyConstructableType, factory.MaximallyConstructableType(_type.ConvertToCanonForm(CanonicalFormKind.Universal)), "Trigger full type generation if universal canonical form exists"); } yield break; } if (!EmitVirtualSlotsAndInterfaces) yield break; DefType defType = _type.GetClosestDefType(); // If we're producing a full vtable, none of the dependencies are conditional. if (!factory.VTable(defType).HasFixedSlots) { foreach (MethodDesc decl in defType.EnumAllVirtualSlots()) { // Generic virtual methods are tracked by an orthogonal mechanism. if (decl.HasInstantiation) continue; MethodDesc impl = defType.FindVirtualFunctionTargetMethodOnObjectType(decl); if (impl.OwningType == defType && !impl.IsAbstract) { MethodDesc canonImpl = impl.GetCanonMethodTarget(CanonicalFormKind.Specific); yield return new CombinedDependencyListEntry(factory.MethodEntrypoint(canonImpl, _type.IsValueType), factory.VirtualMethodUse(decl), "Virtual method"); } } Debug.Assert( _type == defType || ((System.Collections.IStructuralEquatable)defType.RuntimeInterfaces).Equals(_type.RuntimeInterfaces, EqualityComparer<DefType>.Default)); // Add conditional dependencies for interface methods the type implements. For example, if the type T implements // interface IFoo which has a method M1, add a dependency on T.M1 dependent on IFoo.M1 being called, since it's // possible for any IFoo object to actually be an instance of T. foreach (DefType interfaceType in defType.RuntimeInterfaces) { Debug.Assert(interfaceType.IsInterface); foreach (MethodDesc interfaceMethod in interfaceType.GetAllMethods()) { if (interfaceMethod.Signature.IsStatic) continue; // Generic virtual methods are tracked by an orthogonal mechanism. if (interfaceMethod.HasInstantiation) continue; MethodDesc implMethod = defType.ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod); if (implMethod != null) { yield return new CombinedDependencyListEntry(factory.VirtualMethodUse(implMethod), factory.VirtualMethodUse(interfaceMethod), "Interface method"); } } } } } public static bool IsTypeNodeShareable(TypeDesc type) { return type.IsParameterizedType || type.IsFunctionPointer || type is InstantiatedType; } private void AddVirtualMethodUseDependencies(DependencyList dependencyList, NodeFactory factory) { DefType closestDefType = _type.GetClosestDefType(); if (_type.RuntimeInterfaces.Length > 0 && !factory.VTable(closestDefType).HasFixedSlots) { foreach (var implementedInterface in _type.RuntimeInterfaces) { // If the type implements ICastable, the methods are implicitly necessary if (implementedInterface == factory.ICastableInterface) { MethodDesc isInstDecl = implementedInterface.GetKnownMethod("IsInstanceOfInterface", null); MethodDesc getImplTypeDecl = implementedInterface.GetKnownMethod("GetImplType", null); MethodDesc isInstMethodImpl = _type.ResolveInterfaceMethodTarget(isInstDecl); MethodDesc getImplTypeMethodImpl = _type.ResolveInterfaceMethodTarget(getImplTypeDecl); if (isInstMethodImpl != null) dependencyList.Add(factory.VirtualMethodUse(isInstMethodImpl), "ICastable IsInst"); if (getImplTypeMethodImpl != null) dependencyList.Add(factory.VirtualMethodUse(getImplTypeMethodImpl), "ICastable GetImplType"); } // If any of the implemented interfaces have variance, calls against compatible interface methods // could result in interface methods of this type being used (e.g. IEnumberable<object>.GetEnumerator() // can dispatch to an implementation of IEnumerable<string>.GetEnumerator()). // For now, we will not try to optimize this and we will pretend all interface methods are necessary. bool allInterfaceMethodsAreImplicitlyUsed = false; if (implementedInterface.HasVariance) { TypeDesc interfaceDefinition = implementedInterface.GetTypeDefinition(); for (int i = 0; i < interfaceDefinition.Instantiation.Length; i++) { if (((GenericParameterDesc)interfaceDefinition.Instantiation[i]).Variance != 0 && !implementedInterface.Instantiation[i].IsValueType) { allInterfaceMethodsAreImplicitlyUsed = true; break; } } } if (!allInterfaceMethodsAreImplicitlyUsed && (_type.IsArray || _type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) && implementedInterface.HasInstantiation) { // NOTE: we need to also do this for generic interfaces on arrays because they have a weird casting rule // that doesn't require the implemented interface to be variant to consider it castable. // For value types, we only need this when the array is castable by size (int[] and ICollection<uint>), // or it's a reference type (Derived[] and ICollection<Base>). TypeDesc elementType = _type.IsArray ? ((ArrayType)_type).ElementType : _type.Instantiation[0]; allInterfaceMethodsAreImplicitlyUsed = CastingHelper.IsArrayElementTypeCastableBySize(elementType) || (elementType.IsDefType && !elementType.IsValueType); } if (allInterfaceMethodsAreImplicitlyUsed) { foreach (var interfaceMethod in implementedInterface.GetAllMethods()) { if (interfaceMethod.Signature.IsStatic) continue; // Generic virtual methods are tracked by an orthogonal mechanism. if (interfaceMethod.HasInstantiation) continue; MethodDesc implMethod = closestDefType.ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod); if (implMethod != null) { dependencyList.Add(factory.VirtualMethodUse(interfaceMethod), "Variant interface method"); dependencyList.Add(factory.VirtualMethodUse(implMethod), "Variant interface method"); } } } } } } internal static bool MethodHasNonGenericILMethodBody(MethodDesc method) { // Generic methods have their own generic dictionaries if (method.HasInstantiation) return false; // Abstract methods don't have a body if (method.IsAbstract) return false; // PInvoke methods, runtime imports, etc. are not permitted on generic types, // but let's not crash the compilation because of that. if (method.IsPInvoke || method.IsRuntimeImplemented) return false; // InternalCall functions do not really have entrypoints that need to be handled here if (method.IsInternalCall) return false; return true; } protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory) { DependencyList dependencies = new DependencyList(); // Include the optional fields by default. We don't know if optional fields will be needed until // all of the interface usage has been stabilized. If we end up not needing it, the EEType node will not // generate any relocs to it, and the optional fields node will instruct the object writer to skip // emitting it. dependencies.Add(new DependencyListEntry(_optionalFieldsNode, "Optional fields")); StaticsInfoHashtableNode.AddStaticsInfoDependencies(ref dependencies, factory, _type); if (EmitVirtualSlotsAndInterfaces) { if (!_type.IsArrayTypeWithoutGenericInterfaces()) { // Sealed vtables have relative pointers, so to minimize size, we build sealed vtables for the canonical types dependencies.Add(new DependencyListEntry(factory.SealedVTable(_type.ConvertToCanonForm(CanonicalFormKind.Specific)), "Sealed Vtable")); } AddVirtualMethodUseDependencies(dependencies, factory); // Also add the un-normalized vtable slices of implemented interfaces. // This is important to do in the scanning phase so that the compilation phase can find // vtable information for things like IEnumerator<List<__Canon>>. foreach (TypeDesc intface in _type.RuntimeInterfaces) dependencies.Add(factory.VTable(intface), "Interface vtable slice"); } if (factory.CompilationModuleGroup.PresenceOfEETypeImpliesAllMethodsOnType(_type)) { if (_type.IsArray || _type.IsDefType) { // If the compilation group wants this type to be fully promoted, ensure that all non-generic methods of the // type are generated. // This may be done for several reasons: // - The EEType may be going to be COMDAT folded with other EETypes generated in a different object file // This means their generic dictionaries need to have identical contents. The only way to achieve that is // by generating the entries for all methods that contribute to the dictionary, and sorting the dictionaries. // - The generic type may be imported into another module, in which case the generic dictionary imported // must represent all of the methods, as the set of used methods cannot be known at compile time // - As a matter of policy, the type and its methods may be exported for use in another module. The policy // may wish to specify that if a type is to be placed into a shared module, all of the methods associated with // it should be also be exported. foreach (var method in _type.GetClosestDefType().ConvertToCanonForm(CanonicalFormKind.Specific).GetAllMethods()) { if (!MethodHasNonGenericILMethodBody(method)) continue; dependencies.Add(factory.MethodEntrypoint(method.GetCanonMethodTarget(CanonicalFormKind.Specific)), "Ensure all methods on type due to CompilationModuleGroup policy"); } } } return dependencies; } public override ObjectData GetData(NodeFactory factory, bool relocsOnly) { ObjectDataBuilder objData = new ObjectDataBuilder(factory, relocsOnly); objData.RequireInitialPointerAlignment(); objData.AddSymbol(this); ComputeOptionalEETypeFields(factory, relocsOnly); OutputGCDesc(ref objData); OutputComponentSize(ref objData); OutputFlags(factory, ref objData); objData.EmitInt(BaseSize); OutputRelatedType(factory, ref objData); // Number of vtable slots will be only known later. Reseve the bytes for it. var vtableSlotCountReservation = objData.ReserveShort(); // Number of interfaces will only be known later. Reserve the bytes for it. var interfaceCountReservation = objData.ReserveShort(); objData.EmitInt(_type.GetHashCode()); objData.EmitPointerReloc(factory.TypeManagerIndirection); if (EmitVirtualSlotsAndInterfaces) { // Emit VTable Debug.Assert(objData.CountBytes - ((ISymbolDefinitionNode)this).Offset == GetVTableOffset(objData.TargetPointerSize)); SlotCounter virtualSlotCounter = SlotCounter.BeginCounting(ref /* readonly */ objData); OutputVirtualSlots(factory, ref objData, _type, _type, _type, relocsOnly); // Update slot count int numberOfVtableSlots = virtualSlotCounter.CountSlots(ref /* readonly */ objData); objData.EmitShort(vtableSlotCountReservation, checked((short)numberOfVtableSlots)); // Emit interface map SlotCounter interfaceSlotCounter = SlotCounter.BeginCounting(ref /* readonly */ objData); OutputInterfaceMap(factory, ref objData); // Update slot count int numberOfInterfaceSlots = interfaceSlotCounter.CountSlots(ref /* readonly */ objData); objData.EmitShort(interfaceCountReservation, checked((short)numberOfInterfaceSlots)); } else { // If we're not emitting any slots, the number of slots is zero. objData.EmitShort(vtableSlotCountReservation, 0); objData.EmitShort(interfaceCountReservation, 0); } OutputFinalizerMethod(factory, ref objData); OutputOptionalFields(factory, ref objData); OutputNullableTypeParameter(factory, ref objData); OutputSealedVTable(factory, relocsOnly, ref objData); OutputGenericInstantiationDetails(factory, ref objData); return objData.ToObjectData(); } /// <summary> /// Returns the offset within an EEType of the beginning of VTable entries /// </summary> /// <param name="pointerSize">The size of a pointer in bytes in the target architecture</param> public static int GetVTableOffset(int pointerSize) { return 16 + 2 * pointerSize; } protected virtual int GCDescSize => 0; protected virtual void OutputGCDesc(ref ObjectDataBuilder builder) { // Non-constructed EETypeNodes get no GC Desc Debug.Assert(GCDescSize == 0); } private void OutputComponentSize(ref ObjectDataBuilder objData) { if (_type.IsArray) { TypeDesc elementType = ((ArrayType)_type).ElementType; if (elementType == elementType.Context.UniversalCanonType) { objData.EmitShort(0); } else { int elementSize = elementType.GetElementSize().AsInt; // We validated that this will fit the short when the node was constructed. No need for nice messages. objData.EmitShort((short)checked((ushort)elementSize)); } } else if (_type.IsString) { objData.EmitShort(StringComponentSize.Value); } else { objData.EmitShort(0); } } private void OutputFlags(NodeFactory factory, ref ObjectDataBuilder objData) { UInt16 flags = EETypeBuilderHelpers.ComputeFlags(_type); if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) { // Generic array enumerators use special variance rules recognized by the runtime flags |= (UInt16)EETypeFlags.GenericVarianceFlag; } if (factory.TypeSystemContext.IsGenericArrayInterfaceType(_type)) { // Runtime casting logic relies on all interface types implemented on arrays // to have the variant flag set (even if all the arguments are non-variant). // This supports e.g. casting uint[] to ICollection<int> flags |= (UInt16)EETypeFlags.GenericVarianceFlag; } if (!(this is CanonicalDefinitionEETypeNode)) { foreach (DefType itf in _type.RuntimeInterfaces) { if (itf == factory.ICastableInterface) { flags |= (UInt16)EETypeFlags.ICastableFlag; break; } } } ISymbolNode relatedTypeNode = GetRelatedTypeNode(factory); // If the related type (base type / array element type / pointee type) is not part of this compilation group, and // the output binaries will be multi-file (not multiple object files linked together), indicate to the runtime // that it should indirect through the import address table if (relatedTypeNode != null && relatedTypeNode.RepresentsIndirectionCell) { flags |= (UInt16)EETypeFlags.RelatedTypeViaIATFlag; } if (HasOptionalFields) { flags |= (UInt16)EETypeFlags.OptionalFieldsFlag; } if (this is ClonedConstructedEETypeNode) { flags |= (UInt16)EETypeKind.ClonedEEType; } objData.EmitShort((short)flags); } protected virtual int BaseSize { get { int pointerSize = _type.Context.Target.PointerSize; int objectSize; if (_type.IsDefType) { LayoutInt instanceByteCount = ((DefType)_type).InstanceByteCount; if (instanceByteCount.IsIndeterminate) { // Some value must be put in, but the specific value doesn't matter as it // isn't used for specific instantiations, and the universal canon eetype // is never associated with an allocated object. objectSize = pointerSize; } else { objectSize = pointerSize + ((DefType)_type).InstanceByteCount.AsInt; // +pointerSize for SyncBlock } if (_type.IsValueType) objectSize += pointerSize; // + EETypePtr field inherited from System.Object } else if (_type.IsArray) { objectSize = 3 * pointerSize; // SyncBlock + EETypePtr + Length if (_type.IsMdArray) objectSize += 2 * sizeof(int) * ((ArrayType)_type).Rank; } else if (_type.IsPointer) { // These never get boxed and don't have a base size. Use a sentinel value recognized by the runtime. return ParameterizedTypeShapeConstants.Pointer; } else if (_type.IsByRef) { // These never get boxed and don't have a base size. Use a sentinel value recognized by the runtime. return ParameterizedTypeShapeConstants.ByRef; } else throw new NotImplementedException(); objectSize = AlignmentHelper.AlignUp(objectSize, pointerSize); objectSize = Math.Max(MinimumObjectSize, objectSize); if (_type.IsString) { // If this is a string, throw away objectSize we computed so far. Strings are special. // SyncBlock + EETypePtr + length + firstChar objectSize = 2 * pointerSize + sizeof(int) + StringComponentSize.Value; } return objectSize; } } protected static TypeDesc GetFullCanonicalTypeForCanonicalType(TypeDesc type) { if (type.IsCanonicalSubtype(CanonicalFormKind.Specific)) { return type.ConvertToCanonForm(CanonicalFormKind.Specific); } else if (type.IsCanonicalSubtype(CanonicalFormKind.Universal)) { return type.ConvertToCanonForm(CanonicalFormKind.Universal); } else { return type; } } protected virtual ISymbolNode GetBaseTypeNode(NodeFactory factory) { return _type.BaseType != null ? factory.NecessaryTypeSymbol(_type.BaseType) : null; } private ISymbolNode GetRelatedTypeNode(NodeFactory factory) { ISymbolNode relatedTypeNode = null; if (_type.IsArray || _type.IsPointer || _type.IsByRef) { var parameterType = ((ParameterizedType)_type).ParameterType; relatedTypeNode = factory.NecessaryTypeSymbol(parameterType); } else { TypeDesc baseType = _type.BaseType; if (baseType != null) { relatedTypeNode = GetBaseTypeNode(factory); } } return relatedTypeNode; } protected virtual void OutputRelatedType(NodeFactory factory, ref ObjectDataBuilder objData) { ISymbolNode relatedTypeNode = GetRelatedTypeNode(factory); if (relatedTypeNode != null) { objData.EmitPointerReloc(relatedTypeNode); } else { objData.EmitZeroPointer(); } } private void OutputVirtualSlots(NodeFactory factory, ref ObjectDataBuilder objData, TypeDesc implType, TypeDesc declType, TypeDesc templateType, bool relocsOnly) { Debug.Assert(EmitVirtualSlotsAndInterfaces); declType = declType.GetClosestDefType(); templateType = templateType.ConvertToCanonForm(CanonicalFormKind.Specific); var baseType = declType.BaseType; if (baseType != null) { Debug.Assert(templateType.BaseType != null); OutputVirtualSlots(factory, ref objData, implType, baseType, templateType.BaseType, relocsOnly); } // // In the universal canonical types case, we could have base types in the hierarchy that are partial universal canonical types. // The presence of these types could cause incorrect vtable layouts, so we need to fully canonicalize them and walk the // hierarchy of the template type of the original input type to detect these cases. // // Exmaple: we begin with Derived<__UniversalCanon> and walk the template hierarchy: // // class Derived<T> : Middle<T, MyStruct> { } // -> Template is Derived<__UniversalCanon> and needs a dictionary slot // // -> Basetype tempalte is Middle<__UniversalCanon, MyStruct>. It's a partial // Universal canonical type, so we need to fully canonicalize it. // // class Middle<T, U> : Base<U> { } // -> Template is Middle<__UniversalCanon, __UniversalCanon> and needs a dictionary slot // // -> Basetype template is Base<__UniversalCanon> // // class Base<T> { } // -> Template is Base<__UniversalCanon> and needs a dictionary slot. // // If we had not fully canonicalized the Middle class template, we would have ended up with Base<MyStruct>, which does not need // a dictionary slot, meaning we would have created a vtable layout that the runtime does not expect. // // The generic dictionary pointer occupies the first slot of each type vtable slice if (declType.HasGenericDictionarySlot() || templateType.HasGenericDictionarySlot()) { // All generic interface types have a dictionary slot, but only some of them have an actual dictionary. bool isInterfaceWithAnEmptySlot = declType.IsInterface && declType.ConvertToCanonForm(CanonicalFormKind.Specific) == declType; // Note: Canonical type instantiations always have a generic dictionary vtable slot, but it's empty // Note: If the current EETypeNode represents a universal canonical type, any dictionary slot must be empty if (declType.IsCanonicalSubtype(CanonicalFormKind.Any) || implType.IsCanonicalSubtype(CanonicalFormKind.Universal) || factory.LazyGenericsPolicy.UsesLazyGenerics(declType) || isInterfaceWithAnEmptySlot) objData.EmitZeroPointer(); else objData.EmitPointerReloc(factory.TypeGenericDictionary(declType)); } // It's only okay to touch the actual list of slots if we're in the final emission phase // or the vtable is not built lazily. if (relocsOnly && !factory.VTable(declType).HasFixedSlots) return; // Actual vtable slots follow IReadOnlyList<MethodDesc> virtualSlots = factory.VTable(declType).Slots; for (int i = 0; i < virtualSlots.Count; i++) { MethodDesc declMethod = virtualSlots[i]; // No generic virtual methods can appear in the vtable! Debug.Assert(!declMethod.HasInstantiation); MethodDesc implMethod = implType.GetClosestDefType().FindVirtualFunctionTargetMethodOnObjectType(declMethod); // Final NewSlot methods cannot be overridden, and therefore can be placed in the sealed-vtable to reduce the size of the vtable // of this type and any type that inherits from it. if (declMethod.CanMethodBeInSealedVTable() && !declType.IsArrayTypeWithoutGenericInterfaces() && !factory.IsCppCodegenTemporaryWorkaround) continue; if (!implMethod.IsAbstract) { MethodDesc canonImplMethod = implMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); objData.EmitPointerReloc(factory.MethodEntrypoint(canonImplMethod, implMethod.OwningType.IsValueType)); } else { objData.EmitZeroPointer(); } } } protected virtual IEETypeNode GetInterfaceTypeNode(NodeFactory factory, TypeDesc interfaceType) { return factory.NecessaryTypeSymbol(interfaceType); } protected virtual void OutputInterfaceMap(NodeFactory factory, ref ObjectDataBuilder objData) { Debug.Assert(EmitVirtualSlotsAndInterfaces); foreach (var itf in _type.RuntimeInterfaces) { objData.EmitPointerRelocOrIndirectionReference(GetInterfaceTypeNode(factory, itf)); } } private void OutputFinalizerMethod(NodeFactory factory, ref ObjectDataBuilder objData) { if (_type.HasFinalizer) { MethodDesc finalizerMethod = _type.GetFinalizer(); MethodDesc canonFinalizerMethod = finalizerMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); objData.EmitPointerReloc(factory.MethodEntrypoint(canonFinalizerMethod)); } } private void OutputOptionalFields(NodeFactory factory, ref ObjectDataBuilder objData) { if (HasOptionalFields) { objData.EmitPointerReloc(_optionalFieldsNode); } } private void OutputNullableTypeParameter(NodeFactory factory, ref ObjectDataBuilder objData) { if (_type.IsNullable) { objData.EmitPointerReloc(factory.NecessaryTypeSymbol(_type.Instantiation[0])); } } private void OutputSealedVTable(NodeFactory factory, bool relocsOnly, ref ObjectDataBuilder objData) { if (EmitVirtualSlotsAndInterfaces && !_type.IsArrayTypeWithoutGenericInterfaces()) { // Sealed vtables have relative pointers, so to minimize size, we build sealed vtables for the canonical types SealedVTableNode sealedVTable = factory.SealedVTable(_type.ConvertToCanonForm(CanonicalFormKind.Specific)); if (sealedVTable.BuildSealedVTableSlots(factory, relocsOnly) && sealedVTable.NumSealedVTableEntries > 0) objData.EmitReloc(sealedVTable, RelocType.IMAGE_REL_BASED_RELPTR32); } } private void OutputGenericInstantiationDetails(NodeFactory factory, ref ObjectDataBuilder objData) { if (_type.HasInstantiation && !_type.IsTypeDefinition) { objData.EmitPointerRelocOrIndirectionReference(factory.NecessaryTypeSymbol(_type.GetTypeDefinition())); GenericCompositionDetails details; if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) { // Generic array enumerators use special variance rules recognized by the runtime details = new GenericCompositionDetails(_type.Instantiation, new[] { GenericVariance.ArrayCovariant }); } else if (factory.TypeSystemContext.IsGenericArrayInterfaceType(_type)) { // Runtime casting logic relies on all interface types implemented on arrays // to have the variant flag set (even if all the arguments are non-variant). // This supports e.g. casting uint[] to ICollection<int> details = new GenericCompositionDetails(_type, forceVarianceInfo: true); } else details = new GenericCompositionDetails(_type); objData.EmitPointerReloc(factory.GenericComposition(details)); } } /// <summary> /// Populate the OptionalFieldsRuntimeBuilder if any optional fields are required. /// </summary> protected internal virtual void ComputeOptionalEETypeFields(NodeFactory factory, bool relocsOnly) { if (!relocsOnly && EmitVirtualSlotsAndInterfaces && InterfaceDispatchMapNode.MightHaveInterfaceDispatchMap(_type, factory)) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.DispatchMap, checked((uint)factory.InterfaceDispatchMapIndirection(Type).IndexFromBeginningOfArray)); } ComputeRareFlags(factory, relocsOnly); ComputeNullableValueOffset(); if (!relocsOnly) ComputeICastableVirtualMethodSlots(factory); ComputeValueTypeFieldPadding(); } void ComputeRareFlags(NodeFactory factory, bool relocsOnly) { uint flags = 0; MetadataType metadataType = _type as MetadataType; if (_type.IsNullable) { flags |= (uint)EETypeRareFlags.IsNullableFlag; // If the nullable type is not part of this compilation group, and // the output binaries will be multi-file (not multiple object files linked together), indicate to the runtime // that it should indirect through the import address table if (factory.NecessaryTypeSymbol(_type.Instantiation[0]).RepresentsIndirectionCell) flags |= (uint)EETypeRareFlags.NullableTypeViaIATFlag; } if (factory.TypeSystemContext.HasLazyStaticConstructor(_type)) { flags |= (uint)EETypeRareFlags.HasCctorFlag; } if (EETypeBuilderHelpers.ComputeRequiresAlign8(_type)) { flags |= (uint)EETypeRareFlags.RequiresAlign8Flag; } TargetArchitecture targetArch = _type.Context.Target.Architecture; if (metadataType != null && (targetArch == TargetArchitecture.ARM || targetArch == TargetArchitecture.ARMEL || targetArch == TargetArchitecture.ARM64) && metadataType.IsHfa) { flags |= (uint)EETypeRareFlags.IsHFAFlag; } if (metadataType != null && !_type.IsInterface && metadataType.IsAbstract) { flags |= (uint)EETypeRareFlags.IsAbstractClassFlag; } if (_type.IsByRefLike) { flags |= (uint)EETypeRareFlags.IsByRefLikeFlag; } if (EmitVirtualSlotsAndInterfaces && !_type.IsArrayTypeWithoutGenericInterfaces()) { SealedVTableNode sealedVTable = factory.SealedVTable(_type.ConvertToCanonForm(CanonicalFormKind.Specific)); if (sealedVTable.BuildSealedVTableSlots(factory, relocsOnly) && sealedVTable.NumSealedVTableEntries > 0) flags |= (uint)EETypeRareFlags.HasSealedVTableEntriesFlag; } if (flags != 0) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.RareFlags, flags); } } /// <summary> /// To support boxing / unboxing, the offset of the value field of a Nullable type is recorded on the EEType. /// This is variable according to the alignment requirements of the Nullable&lt;T&gt; type parameter. /// </summary> void ComputeNullableValueOffset() { if (!_type.IsNullable) return; if (!_type.Instantiation[0].IsCanonicalSubtype(CanonicalFormKind.Universal)) { var field = _type.GetKnownField("value"); // In the definition of Nullable<T>, the first field should be the boolean representing "hasValue" Debug.Assert(field.Offset.AsInt > 0); // The contract with the runtime states the Nullable value offset is stored with the boolean "hasValue" size subtracted // to get a small encoding size win. _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.NullableValueOffset, (uint)field.Offset.AsInt - 1); } } /// <summary> /// ICastable is a special interface whose two methods are not invoked using regular interface dispatch. /// Instead, their VTable slots are recorded on the EEType of an object implementing ICastable and are /// called directly. /// </summary> protected virtual void ComputeICastableVirtualMethodSlots(NodeFactory factory) { if (_type.IsInterface || !EmitVirtualSlotsAndInterfaces) return; foreach (DefType itf in _type.RuntimeInterfaces) { if (itf == factory.ICastableInterface) { MethodDesc isInstDecl = itf.GetKnownMethod("IsInstanceOfInterface", null); MethodDesc getImplTypeDecl = itf.GetKnownMethod("GetImplType", null); MethodDesc isInstMethodImpl = _type.ResolveInterfaceMethodTarget(isInstDecl); MethodDesc getImplTypeMethodImpl = _type.ResolveInterfaceMethodTarget(getImplTypeDecl); int isInstMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, isInstMethodImpl, _type); int getImplTypeMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, getImplTypeMethodImpl, _type); // Slots are usually -1, since these methods are usually in the sealed vtable of the base type. if (isInstMethodSlot != -1) _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableIsInstSlot, (uint)isInstMethodSlot); if (getImplTypeMethodSlot != -1) _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableGetImplTypeSlot, (uint)getImplTypeMethodSlot); } } } protected virtual void ComputeValueTypeFieldPadding() { // All objects that can have appreciable which can be derived from size compute ValueTypeFieldPadding. // Unfortunately, the name ValueTypeFieldPadding is now wrong to avoid integration conflicts. // Interfaces, sealed types, and non-DefTypes cannot be derived from if (_type.IsInterface || !_type.IsDefType || (_type.IsSealed() && !_type.IsValueType)) return; DefType defType = _type as DefType; Debug.Assert(defType != null); uint valueTypeFieldPaddingEncoded; if (defType.InstanceByteCount.IsIndeterminate) { valueTypeFieldPaddingEncoded = EETypeBuilderHelpers.ComputeValueTypeFieldPaddingFieldValue(0, 1, _type.Context.Target.PointerSize); } else { int numInstanceFieldBytes = defType.InstanceByteCountUnaligned.AsInt; // Check if we have a type derived from System.ValueType or System.Enum, but not System.Enum itself if (defType.IsValueType) { // Value types should have at least 1 byte of size Debug.Assert(numInstanceFieldBytes >= 1); // The size doesn't currently include the EEType pointer size. We need to add this so that // the number of instance field bytes consistently represents the boxed size. numInstanceFieldBytes += _type.Context.Target.PointerSize; } // For unboxing to work correctly and for supporting dynamic type loading for derived types we need // to record the actual size of the fields of a type without any padding for GC heap allocation (since // we can unbox into locals or arrays where this padding is not used, and because field layout for derived // types is effected by the unaligned base size). We don't want to store this information for all EETypes // since it's only relevant for value types, and derivable types so it's added as an optional field. It's // also enough to simply store the size of the padding (between 0 and 4 or 8 bytes for 32-bit and 0 and 8 or 16 bytes // for 64-bit) which cuts down our storage requirements. uint valueTypeFieldPadding = checked((uint)((BaseSize - _type.Context.Target.PointerSize) - numInstanceFieldBytes)); valueTypeFieldPaddingEncoded = EETypeBuilderHelpers.ComputeValueTypeFieldPaddingFieldValue(valueTypeFieldPadding, (uint)defType.InstanceFieldAlignment.AsInt, _type.Context.Target.PointerSize); } if (valueTypeFieldPaddingEncoded != 0) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ValueTypeFieldPadding, valueTypeFieldPaddingEncoded); } } protected override void OnMarked(NodeFactory context) { if (!context.IsCppCodegenTemporaryWorkaround) { Debug.Assert(_type.IsTypeDefinition || !_type.HasSameTypeDefinition(context.ArrayOfTClass), "Asking for Array<T> EEType"); } } /// <summary> /// Validates that it will be possible to create an EEType for '<paramref name="type"/>'. /// </summary> public static void CheckCanGenerateEEType(NodeFactory factory, TypeDesc type) { // Don't validate generic definitons if (type.IsGenericDefinition) { return; } // System.__Canon or System.__UniversalCanon if(type.IsCanonicalDefinitionType(CanonicalFormKind.Any)) { return; } // It must be possible to create an EEType for the base type of this type TypeDesc baseType = type.BaseType; if (baseType != null) { // Make sure EEType can be created for this. factory.NecessaryTypeSymbol(GetFullCanonicalTypeForCanonicalType(baseType)); } // We need EETypes for interfaces foreach (var intf in type.RuntimeInterfaces) { // Make sure EEType can be created for this. factory.NecessaryTypeSymbol(GetFullCanonicalTypeForCanonicalType(intf)); } // Validate classes, structs, enums, interfaces, and delegates DefType defType = type as DefType; if (defType != null) { // Ensure we can compute the type layout defType.ComputeInstanceLayout(InstanceLayoutKind.TypeAndFields); // // The fact that we generated an EEType means that someone can call RuntimeHelpers.RunClassConstructor. // We need to make sure this is possible. // if (factory.TypeSystemContext.HasLazyStaticConstructor(defType)) { defType.ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizesAndFields); } // Make sure instantiation length matches the expectation // TODO: it might be more resonable for the type system to enforce this (also for methods) if (defType.Instantiation.Length != defType.GetTypeDefinition().Instantiation.Length) { ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } foreach (TypeDesc typeArg in defType.Instantiation) { // ByRefs, pointers, function pointers, and System.Void are never valid instantiation arguments if (typeArg.IsByRef || typeArg.IsPointer || typeArg.IsFunctionPointer || typeArg.IsVoid || typeArg.IsByRefLike) { ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } // TODO: validate constraints } // Check the type doesn't have bogus MethodImpls or overrides and we can get the finalizer. defType.GetFinalizer(); } // Validate parameterized types ParameterizedType parameterizedType = type as ParameterizedType; if (parameterizedType != null) { TypeDesc parameterType = parameterizedType.ParameterType; // Make sure EEType can be created for this. factory.NecessaryTypeSymbol(parameterType); if (parameterizedType.IsArray) { if (parameterType.IsFunctionPointer) { // Arrays of function pointers are not currently supported ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } LayoutInt elementSize = parameterType.GetElementSize(); if (!elementSize.IsIndeterminate && elementSize.AsInt >= ushort.MaxValue) { // Element size over 64k can't be encoded in the GCDesc ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadValueClassTooLarge, parameterType); } if (((ArrayType)parameterizedType).Rank > 32) { ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadRankTooLarge, type); } if (parameterType.IsByRefLike) { // Arrays of byref-like types are not allowed ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } } // Validate we're not constructing a type over a ByRef if (parameterType.IsByRef) { // CLR compat note: "ldtoken int32&&" will actually fail with a message about int32&; "ldtoken int32&[]" // will fail with a message about being unable to create an array of int32&. This is a middle ground. ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } // It might seem reasonable to disallow array of void, but the CLR doesn't prevent that too hard. // E.g. "newarr void" will fail, but "newarr void[]" or "ldtoken void[]" will succeed. } // Function pointer EETypes are not currently supported if (type.IsFunctionPointer) { ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } } public static void AddDependenciesForStaticsNode(NodeFactory factory, TypeDesc type, ref DependencyList dependencies) { if ((factory.Target.Abi == TargetAbi.ProjectN) && !ProjectNDependencyBehavior.EnableFullAnalysis) return; // To ensure that the behvior of FieldInfo.GetValue/SetValue remains correct, // if a type may be reflectable, and it is generic, if a canonical instantiation of reflection // can exist which can refer to the associated type of this static base, ensure that type // has an EEType. (Which will allow the static field lookup logic to find the right type) if (type.HasInstantiation && factory.MetadataManager.SupportsReflection && !factory.MetadataManager.IsReflectionBlocked(type)) { // This current implementation is slightly generous, as it does not attempt to restrict // the created types to the maximum extent by investigating reflection data and such. Here we just // check if we support use of a canonically equivalent type to perform reflection. // We don't check to see if reflection is enabled on the type. if (factory.TypeSystemContext.SupportsUniversalCanon || (factory.TypeSystemContext.SupportsCanon && (type != type.ConvertToCanonForm(CanonicalFormKind.Specific)))) { if (dependencies == null) dependencies = new DependencyList(); dependencies.Add(factory.NecessaryTypeSymbol(type), "Static block owning type is necessary for canonically equivalent reflection"); } } } protected static void AddDependenciesForUniversalGVMSupport(NodeFactory factory, TypeDesc type, ref DependencyList dependencies) { if (factory.TypeSystemContext.SupportsUniversalCanon) { if ((factory.Target.Abi == TargetAbi.ProjectN) && !ProjectNDependencyBehavior.EnableFullAnalysis) return; foreach (MethodDesc method in type.GetMethods()) { if (!method.IsVirtual || !method.HasInstantiation) continue; if (method.IsAbstract) continue; TypeDesc[] universalCanonArray = new TypeDesc[method.Instantiation.Length]; for (int i = 0; i < universalCanonArray.Length; i++) universalCanonArray[i] = factory.TypeSystemContext.UniversalCanonType; MethodDesc universalCanonMethodNonCanonicalized = method.MakeInstantiatedMethod(new Instantiation(universalCanonArray)); MethodDesc universalCanonGVMMethod = universalCanonMethodNonCanonicalized.GetCanonMethodTarget(CanonicalFormKind.Universal); if (dependencies == null) dependencies = new DependencyList(); dependencies.Add(new DependencyListEntry(factory.MethodEntrypoint(universalCanonGVMMethod), "USG GVM Method")); } } } protected internal override int ClassCode => 1521789141; protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) { return comparer.Compare(_type, ((EETypeNode)other)._type); } int ISortableSymbolNode.ClassCode => ClassCode; int ISortableSymbolNode.CompareToImpl(ISortableSymbolNode other, CompilerComparer comparer) { return CompareToImpl((ObjectNode)other, comparer); } private struct SlotCounter { private int _startBytes; public static SlotCounter BeginCounting(ref /* readonly */ ObjectDataBuilder builder) => new SlotCounter { _startBytes = builder.CountBytes }; public int CountSlots(ref /* readonly */ ObjectDataBuilder builder) { int bytesEmitted = builder.CountBytes - _startBytes; Debug.Assert(bytesEmitted % builder.TargetPointerSize == 0); return bytesEmitted / builder.TargetPointerSize; } } } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - [email protected]) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.Warfare { /// <summary> /// Enumeration values for DetonationResult (warfare.detonationresult, Detonation Result, /// section 5.2) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public enum DetonationResult : byte { /// <summary> /// Other. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Other.")] Other = 0, /// <summary> /// Entity Impact. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Entity Impact.")] EntityImpact = 1, /// <summary> /// Entity Proximate Detonation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Entity Proximate Detonation.")] EntityProximateDetonation = 2, /// <summary> /// Ground Impact. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Ground Impact.")] GroundImpact = 3, /// <summary> /// Ground Proximate Detonation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Ground Proximate Detonation.")] GroundProximateDetonation = 4, /// <summary> /// Detonation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Detonation.")] Detonation = 5, /// <summary> /// None or No Detonation (Dud). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("None or No Detonation (Dud).")] NoneOrNoDetonationDud = 6, /// <summary> /// HE hit, small. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("HE hit, small.")] HEHitSmall = 7, /// <summary> /// HE hit, medium. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("HE hit, medium.")] HEHitMedium = 8, /// <summary> /// HE hit, large. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("HE hit, large.")] HEHitLarge = 9, /// <summary> /// Armor-piercing hit. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Armor-piercing hit.")] ArmorPiercingHit = 10, /// <summary> /// Dirt blast, small. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Dirt blast, small.")] DirtBlastSmall = 11, /// <summary> /// Dirt blast, medium. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Dirt blast, medium.")] DirtBlastMedium = 12, /// <summary> /// Dirt blast, large. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Dirt blast, large.")] DirtBlastLarge = 13, /// <summary> /// Water blast, small. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Water blast, small.")] WaterBlastSmall = 14, /// <summary> /// Water blast, medium. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Water blast, medium.")] WaterBlastMedium = 15, /// <summary> /// Water blast, large. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Water blast, large.")] WaterBlastLarge = 16, /// <summary> /// Air hit. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Air hit.")] AirHit = 17, /// <summary> /// Building hit, small. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Building hit, small.")] BuildingHitSmall = 18, /// <summary> /// Building hit, medium. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Building hit, medium.")] BuildingHitMedium = 19, /// <summary> /// Building hit, large. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Building hit, large.")] BuildingHitLarge = 20, /// <summary> /// Mine-clearing line charge. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Mine-clearing line charge.")] MineClearingLineCharge = 21, /// <summary> /// Environment object impact. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Environment object impact.")] EnvironmentObjectImpact = 22, /// <summary> /// Environment object proximate detonation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Environment object proximate detonation.")] EnvironmentObjectProximateDetonation = 23, /// <summary> /// Water Impact. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Water Impact.")] WaterImpact = 24, /// <summary> /// Air Burst. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Air Burst.")] AirBurst = 25, /// <summary> /// Kill with fragment type 1. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Kill with fragment type 1.")] KillWithFragmentType1 = 26, /// <summary> /// Kill with fragment type 2. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Kill with fragment type 2.")] KillWithFragmentType2 = 27, /// <summary> /// Kill with fragment type 3. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Kill with fragment type 3.")] KillWithFragmentType3 = 28, /// <summary> /// Kill with fragment type 1 after fly-out failure. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Kill with fragment type 1 after fly-out failure.")] KillWithFragmentType1AfterFlyOutFailure = 29, /// <summary> /// Kill with fragment type 2 after fly-out failure. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Kill with fragment type 2 after fly-out failure.")] KillWithFragmentType2AfterFlyOutFailure = 30, /// <summary> /// Miss due to fly-out failure. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Miss due to fly-out failure.")] MissDueToFlyOutFailure = 31, /// <summary> /// Miss due to end-game failure. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Miss due to end-game failure.")] MissDueToEndGameFailure = 32, /// <summary> /// Miss due to fly-out and end-game failure. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Miss due to fly-out and end-game failure.")] MissDueToFlyOutAndEndGameFailure = 33 } }
using System; using System.Data; using System.Data.OleDb; using System.Collections; using System.Configuration; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComMaterials.Plan.DS { public class MTR_MPSCycleOptionMasterDS { public MTR_MPSCycleOptionMasterDS() { } private const string THIS = "PCSComMaterials.Plan.DS.MTR_MPSCycleOptionMasterDS"; /// <summary> /// This method uses to add data to MTR_MPSCycleOptionMaster /// </summary> /// <Inputs> /// MTR_MPSCycleOptionMasterVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Thursday, July 21, 2005 /// </History> public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { MTR_MPSCycleOptionMasterVO objObject = (MTR_MPSCycleOptionMasterVO) pobjObjectVO; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); string strSql = "INSERT INTO MTR_MPSCycleOptionMaster(" + MTR_MPSCycleOptionMasterTable.CYCLE_FLD + "," + MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD + "," + MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD + "," + MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD + "," + MTR_MPSCycleOptionMasterTable.CCNID_FLD + "," + MTR_MPSCycleOptionMasterTable.GROUPBY_FLD + "," + MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD + ")" + "VALUES(?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.CYCLE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.CYCLE_FLD].Value = objObject.Cycle; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD].Value = objObject.AsOfDate; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD].Value = objObject.MPSGenDate; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD].Value = objObject.PlanHorizon; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.GROUPBY_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.GROUPBY_FLD].Value = objObject.GroupBy; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD].Value = objObject.Description; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to MTR_MPSCycleOptionMaster /// </summary> /// <Inputs> /// MTR_MPSCycleOptionMasterVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Thursday, July 21, 2005 /// </History> public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + MTR_MPSCycleOptionMasterTable.TABLE_NAME + " WHERE " + "MPSCycleOptionMasterID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to MTR_MPSCycleOptionMaster /// </summary> /// <Inputs> /// MTR_MPSCycleOptionMasterVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Thursday, July 21, 2005 /// </History> public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + MTR_MPSCycleOptionMasterTable.MPSCYCLEOPTIONMASTERID_FLD + "," + MTR_MPSCycleOptionMasterTable.CYCLE_FLD + "," + MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD + "," + MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD + "," + MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD + "," + MTR_MPSCycleOptionMasterTable.CCNID_FLD + "," + MTR_MPSCycleOptionMasterTable.GROUPBY_FLD + "," + MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD + " FROM " + MTR_MPSCycleOptionMasterTable.TABLE_NAME +" WHERE " + MTR_MPSCycleOptionMasterTable.MPSCYCLEOPTIONMASTERID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); MTR_MPSCycleOptionMasterVO objObject = new MTR_MPSCycleOptionMasterVO(); while (odrPCS.Read()) { objObject.MPSCycleOptionMasterID = int.Parse(odrPCS[MTR_MPSCycleOptionMasterTable.MPSCYCLEOPTIONMASTERID_FLD].ToString().Trim()); objObject.Cycle = odrPCS[MTR_MPSCycleOptionMasterTable.CYCLE_FLD].ToString().Trim(); objObject.AsOfDate = DateTime.Parse(odrPCS[MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD].ToString().Trim()); try { objObject.MPSGenDate = DateTime.Parse(odrPCS[MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD].ToString().Trim()); } catch{} objObject.PlanHorizon = int.Parse(odrPCS[MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD].ToString().Trim()); objObject.CCNID = int.Parse(odrPCS[MTR_MPSCycleOptionMasterTable.CCNID_FLD].ToString().Trim()); objObject.GroupBy = int.Parse(odrPCS[MTR_MPSCycleOptionMasterTable.GROUPBY_FLD].ToString().Trim()); objObject.Description = odrPCS[MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD].ToString().Trim(); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to MTR_MPSCycleOptionMaster /// </summary> /// <Inputs> /// MTR_MPSCycleOptionMasterVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Thursday, July 21, 2005 /// </History> public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; MTR_MPSCycleOptionMasterVO objObject = (MTR_MPSCycleOptionMasterVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE MTR_MPSCycleOptionMaster SET " + MTR_MPSCycleOptionMasterTable.CYCLE_FLD + "= ?" + "," + MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD + "= ?" + "," + MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD + "= ?" + "," + MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD + "= ?" + "," + MTR_MPSCycleOptionMasterTable.CCNID_FLD + "= ?" + "," + MTR_MPSCycleOptionMasterTable.GROUPBY_FLD + "= ?" + "," + MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD + "= ?" +" WHERE " + MTR_MPSCycleOptionMasterTable.MPSCYCLEOPTIONMASTERID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.CYCLE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.CYCLE_FLD].Value = objObject.Cycle; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD].Value = objObject.AsOfDate; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD].Value = objObject.MPSGenDate; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD].Value = objObject.PlanHorizon; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.GROUPBY_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.GROUPBY_FLD].Value = objObject.GroupBy; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD].Value = objObject.Description; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.MPSCYCLEOPTIONMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.MPSCYCLEOPTIONMASTERID_FLD].Value = objObject.MPSCycleOptionMasterID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to MTR_MPSCycleOptionMaster /// </summary> /// <Inputs> /// MTR_MPSCycleOptionMasterVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Thursday, July 21, 2005 /// </History> public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + MTR_MPSCycleOptionMasterTable.MPSCYCLEOPTIONMASTERID_FLD + "," + MTR_MPSCycleOptionMasterTable.CYCLE_FLD + "," + MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD + "," + MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD + "," + MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD + "," + MTR_MPSCycleOptionMasterTable.CCNID_FLD + "," + MTR_MPSCycleOptionMasterTable.GROUPBY_FLD + "," + MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD + " FROM " + MTR_MPSCycleOptionMasterTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,MTR_MPSCycleOptionMasterTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// CheckMRP /// </summary> /// <param name="pintMpsCycleOptionMasterID"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Thursday, October 20 2005</date> public int CheckMRP(int pintMpsCycleOptionMasterID) { const string METHOD_NAME = THIS + ".CheckMRP()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT COUNT(*)" + " FROM " + MTR_MRPCycleOptionMasterTable.TABLE_NAME + " WHERE " + MTR_MRPCycleOptionMasterTable.MPSCYCLEOPTIONMASTERID_FLD + " = " + pintMpsCycleOptionMasterID.ToString(); Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); object objReturn = ocmdPCS.ExecuteScalar(); return int.Parse(objReturn.ToString()); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// CheckDCPOption /// </summary> /// <param name="pintMpsCycleOptionMasterID"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Tuesday, December 13 2005</date> public int CheckDCPOption (int pintMpsCycleOptionMasterID) { const string METHOD_NAME = THIS + ".CheckDCPOption()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT COUNT(*)" + " FROM " + PRO_DCOptionMasterTable.TABLE_NAME //+ " WHERE " + PRO_DCOptionMasterTable.MPSCYCLEOPTIONMASTERID_FLD + " = " + pintMpsCycleOptionMasterID.ToString(); + " WHERE " + MTR_MPSCycleOptionMasterTable.MPSCYCLEOPTIONMASTERID_FLD + " = " + pintMpsCycleOptionMasterID.ToString(); Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); object objReturn = ocmdPCS.ExecuteScalar(); return int.Parse(objReturn.ToString()); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// This method uses to add data to MTR_MPSCycleOptionMaster /// </summary> /// <Inputs> /// MTR_MPSCycleOptionMasterVO /// </Inputs> /// <Returns> /// void /// </Returns> /// <History> /// Thursday, July 21, 2005 /// </History> public void UpdateDataSet(DataSet pdstData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + MTR_MPSCycleOptionMasterTable.MPSCYCLEOPTIONMASTERID_FLD + "," + MTR_MPSCycleOptionMasterTable.CYCLE_FLD + "," + MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD + "," + MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD + "," + MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD + "," + MTR_MPSCycleOptionMasterTable.CCNID_FLD + "," + MTR_MPSCycleOptionMasterTable.GROUPBY_FLD + "," + MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD + " FROM " + MTR_MPSCycleOptionMasterTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pdstData.EnforceConstraints = false; odadPCS.Update(pdstData,MTR_MPSCycleOptionMasterTable.TABLE_NAME); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// AddAndReturnID /// </summary> /// <param name="pobjMasterVO"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Wednesday, August 10 2005</date> public int AddAndReturnID(object pobjMasterVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { MTR_MPSCycleOptionMasterVO objObject = (MTR_MPSCycleOptionMasterVO) pobjMasterVO; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); string strSql = "INSERT INTO MTR_MPSCycleOptionMaster(" + MTR_MPSCycleOptionMasterTable.CYCLE_FLD + "," + MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD + "," + MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD + "," + MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD + "," + MTR_MPSCycleOptionMasterTable.CCNID_FLD + "," + MTR_MPSCycleOptionMasterTable.GROUPBY_FLD + "," + MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD + ")" + " VALUES(?,?,?,?,?,?,?)" + " SELECT @@IDENTITY" ; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.CYCLE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.CYCLE_FLD].Value = objObject.Cycle; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.ASOFDATE_FLD].Value = objObject.AsOfDate; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD, OleDbType.Date)); if (objObject.MPSGenDate != DateTime.MinValue) { ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD].Value = objObject.MPSGenDate; } else ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.MPSGENDATE_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.PLANHORIZON_FLD].Value = objObject.PlanHorizon; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.GROUPBY_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.GROUPBY_FLD].Value = objObject.GroupBy; ocmdPCS.Parameters.Add(new OleDbParameter(MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MTR_MPSCycleOptionMasterTable.DESCRIPTION_FLD].Value = objObject.Description; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); object objReturn = ocmdPCS.ExecuteScalar(); if (objReturn != null) { return int.Parse(objReturn.ToString()); } else { return 0; } } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
using System; using System.Threading.Tasks; using OrchardCore.ContentManagement.Display.Models; using OrchardCore.ContentManagement.Metadata.Models; using OrchardCore.ContentManagement.Metadata.Settings; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.DisplayManagement.ModelBinding; using OrchardCore.DisplayManagement.Views; namespace OrchardCore.ContentManagement.Display.ContentDisplay { /// <summary> /// Any concrete implementation of this class can provide shapes for any content item which has a specific Part. /// </summary> /// <typeparam name="TPart"></typeparam> public abstract class ContentPartDisplayDriver<TPart> : DisplayDriverBase, IContentPartDisplayDriver where TPart : ContentPart, new() { private ContentTypePartDefinition _typePartDefinition; public override ShapeResult Factory(string shapeType, Func<IBuildShapeContext, ValueTask<IShape>> shapeBuilder, Func<IShape, Task> initializeAsync) { // e.g., HtmlBodyPart.Summary, HtmlBodyPart-BlogPost, BagPart-LandingPage-Services // context.Shape is the ContentItem shape, we need to alter the part shape var result = base.Factory(shapeType, shapeBuilder, initializeAsync).Prefix(Prefix); if (_typePartDefinition != null) { // The stereotype is used when not displaying for a specific content type. We don't use [Stereotype] and [ContentType] at // the same time in an alternate because a content type is always of one stereotype. var stereotype = ""; var settings = _typePartDefinition.ContentTypeDefinition?.GetSettings<ContentTypeSettings>(); if (settings != null) { stereotype = settings.Stereotype; } if (!String.IsNullOrEmpty(stereotype) && !String.Equals("Content", stereotype, StringComparison.OrdinalIgnoreCase)) { stereotype = stereotype + "__"; } var partName = _typePartDefinition.Name; var partType = _typePartDefinition.PartDefinition.Name; var contentType = _typePartDefinition.ContentTypeDefinition.Name; var editorPartType = GetEditorShapeType(_typePartDefinition); if (partType == shapeType || editorPartType == shapeType) { // HtmlBodyPart, Services result.Differentiator(partName); } else { // ListPart-ListPartFeed result.Differentiator($"{partName}-{shapeType}"); } result.Displaying(ctx => { string[] displayTypes; if (editorPartType == shapeType) { displayTypes = new[] { "_" + ctx.Shape.Metadata.DisplayType }; } else { displayTypes = new[] { "", "_" + ctx.Shape.Metadata.DisplayType }; // [ShapeType]_[DisplayType], e.g. HtmlBodyPart.Summary, BagPart.Summary, ListPartFeed.Summary ctx.Shape.Metadata.Alternates.Add($"{shapeType}_{ctx.Shape.Metadata.DisplayType}"); } if (shapeType == partType || shapeType == editorPartType) { foreach (var displayType in displayTypes) { // [ContentType]_[DisplayType]__[PartType], e.g. Blog-HtmlBodyPart, LandingPage-BagPart ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{partType}"); if (!String.IsNullOrEmpty(stereotype)) { // [Stereotype]__[DisplayType]__[PartType], e.g. Widget-ContentsMetadata ctx.Shape.Metadata.Alternates.Add($"{stereotype}{displayType}__{partType}"); } } if (partType != partName) { foreach (var displayType in displayTypes) { // [ContentType]_[DisplayType]__[PartName], e.g. LandingPage-Services ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{partName}"); if (!String.IsNullOrEmpty(stereotype)) { // [Stereotype]_[DisplayType]__[PartName], e.g. LandingPage-Services ctx.Shape.Metadata.Alternates.Add($"{stereotype}{displayType}__{partName}"); } } } } else { foreach (var displayType in displayTypes) { // [ContentType]_[DisplayType]__[PartType]__[ShapeType], e.g. Blog-ListPart-ListPartFeed ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{partType}__{shapeType}"); if (!String.IsNullOrEmpty(stereotype)) { // [Stereotype]_[DisplayType]__[PartType]__[ShapeType], e.g. Blog-ListPart-ListPartFeed ctx.Shape.Metadata.Alternates.Add($"{stereotype}{displayType}__{partType}__{shapeType}"); } } if (partType != partName) { foreach (var displayType in displayTypes) { // [ContentType]_[DisplayType]__[PartName]__[ShapeType], e.g. LandingPage-Services-BagPartSummary ctx.Shape.Metadata.Alternates.Add($"{contentType}{displayType}__{partName}__{shapeType}"); if (!String.IsNullOrEmpty(stereotype)) { // [Stereotype]_[DisplayType]__[PartName]__[ShapeType], e.g. LandingPage-Services-BagPartSummary ctx.Shape.Metadata.Alternates.Add($"{stereotype}{displayType}__{partName}__{shapeType}"); } } } } }); } return result; } async Task<IDisplayResult> IContentPartDisplayDriver.BuildDisplayAsync(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, BuildDisplayContext context) { var part = contentPart as TPart; if (part == null) { return null; } using (BuildPrefix(typePartDefinition, context.HtmlFieldPrefix)) { _typePartDefinition = typePartDefinition; var buildDisplayContext = new BuildPartDisplayContext(typePartDefinition, context); var result = await DisplayAsync(part, buildDisplayContext); _typePartDefinition = null; return result; } } async Task<IDisplayResult> IContentPartDisplayDriver.BuildEditorAsync(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, BuildEditorContext context) { var part = contentPart as TPart; if (part == null) { return null; } using (BuildPrefix(typePartDefinition, context.HtmlFieldPrefix)) { _typePartDefinition = typePartDefinition; var buildEditorContext = new BuildPartEditorContext(typePartDefinition, context); var result = await EditAsync(part, buildEditorContext); _typePartDefinition = null; return result; } } async Task<IDisplayResult> IContentPartDisplayDriver.UpdateEditorAsync(ContentPart contentPart, ContentTypePartDefinition typePartDefinition, UpdateEditorContext context) { var part = contentPart as TPart; if (part == null) { return null; } using (BuildPrefix(typePartDefinition, context.HtmlFieldPrefix)) { var updateEditorContext = new UpdatePartEditorContext(typePartDefinition, context); var result = await UpdateAsync(part, context.Updater, updateEditorContext); part.ContentItem.Apply(typePartDefinition.Name, part); return result; } } public virtual Task<IDisplayResult> DisplayAsync(TPart part, BuildPartDisplayContext context) { return Task.FromResult(Display(part, context)); } public virtual IDisplayResult Display(TPart part, BuildPartDisplayContext context) { return Display(part); } public virtual IDisplayResult Display(TPart part) { return null; } public virtual Task<IDisplayResult> EditAsync(TPart part, BuildPartEditorContext context) { return Task.FromResult(Edit(part, context)); } public virtual IDisplayResult Edit(TPart part, BuildPartEditorContext context) { return Edit(part); } public virtual IDisplayResult Edit(TPart part) { return null; } public virtual Task<IDisplayResult> UpdateAsync(TPart part, IUpdateModel updater, UpdatePartEditorContext context) { return UpdateAsync(part, context); } public virtual Task<IDisplayResult> UpdateAsync(TPart part, UpdatePartEditorContext context) { return UpdateAsync(part, context.Updater); } public virtual Task<IDisplayResult> UpdateAsync(TPart part, IUpdateModel updater) { return Task.FromResult<IDisplayResult>(null); } protected string GetEditorShapeType(string shapeType, ContentTypePartDefinition typePartDefinition) { var editor = typePartDefinition.Editor(); return !String.IsNullOrEmpty(editor) ? shapeType + "__" + editor : shapeType; } protected string GetEditorShapeType(string shapeType, BuildPartEditorContext context) { return GetEditorShapeType(shapeType, context.TypePartDefinition); } protected string GetEditorShapeType(ContentTypePartDefinition typePartDefinition) { return GetEditorShapeType(typeof(TPart).Name + "_Edit", typePartDefinition); } protected string GetEditorShapeType(BuildPartEditorContext context) { return GetEditorShapeType(context.TypePartDefinition); } protected string GetDisplayShapeType(string shapeType, BuildPartDisplayContext context) { var displayMode = context.TypePartDefinition.DisplayMode(); return !String.IsNullOrEmpty(displayMode) ? shapeType + "_Display__" + displayMode : shapeType; } protected string GetDisplayShapeType(BuildPartDisplayContext context) { return GetDisplayShapeType(typeof(TPart).Name, context); } private TempPrefix BuildPrefix(ContentTypePartDefinition typePartDefinition, string htmlFieldPrefix) { var tempPrefix = new TempPrefix(this, Prefix); Prefix = typePartDefinition.Name; if (!String.IsNullOrEmpty(htmlFieldPrefix)) { Prefix = htmlFieldPrefix + "." + Prefix; } return tempPrefix; } /// <summary> /// Restores the previous prefix automatically /// </summary> private class TempPrefix : IDisposable { private readonly ContentPartDisplayDriver<TPart> _driver; private readonly string _originalPrefix; public TempPrefix(ContentPartDisplayDriver<TPart> driver, string originalPrefix) { _driver = driver; _originalPrefix = originalPrefix; } public void Dispose() { _driver.Prefix = _originalPrefix; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.Expressions.Json { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq.Expressions; #if SUPPORTS_BIGINTEGER using System.Numerics; #endif using Bond.Expressions.Pull; using Bond.Protocols; using Newtonsoft.Json; public class SimpleJsonParser<R> : JsonParser<R> where R : IJsonReader { static readonly Dictionary<BondDataType, JsonToken> ScalarTokenTypes = new Dictionary<BondDataType, JsonToken> { { BondDataType.BT_BOOL, JsonToken.Boolean }, { BondDataType.BT_FLOAT, JsonToken.Float }, { BondDataType.BT_DOUBLE, JsonToken.Float }, { BondDataType.BT_INT8, JsonToken.Integer }, { BondDataType.BT_INT16, JsonToken.Integer }, { BondDataType.BT_INT32, JsonToken.Integer }, { BondDataType.BT_INT64, JsonToken.Integer }, { BondDataType.BT_UINT8, JsonToken.Integer }, { BondDataType.BT_UINT16, JsonToken.Integer }, { BondDataType.BT_UINT32, JsonToken.Integer }, { BondDataType.BT_UINT64, JsonToken.Integer }, { BondDataType.BT_STRING, JsonToken.String }, { BondDataType.BT_WSTRING, JsonToken.String }, }; public SimpleJsonParser(RuntimeSchema schema) : base(schema, flatten: true) { } public SimpleJsonParser(Type type) : base(Bond.Schema.GetRuntimeSchema(type), flatten: true) { } protected SimpleJsonParser(SimpleJsonParser<R> that, RuntimeSchema schema) : base(that, schema, flatten: true) { } public override Expression Container(BondDataType? expectedType, ContainerHandler handler) { var parser = new SimpleJsonParser<R>(this, Schema.GetElementSchema()); var elementType = Expression.Constant(Schema.TypeDef.element.id); // if the json contains null instead of an array, simulate an empty list to deserialize a null value // into a nullable var readJsonNullAsEmptyList = Expression.Block( Reader.Read(), handler(parser, elementType, Expression.Constant(false), Expression.Constant(0), null)); // if the json contains an array, read the array into the list var readJsonArrayAsList = Expression.Block( Reader.Read(), handler(parser, elementType, JsonTokenNotEquals(JsonToken.EndArray), Expression.Constant(0), null), Reader.Read()); return Expression.IfThenElse( JsonTokenEquals(JsonToken.Null), readJsonNullAsEmptyList, Expression.IfThenElse( JsonTokenEquals(JsonToken.StartArray), readJsonArrayAsList, ThrowUnexpectedInput("Expected JSON array or null."))); } public override Expression Map(BondDataType? expectedKeyType, BondDataType? expectedValueType, MapHandler handler) { var keyParser = new SimpleJsonParser<R>(this, Schema.GetKeySchema()); var valueParser = new SimpleJsonParser<R>(this, Schema.GetElementSchema()); var keyType = Expression.Constant(Schema.TypeDef.key.id); var valueType = Expression.Constant(Schema.TypeDef.element.id); var next = JsonTokenNotEquals(JsonToken.EndArray); return Expression.Block( Reader.Read(), handler(keyParser, valueParser, keyType, valueType, next, next, Expression.Constant(0)), Reader.Read()); } public override Expression Blob(Expression count) { // null means that blobs will be handled as byte arrays return null; } public override Expression Scalar(Expression valueType, BondDataType expectedType, ValueHandler handler) { JsonToken scalarTokenType; if (!ScalarTokenTypes.TryGetValue(expectedType, out scalarTokenType)) { Debug.Assert(false, "Scalar should be called only on scalar expected types."); } Expression convertedValue; if (scalarTokenType == JsonToken.Integer) { // reader.Value is a boxed long and must be unboxed to the right type in order to // avoid an InvalidCastException. convertedValue = Expression.Convert(Reader.Value, typeof(long)); } else if (scalarTokenType == JsonToken.Float) { convertedValue = Expression.Convert(Reader.Value, typeof(double)); } else { convertedValue = Reader.Value; } var errorMessage = StringExpression.Format( "Invalid input, expected JSON token of type {0}, encountered {1}", Expression.Constant(scalarTokenType, typeof(object)), Expression.Convert(Reader.TokenType, typeof(object))); Expression embeddedExpression = handler(convertedValue); #if SUPPORTS_BIGINTEGER if (expectedType == BondDataType.BT_UINT64 && scalarTokenType == JsonToken.Integer) { embeddedExpression = Expression.IfThenElse( Expression.TypeIs(Reader.Value, typeof(long)), embeddedExpression, handler(Expression.Convert(Reader.Value, typeof(BigInteger)))); } #endif var handleValue = Expression.IfThenElse( JsonTokenEquals(scalarTokenType), embeddedExpression, ThrowUnexpectedInput(errorMessage)); // If a floating point value is expected also accept an integer if (scalarTokenType == JsonToken.Float) { handleValue = Expression.IfThenElse( JsonTokenEquals(JsonToken.Integer), handler(Expression.Convert(Reader.Value, typeof(long))), handleValue); } return Expression.Block( handleValue, Reader.Read()); } protected override IStateMachine<JsonToken> CreateStateMachine(IEnumerable<TransformSchemaPair> transforms, ParameterExpression requiredFields) { return new StateMachine<JsonToken> { InitialState = State.BeforeStructObject, FinalState = State.Finished, Default = ThrowUnexpectedState, TokenTransitions = new[] { new TokenTransition<JsonToken> { Token = JsonToken.None, Default = ThrowUnexpectedState, StateTransitions = new[] { new StateTransition(State.BeforeStructObject, state => Reader.Read()) } }, new TokenTransition<JsonToken> { Token = JsonToken.StartObject, Default = ThrowUnexpectedState, StateTransitions = new[] { new StateTransition(State.BeforeStructObject, State.InStructObject, state => Reader.Read()) } }, new TokenTransition<JsonToken> { Token = JsonToken.EndObject, StateTransitions = new[] { new StateTransition(State.InStructObject, State.Finished, state => Reader.Read()) } }, new TokenTransition<JsonToken> { Token = JsonToken.PropertyName, Default = ThrowUnexpectedState, StateTransitions = new[] { new StateTransition(State.InStructObject, state => ProcessField(requiredFields, transforms)) } } } }; } Expression ThrowUnexpectedState(Expression state) { return ThrowExpression.InvalidDataException( StringExpression.Format( "Unexpected JsonToken '{0}' at state {1} (line {2} position {3})", Expression.Convert(Reader.TokenType, typeof(object)), Expression.Convert(state, typeof(object)), Expression.Convert(Reader.LineNumber, typeof(object)), Expression.Convert(Reader.LinePosition, typeof(object)))); } Expression ThrowUnexpectedInput(Expression errorMessage) { return ThrowExpression.InvalidDataException( StringExpression.Format( "{0} (line {1} position {2})", errorMessage, Expression.Convert(Reader.LineNumber, typeof(object)), Expression.Convert(Reader.LinePosition, typeof(object)))); } Expression ThrowUnexpectedInput(string errorMessage) { return ThrowUnexpectedInput(Expression.Constant(errorMessage)); } Expression ProcessField(ParameterExpression requiredFields, IEnumerable<TransformSchemaPair> transforms) { // unknown fields are skipped (read past the unknown PropertyName then skip the value) Expression body = Expression.Block( Reader.Read(), SkipValue()); var requiredIndex = 0; foreach (var pair in transforms) { var currentSchema = pair.Schema; var currentTransform = pair.Transform; var structDef = currentSchema.StructDef; var index = 0; foreach (var field in currentTransform.Fields) { var fieldDef = structDef.fields[index++]; Debug.Assert(field.Id == fieldDef.id); var parser = new SimpleJsonParser<R>(this, currentSchema.GetFieldSchema(fieldDef)); // chain ifs on field name to handle the value on the right field handler var handleField = field.Value(parser, Expression.Constant(fieldDef.type.id)); if (fieldDef.metadata.modifier == Modifier.Required) { handleField = Expression.Block(RequiredFields.Mark(requiredFields, requiredIndex++), handleField); } string name; body = Expression.IfThenElse( PropertyNameEquals(fieldDef.metadata.attributes.TryGetValue( SimpleJsonWriter.NameAttribute, out name) ? name : fieldDef.metadata.name), Expression.Block(Read(), handleField), body); } } return body; } Expression PropertyNameEquals(string name) { return Expression.Equal(Expression.Convert(Reader.Value, typeof(string)), Expression.Constant(name)); } Expression JsonTokenEquals(JsonToken token) { return Expression.Equal(Reader.TokenType, Expression.Constant(token)); } Expression JsonTokenNotEquals(JsonToken token) { return Expression.NotEqual(Reader.TokenType, Expression.Constant(token)); } Expression SkipValue() { return Expression.Block( Expression.IfThen( Expression.OrElse( Expression.Equal(Reader.TokenType, Expression.Constant(JsonToken.StartObject)), Expression.Equal(Reader.TokenType, Expression.Constant(JsonToken.StartArray))), Reader.Skip()), Reader.Read()); } static class State { public const byte BeforeStructObject = 1; public const byte InStructObject = 2; public const byte Finished = 5; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Base class for interop targets. /// </summary> [SuppressMessage("ReSharper", "LocalVariableHidesMember")] internal abstract class PlatformTarget { /** */ protected const int False = 0; /** */ protected const int True = 1; /** */ protected const int Error = -1; /** */ public const int OpNone = -2; /** */ private static readonly Dictionary<Type, FutureType> IgniteFutureTypeMap = new Dictionary<Type, FutureType> { {typeof(bool), FutureType.Bool}, {typeof(byte), FutureType.Byte}, {typeof(char), FutureType.Char}, {typeof(double), FutureType.Double}, {typeof(float), FutureType.Float}, {typeof(int), FutureType.Int}, {typeof(long), FutureType.Long}, {typeof(short), FutureType.Short} }; /** Unmanaged target. */ private readonly IUnmanagedTarget _target; /** Marshaller. */ private readonly Marshaller _marsh; /// <summary> /// Constructor. /// </summary> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> protected PlatformTarget(IUnmanagedTarget target, Marshaller marsh) { Debug.Assert(target != null); Debug.Assert(marsh != null); _target = target; _marsh = marsh; } /// <summary> /// Unmanaged target. /// </summary> internal IUnmanagedTarget Target { get { return _target; } } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get { return _marsh; } } #region Static Helpers /// <summary> /// Write collection. /// </summary> /// <param name="writer">Writer.</param> /// <param name="vals">Values.</param> /// <returns>The same writer for chaining.</returns> protected static BinaryWriter WriteCollection<T>(BinaryWriter writer, ICollection<T> vals) { return WriteCollection<T, T>(writer, vals, null); } /// <summary> /// Write nullable collection. /// </summary> /// <param name="writer">Writer.</param> /// <param name="vals">Values.</param> /// <returns>The same writer for chaining.</returns> protected static BinaryWriter WriteNullableCollection<T>(BinaryWriter writer, ICollection<T> vals) { return WriteNullable(writer, vals, WriteCollection); } /// <summary> /// Write collection. /// </summary> /// <param name="writer">Writer.</param> /// <param name="vals">Values.</param> /// <param name="selector">A transform function to apply to each element.</param> /// <returns>The same writer for chaining.</returns> protected static BinaryWriter WriteCollection<T1, T2>(BinaryWriter writer, ICollection<T1> vals, Func<T1, T2> selector) { writer.WriteInt(vals.Count); if (selector == null) { foreach (var val in vals) writer.Write(val); } else { foreach (var val in vals) writer.Write(selector(val)); } return writer; } /// <summary> /// Write enumerable. /// </summary> /// <param name="writer">Writer.</param> /// <param name="vals">Values.</param> /// <returns>The same writer for chaining.</returns> protected static BinaryWriter WriteEnumerable<T>(BinaryWriter writer, IEnumerable<T> vals) { return WriteEnumerable<T, T>(writer, vals, null); } /// <summary> /// Write enumerable. /// </summary> /// <param name="writer">Writer.</param> /// <param name="vals">Values.</param> /// <param name="selector">A transform function to apply to each element.</param> /// <returns>The same writer for chaining.</returns> protected static BinaryWriter WriteEnumerable<T1, T2>(BinaryWriter writer, IEnumerable<T1> vals, Func<T1, T2> selector) { var col = vals as ICollection<T1>; if (col != null) return WriteCollection(writer, col, selector); var stream = writer.Stream; var pos = stream.Position; stream.Seek(4, SeekOrigin.Current); var size = 0; if (selector == null) { foreach (var val in vals) { writer.Write(val); size++; } } else { foreach (var val in vals) { writer.Write(selector(val)); size++; } } stream.WriteInt(pos, size); return writer; } /// <summary> /// Write dictionary. /// </summary> /// <param name="writer">Writer.</param> /// <param name="vals">Values.</param> /// <returns>The same writer.</returns> protected static BinaryWriter WriteDictionary<T1, T2>(BinaryWriter writer, IDictionary<T1, T2> vals) { writer.WriteInt(vals.Count); foreach (KeyValuePair<T1, T2> pair in vals) { writer.Write(pair.Key); writer.Write(pair.Value); } return writer; } /// <summary> /// Write a nullable item. /// </summary> /// <param name="writer">Writer.</param> /// <param name="item">Item.</param> /// <param name="writeItem">Write action to perform on item when it is not null.</param> /// <returns>The same writer for chaining.</returns> protected static BinaryWriter WriteNullable<T>(BinaryWriter writer, T item, Func<BinaryWriter, T, BinaryWriter> writeItem) where T : class { if (item == null) { writer.WriteBoolean(false); return writer; } writer.WriteBoolean(true); return writeItem(writer, item); } #endregion #region OUT operations /// <summary> /// Perform out operation. /// </summary> /// <param name="type">Operation type.</param> /// <param name="action">Action to be performed on the stream.</param> /// <returns></returns> protected long DoOutOp(int type, Action<IBinaryStream> action) { using (var stream = IgniteManager.Memory.Allocate().GetStream()) { action(stream); return UU.TargetInStreamOutLong(_target, type, stream.SynchronizeOutput()); } } /// <summary> /// Perform out operation. /// </summary> /// <param name="type">Operation type.</param> /// <param name="action">Action to be performed on the stream.</param> /// <returns></returns> protected long DoOutOp(int type, Action<BinaryWriter> action) { using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = _marsh.StartMarshal(stream); action(writer); FinishMarshal(writer); return UU.TargetInStreamOutLong(_target, type, stream.SynchronizeOutput()); } } /// <summary> /// Perform out operation. /// </summary> /// <param name="type">Operation type.</param> /// <param name="action">Action to be performed on the stream.</param> /// <returns></returns> protected IUnmanagedTarget DoOutOpObject(int type, Action<BinaryWriter> action) { using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = _marsh.StartMarshal(stream); action(writer); FinishMarshal(writer); return UU.TargetInStreamOutObject(_target, type, stream.SynchronizeOutput()); } } /// <summary> /// Perform out operation. /// </summary> /// <param name="type">Operation type.</param> /// <returns>Resulting object.</returns> protected IUnmanagedTarget DoOutOpObject(int type) { return UU.TargetOutObject(_target, type); } /// <summary> /// Perform simple output operation accepting single argument. /// </summary> /// <param name="type">Operation type.</param> /// <param name="val1">Value.</param> /// <returns>Result.</returns> protected long DoOutOp<T1>(int type, T1 val1) { return DoOutOp(type, writer => { writer.Write(val1); }); } /// <summary> /// Perform simple output operation accepting two arguments. /// </summary> /// <param name="type">Operation type.</param> /// <param name="val1">Value 1.</param> /// <param name="val2">Value 2.</param> /// <returns>Result.</returns> protected long DoOutOp<T1, T2>(int type, T1 val1, T2 val2) { return DoOutOp(type, writer => { writer.Write(val1); writer.Write(val2); }); } /// <summary> /// Perform simple output operation accepting three arguments. /// </summary> /// <param name="type">Operation type.</param> /// <param name="val1">Value 1.</param> /// <param name="val2">Value 2.</param> /// <param name="val3">Value 3.</param> /// <returns>Result.</returns> protected long DoOutOp<T1, T2, T3>(int type, T1 val1, T2 val2, T3 val3) { return DoOutOp(type, writer => { writer.Write(val1); writer.Write(val2); writer.Write(val3); }); } #endregion #region IN operations /// <summary> /// Perform in operation. /// </summary> /// <param name="type">Type.</param> /// <param name="action">Action.</param> protected void DoInOp(int type, Action<IBinaryStream> action) { using (var stream = IgniteManager.Memory.Allocate().GetStream()) { UU.TargetOutStream(_target, type, stream.MemoryPointer); stream.SynchronizeInput(); action(stream); } } /// <summary> /// Perform in operation. /// </summary> /// <param name="type">Type.</param> /// <param name="action">Action.</param> /// <returns>Result.</returns> protected T DoInOp<T>(int type, Func<IBinaryStream, T> action) { using (var stream = IgniteManager.Memory.Allocate().GetStream()) { UU.TargetOutStream(_target, type, stream.MemoryPointer); stream.SynchronizeInput(); return action(stream); } } /// <summary> /// Perform simple in operation returning immediate result. /// </summary> /// <param name="type">Type.</param> /// <returns>Result.</returns> protected T DoInOp<T>(int type) { using (var stream = IgniteManager.Memory.Allocate().GetStream()) { UU.TargetOutStream(_target, type, stream.MemoryPointer); stream.SynchronizeInput(); return Unmarshal<T>(stream); } } #endregion #region OUT-IN operations /// <summary> /// Perform out-in operation. /// </summary> /// <param name="type">Operation type.</param> /// <param name="outAction">Out action.</param> /// <param name="inAction">In action.</param> protected void DoOutInOp(int type, Action<BinaryWriter> outAction, Action<IBinaryStream> inAction) { using (PlatformMemoryStream outStream = IgniteManager.Memory.Allocate().GetStream()) { using (PlatformMemoryStream inStream = IgniteManager.Memory.Allocate().GetStream()) { BinaryWriter writer = _marsh.StartMarshal(outStream); outAction(writer); FinishMarshal(writer); UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer); inStream.SynchronizeInput(); inAction(inStream); } } } /// <summary> /// Perform out-in operation. /// </summary> /// <param name="type">Operation type.</param> /// <param name="outAction">Out action.</param> /// <param name="inAction">In action.</param> /// <returns>Result.</returns> protected TR DoOutInOp<TR>(int type, Action<BinaryWriter> outAction, Func<IBinaryStream, TR> inAction) { using (PlatformMemoryStream outStream = IgniteManager.Memory.Allocate().GetStream()) { using (PlatformMemoryStream inStream = IgniteManager.Memory.Allocate().GetStream()) { BinaryWriter writer = _marsh.StartMarshal(outStream); outAction(writer); FinishMarshal(writer); UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer); inStream.SynchronizeInput(); return inAction(inStream); } } } /// <summary> /// Perform out-in operation with a single stream. /// </summary> /// <typeparam name="TR">The type of the r.</typeparam> /// <param name="type">Operation type.</param> /// <param name="outAction">Out action.</param> /// <param name="inAction">In action.</param> /// <param name="inErrorAction">The action to read an error.</param> /// <returns> /// Result. /// </returns> protected TR DoOutInOpX<TR>(int type, Action<BinaryWriter> outAction, Func<IBinaryStream, long, TR> inAction, Func<IBinaryStream, Exception> inErrorAction) { Debug.Assert(inErrorAction != null); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = _marsh.StartMarshal(stream); outAction(writer); FinishMarshal(writer); var res = UU.TargetInStreamOutLong(_target, type, stream.SynchronizeOutput()); if (res != Error && inAction == null) return default(TR); // quick path for void operations stream.SynchronizeInput(); stream.Seek(0, SeekOrigin.Begin); if (res != Error) return inAction != null ? inAction(stream, res) : default(TR); throw inErrorAction(stream); } } /// <summary> /// Perform out-in operation with a single stream. /// </summary> /// <param name="type">Operation type.</param> /// <param name="outAction">Out action.</param> /// <param name="inErrorAction">The action to read an error.</param> /// <returns> /// Result. /// </returns> protected bool DoOutInOpX(int type, Action<BinaryWriter> outAction, Func<IBinaryStream, Exception> inErrorAction) { Debug.Assert(inErrorAction != null); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = _marsh.StartMarshal(stream); outAction(writer); FinishMarshal(writer); var res = UU.TargetInStreamOutLong(_target, type, stream.SynchronizeOutput()); if (res != Error) return res == True; stream.SynchronizeInput(); stream.Seek(0, SeekOrigin.Begin); throw inErrorAction(stream); } } /// <summary> /// Perform out-in operation. /// </summary> /// <param name="type">Operation type.</param> /// <param name="outAction">Out action.</param> /// <param name="inAction">In action.</param> /// <param name="arg">Argument.</param> /// <returns>Result.</returns> protected unsafe TR DoOutInOp<TR>(int type, Action<BinaryWriter> outAction, Func<IBinaryStream, IUnmanagedTarget, TR> inAction, void* arg) { PlatformMemoryStream outStream = null; long outPtr = 0; PlatformMemoryStream inStream = null; long inPtr = 0; try { if (outAction != null) { outStream = IgniteManager.Memory.Allocate().GetStream(); var writer = _marsh.StartMarshal(outStream); outAction(writer); FinishMarshal(writer); outPtr = outStream.SynchronizeOutput(); } if (inAction != null) { inStream = IgniteManager.Memory.Allocate().GetStream(); inPtr = inStream.MemoryPointer; } var res = UU.TargetInObjectStreamOutObjectStream(_target, type, arg, outPtr, inPtr); if (inAction == null) return default(TR); inStream.SynchronizeInput(); return inAction(inStream, res); } finally { try { if (inStream != null) inStream.Dispose(); } finally { if (outStream != null) outStream.Dispose(); } } } /// <summary> /// Perform out-in operation. /// </summary> /// <param name="type">Operation type.</param> /// <param name="outAction">Out action.</param> /// <returns>Result.</returns> protected TR DoOutInOp<TR>(int type, Action<BinaryWriter> outAction) { using (PlatformMemoryStream outStream = IgniteManager.Memory.Allocate().GetStream()) { using (PlatformMemoryStream inStream = IgniteManager.Memory.Allocate().GetStream()) { BinaryWriter writer = _marsh.StartMarshal(outStream); outAction(writer); FinishMarshal(writer); UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer); inStream.SynchronizeInput(); return Unmarshal<TR>(inStream); } } } /// <summary> /// Perform simple out-in operation accepting single argument. /// </summary> /// <param name="type">Operation type.</param> /// <param name="val">Value.</param> /// <returns>Result.</returns> protected TR DoOutInOp<T1, TR>(int type, T1 val) { using (PlatformMemoryStream outStream = IgniteManager.Memory.Allocate().GetStream()) { using (PlatformMemoryStream inStream = IgniteManager.Memory.Allocate().GetStream()) { BinaryWriter writer = _marsh.StartMarshal(outStream); writer.WriteObject(val); FinishMarshal(writer); UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer); inStream.SynchronizeInput(); return Unmarshal<TR>(inStream); } } } /// <summary> /// Perform simple out-in operation accepting two arguments. /// </summary> /// <param name="type">Operation type.</param> /// <param name="val1">Value.</param> /// <param name="val2">Value.</param> /// <returns>Result.</returns> protected TR DoOutInOp<T1, T2, TR>(int type, T1 val1, T2 val2) { using (PlatformMemoryStream outStream = IgniteManager.Memory.Allocate().GetStream()) { using (PlatformMemoryStream inStream = IgniteManager.Memory.Allocate().GetStream()) { BinaryWriter writer = _marsh.StartMarshal(outStream); writer.WriteObject(val1); writer.WriteObject(val2); FinishMarshal(writer); UU.TargetInStreamOutStream(_target, type, outStream.SynchronizeOutput(), inStream.MemoryPointer); inStream.SynchronizeInput(); return Unmarshal<TR>(inStream); } } } /// <summary> /// Perform simple out-in operation accepting two arguments. /// </summary> /// <param name="type">Operation type.</param> /// <param name="val">Value.</param> /// <returns>Result.</returns> protected long DoOutInOp(int type, long val = 0) { return UU.TargetInLongOutLong(_target, type, val); } #endregion #region Async operations /// <summary> /// Performs async operation. /// </summary> /// <param name="type">The type code.</param> /// <param name="writeAction">The write action.</param> /// <returns>Task for async operation</returns> protected Task DoOutOpAsync(int type, Action<BinaryWriter> writeAction = null) { return DoOutOpAsync<object>(type, writeAction); } /// <summary> /// Performs async operation. /// </summary> /// <typeparam name="T">Type of the result.</typeparam> /// <param name="type">The type code.</param> /// <param name="writeAction">The write action.</param> /// <param name="keepBinary">Keep binary flag, only applicable to object futures. False by default.</param> /// <param name="convertFunc">The function to read future result from stream.</param> /// <returns>Task for async operation</returns> protected Task<T> DoOutOpAsync<T>(int type, Action<BinaryWriter> writeAction = null, bool keepBinary = false, Func<BinaryReader, T> convertFunc = null) { return GetFuture((futId, futType) => DoOutOp(type, w => { if (writeAction != null) writeAction(w); w.WriteLong(futId); w.WriteInt(futType); }), keepBinary, convertFunc).Task; } /// <summary> /// Performs async operation. /// </summary> /// <typeparam name="T">Type of the result.</typeparam> /// <param name="type">The type code.</param> /// <param name="writeAction">The write action.</param> /// <returns>Future for async operation</returns> protected Future<T> DoOutOpObjectAsync<T>(int type, Action<IBinaryRawWriter> writeAction) { return GetFuture<T>((futId, futType) => DoOutOpObject(type, w => { writeAction(w); w.WriteLong(futId); w.WriteInt(futType); })); } /// <summary> /// Performs async operation. /// </summary> /// <typeparam name="TR">Type of the result.</typeparam> /// <typeparam name="T1">The type of the first arg.</typeparam> /// <param name="type">The type code.</param> /// <param name="val1">First arg.</param> /// <returns> /// Task for async operation /// </returns> protected Task<TR> DoOutOpAsync<T1, TR>(int type, T1 val1) { return GetFuture<TR>((futId, futType) => DoOutOp(type, w => { w.WriteObject(val1); w.WriteLong(futId); w.WriteInt(futType); })).Task; } /// <summary> /// Performs async operation. /// </summary> /// <typeparam name="TR">Type of the result.</typeparam> /// <typeparam name="T1">The type of the first arg.</typeparam> /// <typeparam name="T2">The type of the second arg.</typeparam> /// <param name="type">The type code.</param> /// <param name="val1">First arg.</param> /// <param name="val2">Second arg.</param> /// <returns> /// Task for async operation /// </returns> protected Task<TR> DoOutOpAsync<T1, T2, TR>(int type, T1 val1, T2 val2) { return GetFuture<TR>((futId, futType) => DoOutOp(type, w => { w.WriteObject(val1); w.WriteObject(val2); w.WriteLong(futId); w.WriteInt(futType); })).Task; } #endregion #region Miscelanneous /// <summary> /// Finish marshaling. /// </summary> /// <param name="writer">Writer.</param> internal void FinishMarshal(BinaryWriter writer) { _marsh.FinishMarshal(writer); } /// <summary> /// Unmarshal object using the given stream. /// </summary> /// <param name="stream">Stream.</param> /// <returns>Unmarshalled object.</returns> protected virtual T Unmarshal<T>(IBinaryStream stream) { return _marsh.Unmarshal<T>(stream); } /// <summary> /// Creates a future and starts listening. /// </summary> /// <typeparam name="T">Future result type</typeparam> /// <param name="listenAction">The listen action.</param> /// <param name="keepBinary">Keep binary flag, only applicable to object futures. False by default.</param> /// <param name="convertFunc">The function to read future result from stream.</param> /// <returns>Created future.</returns> private Future<T> GetFuture<T>(Func<long, int, IUnmanagedTarget> listenAction, bool keepBinary = false, Func<BinaryReader, T> convertFunc = null) { var futType = FutureType.Object; var type = typeof(T); if (type.IsPrimitive) IgniteFutureTypeMap.TryGetValue(type, out futType); var fut = convertFunc == null && futType != FutureType.Object ? new Future<T>() : new Future<T>(new FutureConverter<T>(_marsh, keepBinary, convertFunc)); var futHnd = _marsh.Ignite.HandleRegistry.Allocate(fut); IUnmanagedTarget futTarget; try { futTarget = listenAction(futHnd, (int)futType); } catch (Exception) { _marsh.Ignite.HandleRegistry.Release(futHnd); throw; } fut.SetTarget(new Listenable(futTarget, _marsh)); return fut; } /// <summary> /// Creates a future and starts listening. /// </summary> /// <typeparam name="T">Future result type</typeparam> /// <param name="listenAction">The listen action.</param> /// <param name="keepBinary">Keep binary flag, only applicable to object futures. False by default.</param> /// <param name="convertFunc">The function to read future result from stream.</param> /// <returns>Created future.</returns> protected Future<T> GetFuture<T>(Action<long, int> listenAction, bool keepBinary = false, Func<BinaryReader, T> convertFunc = null) { var futType = FutureType.Object; var type = typeof(T); if (type.IsPrimitive) IgniteFutureTypeMap.TryGetValue(type, out futType); var fut = convertFunc == null && futType != FutureType.Object ? new Future<T>() : new Future<T>(new FutureConverter<T>(_marsh, keepBinary, convertFunc)); var futHnd = _marsh.Ignite.HandleRegistry.Allocate(fut); try { listenAction(futHnd, (int)futType); } catch (Exception) { _marsh.Ignite.HandleRegistry.Release(futHnd); throw; } return fut; } #endregion } /// <summary> /// PlatformTarget with IDisposable pattern. /// </summary> internal abstract class PlatformDisposableTarget : PlatformTarget, IDisposable { /** Disposed flag. */ private volatile bool _disposed; /// <summary> /// Constructor. /// </summary> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> protected PlatformDisposableTarget(IUnmanagedTarget target, Marshaller marsh) : base(target, marsh) { // No-op. } /** <inheritdoc /> */ public void Dispose() { lock (this) { if (_disposed) return; Dispose(true); GC.SuppressFinalize(this); _disposed = true; } } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"> /// <c>true</c> when called from Dispose; <c>false</c> when called from finalizer. /// </param> protected virtual void Dispose(bool disposing) { Target.Dispose(); } /// <summary> /// Throws <see cref="ObjectDisposedException"/> if this instance has been disposed. /// </summary> protected void ThrowIfDisposed() { if (_disposed) throw new ObjectDisposedException(GetType().Name, "Object has been disposed."); } } }
// // SubSonic - http://subsonicproject.com // // The contents of this file are subject to the New BSD // License (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.opensource.org/licenses/bsd-license.php // // Software distributed under the License is distributed on an // "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or // implied. See the License for the specific language governing // rights and limitations under the License. // using System; using SubSonic.Schema; namespace SubSonic.Query { /// <summary> /// Enum for General SQL Functions /// </summary> public enum AggregateFunction { Count, Sum, Avg, Min, Max, StDev, Var, GroupBy } /// <summary> /// /// </summary> public class Aggregate { #region Aggregates Factories /// <summary> /// Counts the specified col. /// </summary> /// <param name="col">The col.</param> /// <returns></returns> public static Aggregate Count(IColumn col) { Aggregate agg = new Aggregate(col, AggregateFunction.Count); return agg; } /// <summary> /// Counts the specified col. /// </summary> /// <param name="col">The col.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Count(IColumn col, string alias) { Aggregate agg = new Aggregate(col, alias, AggregateFunction.Count); return agg; } /// <summary> /// Counts the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <returns></returns> public static Aggregate Count(string columnName) { Aggregate agg = new Aggregate(columnName, AggregateFunction.Count); return agg; } /// <summary> /// Counts the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Count(string columnName, string alias) { Aggregate agg = new Aggregate(columnName, alias, AggregateFunction.Count); return agg; } /// <summary> /// Sums the specified col. /// </summary> /// <param name="col">The col.</param> /// <returns></returns> public static Aggregate Sum(IColumn col) { Aggregate agg = new Aggregate(col, AggregateFunction.Sum); return agg; } /// <summary> /// Sums the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <returns></returns> public static Aggregate Sum(string columnName) { Aggregate agg = new Aggregate(columnName, AggregateFunction.Sum); return agg; } /// <summary> /// Sums the specified col. /// </summary> /// <param name="col">The col.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Sum(IColumn col, string alias) { Aggregate agg = new Aggregate(col, alias, AggregateFunction.Sum); return agg; } /// <summary> /// Sums the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Sum(string columnName, string alias) { Aggregate agg = new Aggregate(columnName, alias, AggregateFunction.Sum); return agg; } /// <summary> /// Groups the by. /// </summary> /// <param name="col">The col.</param> /// <returns></returns> public static Aggregate GroupBy(IColumn col) { Aggregate agg = new Aggregate(col, AggregateFunction.GroupBy); return agg; } /// <summary> /// Groups the by. /// </summary> /// <param name="columnName">Name of the column.</param> /// <returns></returns> public static Aggregate GroupBy(string columnName) { Aggregate agg = new Aggregate(columnName, AggregateFunction.GroupBy); return agg; } /// <summary> /// Groups the by. /// </summary> /// <param name="col">The col.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate GroupBy(IColumn col, string alias) { Aggregate agg = new Aggregate(col, alias, AggregateFunction.GroupBy); return agg; } /// <summary> /// Groups the by. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate GroupBy(string columnName, string alias) { Aggregate agg = new Aggregate(columnName, alias, AggregateFunction.GroupBy); return agg; } /// <summary> /// Avgs the specified col. /// </summary> /// <param name="col">The col.</param> /// <returns></returns> public static Aggregate Avg(IColumn col) { Aggregate agg = new Aggregate(col, AggregateFunction.Avg); return agg; } /// <summary> /// Avgs the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <returns></returns> public static Aggregate Avg(string columnName) { Aggregate agg = new Aggregate(columnName, AggregateFunction.Avg); return agg; } /// <summary> /// Avgs the specified col. /// </summary> /// <param name="col">The col.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Avg(IColumn col, string alias) { Aggregate agg = new Aggregate(col, alias, AggregateFunction.Avg); return agg; } /// <summary> /// Avgs the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Avg(string columnName, string alias) { Aggregate agg = new Aggregate(columnName, alias, AggregateFunction.Avg); return agg; } /// <summary> /// Maxes the specified col. /// </summary> /// <param name="col">The col.</param> /// <returns></returns> public static Aggregate Max(IColumn col) { Aggregate agg = new Aggregate(col, AggregateFunction.Max); return agg; } /// <summary> /// Maxes the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <returns></returns> public static Aggregate Max(string columnName) { Aggregate agg = new Aggregate(columnName, AggregateFunction.Max); return agg; } /// <summary> /// Maxes the specified col. /// </summary> /// <param name="col">The col.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Max(IColumn col, string alias) { Aggregate agg = new Aggregate(col, alias, AggregateFunction.Max); return agg; } /// <summary> /// Maxes the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Max(string columnName, string alias) { Aggregate agg = new Aggregate(columnName, alias, AggregateFunction.Max); return agg; } /// <summary> /// Mins the specified col. /// </summary> /// <param name="col">The col.</param> /// <returns></returns> public static Aggregate Min(IColumn col) { Aggregate agg = new Aggregate(col, AggregateFunction.Min); return agg; } /// <summary> /// Mins the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <returns></returns> public static Aggregate Min(string columnName) { Aggregate agg = new Aggregate(columnName, AggregateFunction.Min); return agg; } /// <summary> /// Mins the specified col. /// </summary> /// <param name="col">The col.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Min(IColumn col, string alias) { Aggregate agg = new Aggregate(col, alias, AggregateFunction.Min); return agg; } /// <summary> /// Mins the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Min(string columnName, string alias) { Aggregate agg = new Aggregate(columnName, alias, AggregateFunction.Min); return agg; } /// <summary> /// Variances the specified col. /// </summary> /// <param name="col">The col.</param> /// <returns></returns> public static Aggregate Variance(IColumn col) { Aggregate agg = new Aggregate(col, AggregateFunction.Var); return agg; } /// <summary> /// Variances the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <returns></returns> public static Aggregate Variance(string columnName) { Aggregate agg = new Aggregate(columnName, AggregateFunction.Var); return agg; } /// <summary> /// Variances the specified col. /// </summary> /// <param name="col">The col.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Variance(IColumn col, string alias) { Aggregate agg = new Aggregate(col, alias, AggregateFunction.Var); return agg; } /// <summary> /// Variances the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate Variance(string columnName, string alias) { Aggregate agg = new Aggregate(columnName, alias, AggregateFunction.Var); return agg; } /// <summary> /// Standards the deviation. /// </summary> /// <param name="col">The col.</param> /// <returns></returns> public static Aggregate StandardDeviation(IColumn col) { Aggregate agg = new Aggregate(col, AggregateFunction.StDev); return agg; } /// <summary> /// Standards the deviation. /// </summary> /// <param name="columnName">Name of the column.</param> /// <returns></returns> public static Aggregate StandardDeviation(string columnName) { Aggregate agg = new Aggregate(columnName, AggregateFunction.StDev); return agg; } /// <summary> /// Standards the deviation. /// </summary> /// <param name="col">The col.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate StandardDeviation(IColumn col, string alias) { Aggregate agg = new Aggregate(col, alias, AggregateFunction.StDev); return agg; } /// <summary> /// Standards the deviation. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="alias">The alias.</param> /// <returns></returns> public static Aggregate StandardDeviation(string columnName, string alias) { Aggregate agg = new Aggregate(columnName, alias, AggregateFunction.StDev); return agg; } #endregion #region .ctors private AggregateFunction _aggregateType = AggregateFunction.Count; /// <summary> /// Initializes a new instance of the <see cref="Aggregate"/> class. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="aggregateType">Type of the aggregate.</param> public Aggregate(string columnName, AggregateFunction aggregateType) { ColumnName = columnName; _aggregateType = aggregateType; Alias = String.Concat(GetFunctionType(this), "Of", columnName); } /// <summary> /// Initializes a new instance of the <see cref="Aggregate"/> class. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="alias">The alias.</param> /// <param name="aggregateType">Type of the aggregate.</param> public Aggregate(string columnName, string alias, AggregateFunction aggregateType) { ColumnName = columnName; _aggregateType = aggregateType; Alias = alias; } /// <summary> /// Initializes a new instance of the <see cref="Aggregate"/> class. /// </summary> /// <param name="column">The column.</param> /// <param name="aggregateType">Type of the aggregate.</param> public Aggregate(IDBObject column, AggregateFunction aggregateType) { ColumnName = column.QualifiedName; _aggregateType = aggregateType; Alias = String.Concat(GetFunctionType(this), "Of", column.Name); } /// <summary> /// Initializes a new instance of the <see cref="Aggregate"/> class. /// </summary> /// <param name="column">The column.</param> /// <param name="alias">The alias.</param> /// <param name="aggregateType">Type of the aggregate.</param> public Aggregate(IDBObject column, string alias, AggregateFunction aggregateType) { ColumnName = column.QualifiedName; Alias = alias; _aggregateType = aggregateType; } /// <summary> /// Gets the type of the function. /// </summary> /// <param name="agg">The agg.</param> /// <returns></returns> public static string GetFunctionType(Aggregate agg) { return Enum.GetName(typeof(AggregateFunction), agg.AggregateType); } #endregion /// <summary> /// Gets or sets the type of the aggregate. /// </summary> /// <value>The type of the aggregate.</value> public AggregateFunction AggregateType { get { return _aggregateType; } set { _aggregateType = value; } } /// <summary> /// Gets or sets the name of the column. /// </summary> /// <value>The name of the column.</value> public string ColumnName { get; set; } /// <summary> /// Gets or sets the alias. /// </summary> /// <value>The alias.</value> public string Alias { get; set; } /// <summary> /// Gets the SQL function call without an alias. Example: AVG(UnitPrice). /// </summary> /// <returns></returns> public string WithoutAlias() { string result; if(AggregateType == AggregateFunction.GroupBy) result = ColumnName; else { string functionName = GetFunctionType(this); functionName = functionName.ToUpper(); const string aggFormat = " {0}({1})"; result = string.Format(aggFormat, functionName, ColumnName); } return result; } /// <summary> /// Overrides ToString() to return the SQL Function call /// </summary> /// <returns></returns> public override string ToString() { string result; if(AggregateType == AggregateFunction.GroupBy) result = ColumnName; else { string functionName = GetFunctionType(this); functionName = functionName.ToUpper(); const string aggFormat = " {0}({1}) as '{2}'"; result = string.Format(aggFormat, functionName, ColumnName, Alias); } return result; } } }
/* * Copyright (c) 2009, Stefan Simek * * 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; using System.Reflection; using System.Reflection.Emit; namespace TriAxis.RunSharp { using Operands; interface IMemberInfo { MemberInfo Member { get; } string Name { get; } Type ReturnType { get; } Type[] ParameterTypes { get; } bool IsParameterArray { get; } bool IsStatic { get; } bool IsOverride { get; } } interface ITypeInfoProvider { IEnumerable<IMemberInfo> GetConstructors(); IEnumerable<IMemberInfo> GetFields(); IEnumerable<IMemberInfo> GetProperties(); IEnumerable<IMemberInfo> GetEvents(); IEnumerable<IMemberInfo> GetMethods(); string DefaultMember { get; } } static class TypeInfo { static Dictionary<Type, ITypeInfoProvider> providers = new Dictionary<Type, ITypeInfoProvider>(); static Dictionary<Type, WeakReference> cache = new Dictionary<Type, WeakReference>(); class CacheEntry { Type t; IMemberInfo[] constructors, fields, properties, events, methods; static string nullStr = "$NULL"; string defaultMember = nullStr; public CacheEntry(Type t) { this.t = t; if (t.GetType() != typeof(object).GetType()) { // not a runtime type, TypeInfoProvider missing - return nothing constructors = fields = properties = events = methods = empty; defaultMember = null; } } ~CacheEntry() { lock (cache) { if (cache[t].Target == this || cache[t].Target == null) cache.Remove(t); } } static IMemberInfo[] empty = { }; public IMemberInfo[] Constructors { get { if (constructors == null) { ConstructorInfo[] ctors = t.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance); constructors = Array.ConvertAll<ConstructorInfo, IMemberInfo>(ctors, delegate(ConstructorInfo ci) { return new StdMethodInfo(ci); }); } return constructors; } } public IMemberInfo[] Fields { get { if (fields == null) { FieldInfo[] fis = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static); fields = Array.ConvertAll<FieldInfo, IMemberInfo>(fis, delegate(FieldInfo fi) { return new StdFieldInfo(fi); }); } return fields; } } public IMemberInfo[] Properties { get { if (properties == null) { PropertyInfo[] pis = t.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static); properties = Array.ConvertAll<PropertyInfo, IMemberInfo>(pis, delegate(PropertyInfo pi) { return new StdPropertyInfo(pi); }); } return properties; } } public IMemberInfo[] Events { get { if (events == null) { EventInfo[] eis = t.GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static); events = Array.ConvertAll<EventInfo, IMemberInfo>(eis, delegate(EventInfo ei) { return new StdEventInfo(ei); }); } return events; } } public IMemberInfo[] Methods { get { if (methods == null) { MethodInfo[] mis = t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static); methods = Array.ConvertAll<MethodInfo, IMemberInfo>(mis, delegate(MethodInfo mi) { return new StdMethodInfo(mi); }); } return methods; } } public string DefaultMember { get { if (defaultMember == nullStr) { foreach (DefaultMemberAttribute dma in Attribute.GetCustomAttributes(t, typeof(DefaultMemberAttribute))) return defaultMember = dma.MemberName; defaultMember = null; } return defaultMember; } } } public static void RegisterProvider(Type t, ITypeInfoProvider prov) { providers[t] = prov; } public static void UnregisterProvider(Type t) { providers.Remove(t); } static CacheEntry GetCacheEntry(Type t) { if (t is TypeBuilder) t = t.UnderlyingSystemType; lock (cache) { CacheEntry ce; WeakReference wr; if (cache.TryGetValue(t, out wr)) { ce = wr.Target as CacheEntry; if (ce != null) return ce; } ce = new CacheEntry(t); cache[t] = new WeakReference(ce); return ce; } } public static IEnumerable<IMemberInfo> GetConstructors(Type t) { ITypeInfoProvider prov; if (providers.TryGetValue(t, out prov)) return prov.GetConstructors(); return GetCacheEntry(t).Constructors; } public static IEnumerable<IMemberInfo> GetFields(Type t) { ITypeInfoProvider prov; if (providers.TryGetValue(t, out prov)) return prov.GetFields(); return GetCacheEntry(t).Fields; } public static IEnumerable<IMemberInfo> GetProperties(Type t) { ITypeInfoProvider prov; if (providers.TryGetValue(t, out prov)) return prov.GetProperties(); return GetCacheEntry(t).Properties; } public static IEnumerable<IMemberInfo> GetEvents(Type t) { ITypeInfoProvider prov; if (providers.TryGetValue(t, out prov)) return prov.GetEvents(); return GetCacheEntry(t).Events; } public static IEnumerable<IMemberInfo> GetMethods(Type t) { ITypeInfoProvider prov; if (providers.TryGetValue(t, out prov)) return prov.GetMethods(); return GetCacheEntry(t).Methods; } public static string GetDefaultMember(Type t) { ITypeInfoProvider prov; if (providers.TryGetValue(t, out prov)) return prov.DefaultMember; return GetCacheEntry(t).DefaultMember; } public static IEnumerable<IMemberInfo> Filter(IEnumerable<IMemberInfo> source, string name, bool ignoreCase, bool isStatic, bool allowOverrides) { foreach (IMemberInfo mi in source) { if (mi.IsStatic != isStatic) continue; if (!allowOverrides && mi.IsOverride) continue; if (name != null) { if (ignoreCase) { if (!mi.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) continue; } else { if (mi.Name != name) continue; } } yield return mi; } } public static ApplicableFunction FindConstructor(Type t, Operand[] args) { ApplicableFunction ctor = OverloadResolver.Resolve(GetConstructors(t), args); if (ctor == null) throw new MissingMemberException(Properties.Messages.ErrMissingConstructor); return ctor; } public static IMemberInfo FindField(Type t, string name, bool @static) { for (; t != null; t = t.BaseType) { foreach (IMemberInfo mi in GetFields(t)) { if (mi.Name == name && mi.IsStatic == @static) return mi; } } throw new MissingFieldException(Properties.Messages.ErrMissingField); } public static ApplicableFunction FindProperty(Type t, string name, Operand[] indexes, bool @static) { if (name == null) name = GetDefaultMember(t); for (; t != null; t = t.BaseType) { ApplicableFunction af = OverloadResolver.Resolve(Filter(GetProperties(t), name, false, @static, false), indexes); if (af != null) return af; } throw new MissingMemberException(Properties.Messages.ErrMissingProperty); } public static IMemberInfo FindEvent(Type t, string name, bool @static) { for (; t != null; t = t.BaseType) { foreach (IMemberInfo mi in GetEvents(t)) { if (mi.Name == name && mi.IsStatic == @static) return mi; } } throw new MissingMemberException(Properties.Messages.ErrMissingEvent); } public static ApplicableFunction FindMethod(Type t, string name, Operand[] args, bool @static) { for (; t != null; t = t.BaseType) { ApplicableFunction af = OverloadResolver.Resolve(Filter(GetMethods(t), name, false, @static, false), args); if (af != null) return af; } throw new MissingMethodException(Properties.Messages.ErrMissingMethod); } class StdMethodInfo : IMemberInfo { MethodBase mb; MethodInfo mi; string name; Type returnType; Type[] parameterTypes; bool hasVar; public StdMethodInfo(MethodInfo mi) : this((MethodBase)mi) { this.mi = mi; } public StdMethodInfo(ConstructorInfo ci) : this((MethodBase)ci) { this.returnType = typeof(void); } public StdMethodInfo(MethodBase mb) { this.mb = mb; } void RequireParameters() { if (parameterTypes == null) { ParameterInfo[] pis = mb.GetParameters(); parameterTypes = ArrayUtils.GetTypes(pis); hasVar = pis.Length > 0 && pis[pis.Length - 1].GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0; } } public MemberInfo Member { get { return mb; } } public string Name { get { if (name == null) name = mb.Name; return name; } } public Type ReturnType { get { if (returnType == null) returnType = mi.ReturnType; return returnType; } } public Type[] ParameterTypes { get { RequireParameters(); return parameterTypes; } } public bool IsParameterArray { get { RequireParameters(); return hasVar; } } public bool IsStatic { get { return mb.IsStatic; } } public bool IsOverride { get { return Utils.IsOverride(mb.Attributes); } } public override string ToString() { return mb.ToString(); } } class StdPropertyInfo : IMemberInfo { PropertyInfo pi; string name; MethodInfo mi; Type returnType; Type[] parameterTypes; bool hasVar; public StdPropertyInfo(PropertyInfo pi) { this.pi = pi; this.mi = pi.GetGetMethod(); if (mi == null) mi = pi.GetSetMethod(); // mi will remain null for abstract properties } void RequireParameters() { if (parameterTypes == null) { ParameterInfo[] pis = pi.GetIndexParameters(); parameterTypes = ArrayUtils.GetTypes(pis); hasVar = pis.Length > 0 && pis[pis.Length - 1].GetCustomAttributes(typeof(ParamArrayAttribute), false).Length > 0; } } public MemberInfo Member { get { return pi; } } public string Name { get { if (name == null) name = pi.Name; return name; } } public Type ReturnType { get { if (returnType == null) returnType = pi.PropertyType; return returnType; } } public Type[] ParameterTypes { get { RequireParameters(); return parameterTypes; } } public bool IsParameterArray { get { RequireParameters(); return hasVar; } } public bool IsOverride { get { return mi == null ? false : Utils.IsOverride(mi.Attributes); } } public bool IsStatic { get { return mi == null ? false : mi.IsStatic; } } public override string ToString() { return pi.ToString(); } } class StdEventInfo : IMemberInfo { EventInfo ei; string name; MethodInfo mi; public StdEventInfo(EventInfo ei) { this.ei = ei; this.name = ei.Name; this.mi = ei.GetAddMethod(); if (mi == null) mi = ei.GetRemoveMethod(); // mi will remain null for abstract properties } public MemberInfo Member { get { return ei; } } public string Name { get { return name; } } public Type ReturnType { get { return ei.EventHandlerType; } } public Type[] ParameterTypes { get { return Type.EmptyTypes; } } public bool IsParameterArray { get { return false; } } public bool IsOverride { get { return mi == null ? false : Utils.IsOverride(mi.Attributes); } } public bool IsStatic { get { return mi == null ? false : mi.IsStatic; } } public override string ToString() { return ei.ToString(); } } class StdFieldInfo : IMemberInfo { FieldInfo fi; string name; public StdFieldInfo(FieldInfo fi) { this.fi = fi; this.name = fi.Name; } public MemberInfo Member { get { return fi; } } public string Name { get { return name; } } public Type ReturnType { get { return fi.FieldType; } } public Type[] ParameterTypes { get { return Type.EmptyTypes; } } public bool IsParameterArray { get { return false; } } public bool IsOverride { get { return false; } } public bool IsStatic { get { return fi.IsStatic; } } public override string ToString() { return fi.ToString(); } } } /* public Operand Invoke(string name, params Operand[] args) { Operand target = Target; for (Type src = this; src != null; src = src.Base) { ApplicableFunction match = OverloadResolver.Resolve(Type.FilterMethods(src.GetMethods(), name, false, (object)target == null, false), args); if (match != null) return new Invocation(match, Target, args); } throw new MissingMethodException(Properties.Messages.ErrMissingMethod); }*/ }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Payroll Groups /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class PN : EduHubEntity { #region Navigation Property Cache private PPD Cache_PPDKEY_PPD; private KBANK Cache_DD_GLCODE_KBANK; private GL Cache_GLCODE_GL; private GL Cache_GLBANK_GL; private GL Cache_GLTAX_GL; private KGLSUB Cache_SUBPROGRAM_KGLSUB; private KGLINIT Cache_INITIATIVE_KGLINIT; #endregion #region Foreign Navigation Properties private IReadOnlyList<PE> Cache_PNKEY_PE_PAYCODE; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Payroll code /// </summary> public short PNKEY { get; internal set; } /// <summary> /// Description /// [Alphanumeric (30)] /// </summary> public string DESCRIPTION { get; internal set; } /// <summary> /// M, F or W /// [Uppercase Alphanumeric (1)] /// </summary> public string TRANSTYPE { get; internal set; } /// <summary> /// First paydate of the year /// </summary> public DateTime? FIRSTDATE { get; internal set; } /// <summary> /// Next paydate of the year /// </summary> public DateTime? NEXTDATE { get; internal set; } /// <summary> /// Number of pays for year /// </summary> public short? NO_PAYS { get; internal set; } /// <summary> /// Roundoff point:... /// from 0.01 to 100.00 /// </summary> public decimal? ROUNDOFF { get; internal set; } /// <summary> /// PAYG Payer details /// [Uppercase Alphanumeric (10)] /// </summary> public string PPDKEY { get; internal set; } /// <summary> /// PAY_TYPE = A or T /// A = Autopay process /// T = Timesheet entry process /// [Uppercase Alphanumeric (1)] /// </summary> public string PAY_TYPE { get; internal set; } /// <summary> /// oldname=ACN_NUMBER; /// Employer ACN number (incl spaces) /// [Alphanumeric (12)] /// </summary> public string ACN { get; internal set; } /// <summary> /// Employer ABN number /// [Alphanumeric (16)] /// </summary> public string ABN { get; internal set; } /// <summary> /// Direct Deposit GL Bank Account /// [Uppercase Alphanumeric (10)] /// </summary> public string DD_GLCODE { get; internal set; } /// <summary> /// Salary expense code /// [Uppercase Alphanumeric (10)] /// </summary> public string GLCODE { get; internal set; } /// <summary> /// Wages clearing account /// [Uppercase Alphanumeric (10)] /// </summary> public string GLBANK { get; internal set; } /// <summary> /// Group Tax clearing account /// [Uppercase Alphanumeric (10)] /// </summary> public string GLTAX { get; internal set; } /// <summary> /// For every transaction there is a subprogram /// [Uppercase Alphanumeric (4)] /// </summary> public string SUBPROGRAM { get; internal set; } /// <summary> /// A subprogram always belongs to a program /// [Uppercase Alphanumeric (3)] /// </summary> public string GLPROGRAM { get; internal set; } /// <summary> /// Transaction might belong to an Initiative /// [Uppercase Alphanumeric (3)] /// </summary> public string INITIATIVE { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// PPD (PAYG Payer Details) related entity by [PN.PPDKEY]-&gt;[PPD.PPDKEY] /// PAYG Payer details /// </summary> public PPD PPDKEY_PPD { get { if (PPDKEY == null) { return null; } if (Cache_PPDKEY_PPD == null) { Cache_PPDKEY_PPD = Context.PPD.FindByPPDKEY(PPDKEY); } return Cache_PPDKEY_PPD; } } /// <summary> /// KBANK (Bank Account) related entity by [PN.DD_GLCODE]-&gt;[KBANK.GLCODE] /// Direct Deposit GL Bank Account /// </summary> public KBANK DD_GLCODE_KBANK { get { if (DD_GLCODE == null) { return null; } if (Cache_DD_GLCODE_KBANK == null) { Cache_DD_GLCODE_KBANK = Context.KBANK.FindByGLCODE(DD_GLCODE); } return Cache_DD_GLCODE_KBANK; } } /// <summary> /// GL (General Ledger) related entity by [PN.GLCODE]-&gt;[GL.CODE] /// Salary expense code /// </summary> public GL GLCODE_GL { get { if (GLCODE == null) { return null; } if (Cache_GLCODE_GL == null) { Cache_GLCODE_GL = Context.GL.FindByCODE(GLCODE); } return Cache_GLCODE_GL; } } /// <summary> /// GL (General Ledger) related entity by [PN.GLBANK]-&gt;[GL.CODE] /// Wages clearing account /// </summary> public GL GLBANK_GL { get { if (GLBANK == null) { return null; } if (Cache_GLBANK_GL == null) { Cache_GLBANK_GL = Context.GL.FindByCODE(GLBANK); } return Cache_GLBANK_GL; } } /// <summary> /// GL (General Ledger) related entity by [PN.GLTAX]-&gt;[GL.CODE] /// Group Tax clearing account /// </summary> public GL GLTAX_GL { get { if (GLTAX == null) { return null; } if (Cache_GLTAX_GL == null) { Cache_GLTAX_GL = Context.GL.FindByCODE(GLTAX); } return Cache_GLTAX_GL; } } /// <summary> /// KGLSUB (General Ledger Sub Programs) related entity by [PN.SUBPROGRAM]-&gt;[KGLSUB.SUBPROGRAM] /// For every transaction there is a subprogram /// </summary> public KGLSUB SUBPROGRAM_KGLSUB { get { if (SUBPROGRAM == null) { return null; } if (Cache_SUBPROGRAM_KGLSUB == null) { Cache_SUBPROGRAM_KGLSUB = Context.KGLSUB.FindBySUBPROGRAM(SUBPROGRAM); } return Cache_SUBPROGRAM_KGLSUB; } } /// <summary> /// KGLINIT (General Ledger Initiatives) related entity by [PN.INITIATIVE]-&gt;[KGLINIT.INITIATIVE] /// Transaction might belong to an Initiative /// </summary> public KGLINIT INITIATIVE_KGLINIT { get { if (INITIATIVE == null) { return null; } if (Cache_INITIATIVE_KGLINIT == null) { Cache_INITIATIVE_KGLINIT = Context.KGLINIT.FindByINITIATIVE(INITIATIVE); } return Cache_INITIATIVE_KGLINIT; } } #endregion #region Foreign Navigation Properties /// <summary> /// PE (Employees) related entities by [PN.PNKEY]-&gt;[PE.PAYCODE] /// Payroll code /// </summary> public IReadOnlyList<PE> PNKEY_PE_PAYCODE { get { if (Cache_PNKEY_PE_PAYCODE == null && !Context.PE.TryFindByPAYCODE(PNKEY, out Cache_PNKEY_PE_PAYCODE)) { Cache_PNKEY_PE_PAYCODE = new List<PE>().AsReadOnly(); } return Cache_PNKEY_PE_PAYCODE; } } #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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // LongRangePartitionerTests.cs - Tests for range partitioner for long integer range. // // PLEASE NOTE !! - For tests that need to iterate the elements inside the partitions more // than once, we need to call GetPartitions for the second time. Iterating a second times // over the first enumerable<tuples> / IList<IEnumerator<tuples> will yield no elements // // PLEASE NOTE!! - we use lazy evaluation wherever possible to allow for more than Int32.MaxValue // elements. ToArray / toList will result in an OOM // // Taken from dev11 branch: // \qa\clr\testsrc\pfx\Functional\Common\Partitioner\YetiTests\RangePartitioner\LongRangePartitionerTests.cs // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using Xunit; namespace System.Collections.Concurrent.Tests { public class LongRangePartitionerTests { /// <summary> /// Ensure that the partitioner returned has properties set correctly /// </summary> [Fact] public static void CheckKeyProperties() { var partitioner = Partitioner.Create(0, 9223372036854774807); Assert.True(partitioner.KeysOrderedInEachPartition, "Expected KeysOrderedInEachPartition to be set to true"); Assert.False(partitioner.KeysOrderedAcrossPartitions, "KeysOrderedAcrossPartitions to be set to false"); Assert.True(partitioner.KeysNormalized, "Expected KeysNormalized to be set to true"); partitioner = Partitioner.Create(0, 9223372036854774807, 90); Assert.True(partitioner.KeysOrderedInEachPartition, "Expected KeysOrderedInEachPartition to be set to true"); Assert.False(partitioner.KeysOrderedAcrossPartitions, "KeysOrderedAcrossPartitions to be set to false"); Assert.True(partitioner.KeysNormalized, "Expected KeysNormalized to be set to true"); } /// <summary> /// GetPartitions returns an IList<IEnumerator<Tuple<long, long>> /// We unroll the tuples and flatten them to a single sequence /// The single sequence is compared to the original range for verification /// </summary> [Fact] public static void CheckGetPartitions() { CheckGetPartitions(0, 1, 1); CheckGetPartitions(1, 1999, 3); CheckGetPartitions(2147473647, 9999, 4); CheckGetPartitions(2147484647, 1000, 8); CheckGetPartitions(-2147484647, 1000, 16); CheckGetPartitions(-1999, 5000, 63); CheckGetPartitions(9223372036854774807, 999, 13); // close to Int64.Max } private static void CheckGetPartitions(long from, long count, int dop) { long to = from + count; var partitioner = Partitioner.Create(from, to); //var elements = partitioner.GetPartitions(dop).SelectMany(enumerator => enumerator.UnRoll()); IList<long> elements = new List<long>(); foreach (var partition in partitioner.GetPartitions(dop)) { foreach (var item in partition.UnRoll()) elements.Add(item); } Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetPartitions element mismatch"); } /// <summary> /// CheckGetDynamicPartitions returns an IEnumerable<Tuple<long, long>> /// We unroll the tuples and flatten them to a single sequence /// The single sequence is compared to the original range for verification /// </summary> [Fact] public static void CheckGetDynamicPartitions() { CheckGetDynamicPartitions(0, 1); CheckGetDynamicPartitions(1, 1999); CheckGetDynamicPartitions(2147473647, 9999); CheckGetDynamicPartitions(2147484647, 1000); CheckGetDynamicPartitions(-2147484647, 1000); CheckGetDynamicPartitions(-1999, 5000); CheckGetDynamicPartitions(9223372036854774807, 999); // close to Int64.Max } private static void CheckGetDynamicPartitions(long from, long count) { long to = from + count; var partitioner = Partitioner.Create(from, to); //var elements = partitioner.GetDynamicPartitions().SelectMany(tuple => tuple.UnRoll()); IList<long> elements = new List<long>(); foreach (var partition in partitioner.GetDynamicPartitions()) { foreach (var item in partition.UnRoll()) elements.Add(item); } Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetDynamicPartitions Element mismatch"); } /// <summary> /// GetOrderablePartitions returns an IList<IEnumerator<KeyValuePair<long, Tuple<long, long>>> /// We unroll the tuples and flatten them to a single sequence /// The single sequence is compared to the original range for verification /// Also the indices are extracted to ensure that they are ordered & normalized /// </summary> [Fact] public static void CheckGetOrderablePartitions() { CheckGetOrderablePartitions(0, 1, 1); CheckGetOrderablePartitions(1, 1999, 3); CheckGetOrderablePartitions(2147473647, 9999, 4); CheckGetOrderablePartitions(2147484647, 1000, 8); CheckGetOrderablePartitions(-2147484647, 1000, 16); CheckGetOrderablePartitions(-1999, 5000, 63); CheckGetOrderablePartitions(9223372036854774807, 999, 13); // close to Int64.Max } private static void CheckGetOrderablePartitions(long from, long count, int dop) { long to = from + count; var partitioner = Partitioner.Create(from, to); //var elements = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRoll()); IList<long> elements = new List<long>(); foreach (var partition in partitioner.GetPartitions(dop)) { foreach (var item in partition.UnRoll()) elements.Add(item); } Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetOrderablePartitions Element mismatch"); //var keys = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRollIndices()).ToArray(); IList<long> keys = new List<long>(); foreach (var partition in partitioner.GetOrderablePartitions(dop)) { foreach (var item in partition.UnRollIndices()) keys.Add(item); } Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderablePartitions key mismatch"); } /// <summary> /// GetOrderableDynamicPartitions returns an IEnumerable<KeyValuePair<long, Tuple<long, long>> /// We unroll the tuples and flatten them to a single sequence /// The single sequence is compared to the original range for verification /// Also the indices are extracted to ensure that they are ordered & normalized /// </summary> /// <param name="from"></param> /// <param name="count"></param> [Fact] public static void GetOrderableDynamicPartitions() { GetOrderableDynamicPartitions(0, 1); GetOrderableDynamicPartitions(1, 1999); GetOrderableDynamicPartitions(2147473647, 9999); GetOrderableDynamicPartitions(2147484647, 1000); GetOrderableDynamicPartitions(-2147484647, 1000); GetOrderableDynamicPartitions(-1999, 5000); GetOrderableDynamicPartitions(9223372036854774807, 999); // close to Int64.Max } private static void GetOrderableDynamicPartitions(long from, long count) { long to = from + count; var partitioner = Partitioner.Create(from, to); //var elements = partitioner.GetOrderableDynamicPartitions().SelectMany(tuple => tuple.UnRoll()); IList<long> elements = new List<long>(); foreach (var partition in partitioner.GetOrderableDynamicPartitions()) { foreach (var item in partition.UnRoll()) elements.Add(item); } Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetOrderableDynamicPartitions Element mismatch"); //var keys = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.Key).ToArray(); IList<long> keys = new List<long>(); foreach (var tuple in partitioner.GetOrderableDynamicPartitions()) { keys.Add(tuple.Key); } Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderableDynamicPartitions key mismatch"); } /// <summary> /// GetPartitions returns an IList<IEnumerator<Tuple<long, long>> /// We unroll the tuples and flatten them to a single sequence /// The single sequence is compared to the original range for verification /// This method tests the partitioner created with user provided desiredRangeSize /// The range sizes for individual ranges are checked to see if they are equal to /// desiredRangeSize. The last range may have less than or equal to desiredRangeSize. /// </summary> [Fact] public static void CheckGetPartitionsWithRange() { CheckGetPartitionsWithRange(1999, 1000, 20, 1); CheckGetPartitionsWithRange(-1999, 1000, 100, 2); CheckGetPartitionsWithRange(1999, 1, 2000, 3); CheckGetPartitionsWithRange(9223372036854774807, 999, 600, 4); CheckGetPartitionsWithRange(-9223372036854774807, 1000, 19, 63); } private static void CheckGetPartitionsWithRange(long from, long count, long desiredRangeSize, int dop) { long to = from + count; var partitioner = Partitioner.Create(from, to, desiredRangeSize); //var elements = partitioner.GetPartitions(dop).SelectMany(enumerator => enumerator.UnRoll()); IList<long> elements = new List<long>(); foreach (var partition in partitioner.GetPartitions(dop)) { foreach (var item in partition.UnRoll()) elements.Add(item); } Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetPartitions element mismatch"); //var rangeSizes = partitioner.GetPartitions(dop).SelectMany(enumerator => enumerator.GetRangeSize()).ToArray(); IList<long> rangeSizes = new List<long>(); foreach (var partition in partitioner.GetPartitions(dop)) { foreach (var item in partition.GetRangeSize()) rangeSizes.Add(item); } ValidateRangeSize(desiredRangeSize, rangeSizes); } /// <summary> /// CheckGetDynamicPartitionsWithRange returns an IEnumerable<Tuple<long, long>> /// We unroll the tuples and flatten them to a single sequence /// The single sequence is compared to the original range for verification /// This method tests the partitioner created with user provided desiredRangeSize /// The range sizes for individual ranges are checked to see if they are equal to /// desiredRangeSize. The last range may have less than or equal to desiredRangeSize. /// </summary> [Fact] public static void CheckGetDynamicPartitionsWithRange() { CheckGetDynamicPartitionsWithRange(1999, 1000, 20); CheckGetDynamicPartitionsWithRange(-1999, 1000, 100); CheckGetDynamicPartitionsWithRange(1999, 1, 2000); CheckGetDynamicPartitionsWithRange(9223372036854774807, 999, 600); CheckGetDynamicPartitionsWithRange(-9223372036854774807, 1000, 19); } private static void CheckGetDynamicPartitionsWithRange(long from, long count, long desiredRangeSize) { long to = from + count; var partitioner = Partitioner.Create(from, to, desiredRangeSize); //var elements = partitioner.GetDynamicPartitions().SelectMany(tuple => tuple.UnRoll()); IList<long> elements = new List<long>(); foreach (var partition in partitioner.GetDynamicPartitions()) { foreach (var item in partition.UnRoll()) elements.Add(item); } Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetDynamicPartitions Element mismatch"); //var rangeSizes = partitioner.GetDynamicPartitions().Select(tuple => tuple.GetRangeSize()).ToArray(); IList<long> rangeSizes = new List<long>(); foreach (var partition in partitioner.GetDynamicPartitions()) { rangeSizes.Add(partition.GetRangeSize()); } ValidateRangeSize(desiredRangeSize, rangeSizes); } /// <summary> /// GetOrderablePartitions returns an IList<IEnumerator<KeyValuePair<long, Tuple<long, long>>> /// We unroll the tuples and flatten them to a single sequence /// The single sequence is compared to the original range for verification /// Also the indices are extracted to ensure that they are ordered & normalized /// This method tests the partitioner created with user provided desiredRangeSize /// The range sizes for individual ranges are checked to see if they are equal to /// desiredRangeSize. The last range may have less than or equal to desiredRangeSize. /// </summary> [Fact] public static void CheckGetOrderablePartitionsWithRange() { CheckGetOrderablePartitionsWithRange(1999, 1000, 20, 1); CheckGetOrderablePartitionsWithRange(-1999, 1000, 100, 2); CheckGetOrderablePartitionsWithRange(1999, 1, 2000, 3); CheckGetOrderablePartitionsWithRange(9223372036854774807, 999, 600, 4); CheckGetOrderablePartitionsWithRange(-9223372036854774807, 1000, 19, 63); } private static void CheckGetOrderablePartitionsWithRange(long from, long count, long desiredRangeSize, int dop) { long to = from + count; var partitioner = Partitioner.Create(from, to, desiredRangeSize); //var elements = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRoll()); IList<long> elements = new List<long>(); foreach (var partition in partitioner.GetOrderablePartitions(dop)) { foreach (var item in partition.UnRoll()) elements.Add(item); } Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetOrderablePartitions Element mismatch"); //var keys = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRollIndices()).ToArray(); IList<long> keys = new List<long>(); foreach (var partition in partitioner.GetOrderablePartitions(dop)) { foreach (var item in partition.UnRollIndices()) keys.Add(item); } Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderablePartitions key mismatch"); //var rangeSizes = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.GetRangeSize()).ToArray(); IList<long> rangeSizes = new List<long>(); foreach (var partition in partitioner.GetOrderablePartitions(dop)) { foreach (var item in partition.GetRangeSize()) rangeSizes.Add(item); } ValidateRangeSize(desiredRangeSize, rangeSizes); } /// <summary> /// GetOrderableDynamicPartitions returns an IEnumerable<KeyValuePair<long, Tuple<long, long>> /// We unroll the tuples and flatten them to a single sequence /// The single sequence is compared to the original range for verification /// Also the indices are extracted to ensure that they are ordered & normalized /// This method tests the partitioner created with user provided desiredRangeSize /// The range sizes for individual ranges are checked to see if they are equal to /// desiredRangeSize. The last range may have less than or equal to desiredRangeSize. /// </summary> [Fact] public static void GetOrderableDynamicPartitionsWithRange() { GetOrderableDynamicPartitionsWithRange(1999, 1000, 20); GetOrderableDynamicPartitionsWithRange(-1999, 1000, 100); GetOrderableDynamicPartitionsWithRange(1999, 1, 2000); GetOrderableDynamicPartitionsWithRange(9223372036854774807, 999, 600); GetOrderableDynamicPartitionsWithRange(-9223372036854774807, 1000, 19); } private static void GetOrderableDynamicPartitionsWithRange(long from, long count, long desiredRangeSize) { long to = from + count; var partitioner = Partitioner.Create(from, to, desiredRangeSize); //var elements = partitioner.GetOrderableDynamicPartitions().SelectMany(tuple => tuple.UnRoll()); IList<long> elements = new List<long>(); foreach (var tuple in partitioner.GetOrderableDynamicPartitions()) { foreach (var item in tuple.UnRoll()) elements.Add(item); } Assert.True(elements.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(from, to)), "GetOrderableDynamicPartitions Element mismatch"); //var keys = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.Key).ToArray(); IList<long> keys = new List<long>(); foreach (var tuple in partitioner.GetOrderableDynamicPartitions()) { keys.Add(tuple.Key); } Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderableDynamicPartitions key mismatch"); //var rangeSizes = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.GetRangeSize()).ToArray(); IList<long> rangeSizes = new List<long>(); foreach (var partition in partitioner.GetOrderableDynamicPartitions()) { rangeSizes.Add(partition.GetRangeSize()); } ValidateRangeSize(desiredRangeSize, rangeSizes); } /// <summary> /// Helper function to validate the range size of the partitioners match what the user specified /// (desiredRangeSize). /// The last range may have less than or equal to desiredRangeSize. /// </summary> /// <param name="desiredRangeSize"></param> /// <param name="rangeSizes"></param> /// <returns></returns> private static void ValidateRangeSize(long desiredRangeSize, IList<long> rangeSizes) { //var rangesWithDifferentRangeSize = rangeSizes.Take(rangeSizes.Length - 1).Where(r => r != desiredRangeSize).ToArray(); IList<long> rangesWithDifferentRangeSize = new List<long>(); // ensuring that every range, size from the last one is the same. int numToTake = rangeSizes.Count - 1; for (int i = 0; i < numToTake; i++) { long range = rangeSizes[i]; if (range != desiredRangeSize) rangesWithDifferentRangeSize.Add(range); } Assert.Equal(0, rangesWithDifferentRangeSize.Count); Assert.InRange(rangeSizes[rangeSizes.Count - 1], 0, desiredRangeSize); } /// <summary> /// Ensure that the range partitioner doesn't chunk up elements i.e. uses chunk size = 1 /// </summary> [Fact] public static void RangePartitionerChunking() { RangePartitionerChunking(2147473647, 9999, 4); RangePartitionerChunking(2147484647, 1000, -1); } private static void RangePartitionerChunking(long from, long count, long rangeSize) { long to = from + count; var partitioner = (rangeSize == -1) ? Partitioner.Create(from, to) : Partitioner.Create(from, to, rangeSize); // Check static partitions var partitions = partitioner.GetPartitions(2); // Initialize the from / to values from the first element if (!partitions[0].MoveNext()) return; Assert.Equal(from, partitions[0].Current.Item1); if (rangeSize == -1) { rangeSize = partitions[0].Current.Item2 - partitions[0].Current.Item1; } long nextExpectedFrom = partitions[0].Current.Item2; long nextExpectedTo = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize); // Ensure that each partition gets one range only // we check this by alternating partitions asking for elements and make sure // that we get ranges in a sequence. If chunking were to happen then we wouldn't see a sequence long actualCount = partitions[0].Current.Item2 - partitions[0].Current.Item1; while (true) { if (!partitions[0].MoveNext()) break; Assert.Equal(nextExpectedFrom, partitions[0].Current.Item1); Assert.Equal(nextExpectedTo, partitions[0].Current.Item2); nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize); nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize); actualCount += partitions[0].Current.Item2 - partitions[0].Current.Item1; if (!partitions[1].MoveNext()) break; Assert.Equal(nextExpectedFrom, partitions[1].Current.Item1); Assert.Equal(nextExpectedTo, partitions[1].Current.Item2); nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize); nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize); actualCount += partitions[1].Current.Item2 - partitions[1].Current.Item1; if (!partitions[1].MoveNext()) break; Assert.Equal(nextExpectedFrom, partitions[1].Current.Item1); Assert.Equal(nextExpectedTo, partitions[1].Current.Item2); nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize); nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize); actualCount += partitions[1].Current.Item2 - partitions[1].Current.Item1; if (!partitions[0].MoveNext()) break; Assert.Equal(nextExpectedFrom, partitions[0].Current.Item1); Assert.Equal(nextExpectedTo, partitions[0].Current.Item2); nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize); nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize); actualCount += partitions[0].Current.Item2 - partitions[0].Current.Item1; } // Verifying that all items are there Assert.Equal(count, actualCount); } /// <summary> /// Ensure that the range partitioner doesn't chunk up elements i.e. uses chunk size = 1 /// </summary> [Fact] public static void RangePartitionerDynamicChunking() { RangePartitionerDynamicChunking(2147473647, 9999, 4); RangePartitionerDynamicChunking(2147484647, 1000, -1); } private static void RangePartitionerDynamicChunking(long from, long count, long rangeSize) { long to = from + count; var partitioner = (rangeSize == -1) ? Partitioner.Create(from, to) : Partitioner.Create(from, to, rangeSize); // Check static partitions var partitions = partitioner.GetDynamicPartitions(); var partition1 = partitions.GetEnumerator(); var partition2 = partitions.GetEnumerator(); // Initialize the from / to values from the first element if (!partition1.MoveNext()) return; Assert.Equal(from, partition1.Current.Item1); if (rangeSize == -1) { rangeSize = partition1.Current.Item2 - partition1.Current.Item1; } long nextExpectedFrom = partition1.Current.Item2; long nextExpectedTo = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize); // Ensure that each partition gets one range only // we check this by alternating partitions asking for elements and make sure // that we get ranges in a sequence. If chunking were to happen then we wouldn't see a sequence long actualCount = partition1.Current.Item2 - partition1.Current.Item1; while (true) { if (!partition1.MoveNext()) break; Assert.Equal(nextExpectedFrom, partition1.Current.Item1); Assert.Equal(nextExpectedTo, partition1.Current.Item2); nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize); nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize); actualCount += partition1.Current.Item2 - partition1.Current.Item1; if (!partition2.MoveNext()) break; Assert.Equal(nextExpectedFrom, partition2.Current.Item1); Assert.Equal(nextExpectedTo, partition2.Current.Item2); nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize); nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize); actualCount += partition2.Current.Item2 - partition2.Current.Item1; if (!partition2.MoveNext()) break; Assert.Equal(nextExpectedFrom, partition2.Current.Item1); Assert.Equal(nextExpectedTo, partition2.Current.Item2); nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize); nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize); actualCount += partition2.Current.Item2 - partition2.Current.Item1; if (!partition1.MoveNext()) break; Assert.Equal(nextExpectedFrom, partition1.Current.Item1); Assert.Equal(nextExpectedTo, partition1.Current.Item2); nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize); nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize); actualCount += partition1.Current.Item2 - partition1.Current.Item1; } // Verifying that all items are there Assert.Equal(count, actualCount); } /// <summary> /// Ensure that the range partitioner doesn't exceed the exclusive bound /// </summary> /// <param name="fromInclusive"></param> /// <param name="toExclusive"></param> [Theory] [InlineData(-1, long.MaxValue)] [InlineData(long.MinValue, long.MaxValue)] [InlineData(long.MinValue, -1)] [InlineData(long.MinValue / 2, long.MaxValue / 2)] public void TestPartitionerCreate(long fromInclusive, long toExclusive) { OrderablePartitioner<Tuple<long, long>> op = Partitioner.Create(fromInclusive, toExclusive); long start = fromInclusive; foreach (var p in op.GetDynamicPartitions()) { Assert.Equal(start, p.Item1); start = p.Item2; } Assert.Equal(toExclusive, start); } } }
/* ==================================================================== 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 NPOI.Util; using System.Collections.Generic; using System.IO; using System; using NPOI.HSLF.Record; namespace NPOI.HSLF.Model.TextProperties { /** * For a given run of characters, holds the properties (which could * be paragraph properties or character properties). * Used to hold the number of characters affected, the list of active * properties, and the random reserved field if required. */ public class TextPropCollection { private int charactersCovered; private short reservedField; private List<TextProp> textPropList; private int maskSpecial = 0; public int GetSpecialMask() { return maskSpecial; } /** Fetch the number of characters this styling applies to */ public int GetCharactersCovered() { return charactersCovered; } /** Fetch the TextProps that define this styling */ public List<TextProp> GetTextPropList() { return textPropList; } /** Fetch the TextProp with this name, or null if it isn't present */ public TextProp FindByName(String textPropName) { for (int i = 0; i < textPropList.Count; i++) { TextProp prop = textPropList[i]; if (prop.GetName().Equals(textPropName)) { return prop; } } return null; } /** Add the TextProp with this name to the list */ public TextProp AddWithName(String name) { // Find the base TextProp to base on TextProp base1 = null; for(int i=0; i < StyleTextPropAtom.characterTextPropTypes.Length; i++) { if(StyleTextPropAtom.characterTextPropTypes[i].GetName().Equals(name)) { base1 = StyleTextPropAtom.characterTextPropTypes[i]; } } for(int i=0; i < StyleTextPropAtom.paragraphTextPropTypes.Length; i++) { if(StyleTextPropAtom.paragraphTextPropTypes[i].GetName().Equals(name)) { base1 = StyleTextPropAtom.paragraphTextPropTypes[i]; } } if(base1== null) { throw new ArgumentException("No TextProp with name " + name + " is defined to add from"); } // Add a copy of this property, in the right place to the list TextProp textProp = (TextProp)base1.Clone(); int pos = 0; for(int i=0; i<textPropList.Count; i++) { TextProp curProp = textPropList[i]; if(textProp.GetMask() > curProp.GetMask()) { pos++; } } textPropList.Insert(pos, textProp); return textProp; } /** * For an existing Set of text properties, build the list of * properties coded for in a given run of properties. * @return the number of bytes that were used encoding the properties list */ public int BuildTextPropList(int ContainsField, TextProp[] potentialProperties, byte[] data, int dataOffset) { int bytesPassed = 0; // For each possible entry, see if we match the mask // If we do, decode that, save it, and shuffle on for (int i = 0; i < potentialProperties.Length; i++) { // Check there's still data left to read // Check if this property is found in the mask if ((ContainsField & potentialProperties[i].GetMask()) != 0) { if (dataOffset + bytesPassed >= data.Length) { // Out of data, can't be any more properties to go // remember the mask and return maskSpecial |= potentialProperties[i].GetMask(); return bytesPassed; } // Bingo, data Contains this property TextProp prop = (TextProp)potentialProperties[i].Clone(); int val = 0; if (prop.GetSize() == 2) { val = LittleEndian.GetShort(data, dataOffset + bytesPassed); } else if (prop.GetSize() == 4) { val = LittleEndian.GetInt(data, dataOffset + bytesPassed); } else if (prop.GetSize() == 0) { //remember "special" bits. maskSpecial |= potentialProperties[i].GetMask(); continue; } prop.SetValue(val); bytesPassed += prop.GetSize(); textPropList.Add(prop); } } // Return how many bytes were used return bytesPassed; } /** * Create a new collection of text properties (be they paragraph * or character) which will be groked via a subsequent call to * buildTextPropList(). */ public TextPropCollection(int charactersCovered, short reservedField) { this.charactersCovered = charactersCovered; this.reservedField = reservedField; textPropList = new List<TextProp>(); } /** * Create a new collection of text properties (be they paragraph * or character) for a run of text without any */ public TextPropCollection(int textSize) { charactersCovered = textSize; reservedField = -1; textPropList = new List<TextProp>(); } /** * Update the size of the text that this Set of properties * applies to */ public void updateTextSize(int textSize) { charactersCovered = textSize; } /** * Writes out to disk the header, and then all the properties */ public void WriteOut(Stream o) { // First goes the number of characters we affect StyleTextPropAtom.WriteLittleEndian(charactersCovered, o); // Then we have the reserved field if required if (reservedField > -1) { StyleTextPropAtom.WriteLittleEndian(reservedField, o); } // Then the mask field int mask = maskSpecial; for (int i = 0; i < textPropList.Count; i++) { TextProp textProp = (TextProp)textPropList[i]; //sometimes header indicates that the bitmask is present but its value is 0 if (textProp is BitMaskTextProp) { if (mask == 0) mask |= textProp.GetWriteMask(); } else { mask |= textProp.GetWriteMask(); } } StyleTextPropAtom.WriteLittleEndian(mask, o); // Then the contents of all the properties for (int i = 0; i < textPropList.Count; i++) { TextProp textProp = textPropList[i]; int val = textProp.GetValue(); if (textProp.GetSize() == 2) { StyleTextPropAtom.WriteLittleEndian((short)val, o); } else if (textProp.GetSize() == 4) { StyleTextPropAtom.WriteLittleEndian(val, o); } } } public short GetReservedField() { return reservedField; } public void SetReservedField(short val) { reservedField = val; } } }
using System; using System.Collections; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Markup; using System.Windows.Media; // IAddChild, ContentPropertyAttribute namespace Microsoft._3DTools { /// <summary> /// This class enables a Viewport3D to be enhanced by allowing UIElements to be placed /// behind and in front of the Viewport3D. These can then be used for various enhancements. /// For examples see the Trackball, or InteractiveViewport3D. /// </summary> [ContentProperty("Content")] public abstract class Viewport3DDecorator : FrameworkElement, IAddChild { private UIElement _content; //--------------------------------------------------------- // // Private data // //--------------------------------------------------------- /// <summary> /// Creates the Viewport3DDecorator /// </summary> public Viewport3DDecorator() { // create the two lists of children PreViewportChildren = new UIElementCollection(this, this); PostViewportChildren = new UIElementCollection(this, this); // no content yet _content = null; } /// <summary> /// The content/child of the Viewport3DDecorator. A Viewport3DDecorator only has one /// child and this child must be either another Viewport3DDecorator or a Viewport3D. /// </summary> public UIElement Content { get { return _content; } set { // check to make sure it is a Viewport3D or a Viewport3DDecorator if (!(value is Viewport3D || value is Viewport3DDecorator)) throw new ArgumentException("Not a valid child type", "value"); // check to make sure we're attempting to set something new if (_content != value) { var oldContent = _content; var newContent = value; // remove the previous child RemoveVisualChild(oldContent); RemoveLogicalChild(oldContent); // set the private variable _content = value; // link in the new child AddLogicalChild(newContent); AddVisualChild(newContent); // let anyone know that derives from us that there was a change OnViewport3DDecoratorContentChange(oldContent, newContent); // data bind to what is below us so that we have the same width/height // as the Viewport3D being enhanced // create the bindings now for use later BindToContentsWidthHeight(newContent); // Invalidate measure to indicate a layout update may be necessary InvalidateMeasure(); } } } /// <summary> /// Property to get the Viewport3D that is being enhanced. /// </summary> public Viewport3D Viewport3D { get { Viewport3D viewport3D = null; var currEnhancer = this; // we follow the enhancers down until we get the // Viewport3D they are enhancing while (true) { var currContent = currEnhancer.Content; if (currContent == null) break; if (currContent is Viewport3D) { viewport3D = (Viewport3D) currContent; break; } currEnhancer = (Viewport3DDecorator) currContent; } return viewport3D; } } /// <summary> /// The UIElements that occur before the Viewport3D /// </summary> protected UIElementCollection PreViewportChildren { get; } /// <summary> /// The UIElements that occur after the Viewport3D /// </summary> protected UIElementCollection PostViewportChildren { get; } /// <summary> /// Returns the number of Visual children this element has. /// </summary> protected override int VisualChildrenCount { get { var contentCount = Content == null ? 0 : 1; return PreViewportChildren.Count + PostViewportChildren.Count + contentCount; } } /// <summary> /// Returns an enumertor to this element's logical children /// </summary> protected override IEnumerator LogicalChildren { get { var logicalChildren = new Visual[VisualChildrenCount]; for (var i = 0; i < VisualChildrenCount; i++) logicalChildren[i] = GetVisualChild(i); // return an enumerator to the ArrayList return logicalChildren.GetEnumerator(); } } //------------------------------------------------------ // // IAddChild implementation // //------------------------------------------------------ void IAddChild.AddChild(object value) { // check against null if (value == null) throw new ArgumentNullException("value"); // we only can have one child if (Content != null) throw new ArgumentException("Viewport3DDecorator can only have one child"); // now we can actually set the content Content = (UIElement) value; } void IAddChild.AddText(string text) { // The only text we accept is whitespace, which we ignore. for (var i = 0; i < text.Length; i++) if (!char.IsWhiteSpace(text[i])) throw new ArgumentException("Non whitespace in add text", text); } /// <summary> /// Data binds the (Max/Min)Width and (Max/Min)Height properties to the same /// ones as the content. This will make it so we end up being sized to be /// exactly the same ActualWidth and ActualHeight as waht is below us. /// </summary> /// <param name="newContent">What to bind to</param> private void BindToContentsWidthHeight(UIElement newContent) { // bind to width height var _widthBinding = new Binding("Width"); _widthBinding.Mode = BindingMode.OneWay; var _heightBinding = new Binding("Height"); _heightBinding.Mode = BindingMode.OneWay; _widthBinding.Source = newContent; _heightBinding.Source = newContent; BindingOperations.SetBinding(this, WidthProperty, _widthBinding); BindingOperations.SetBinding(this, HeightProperty, _heightBinding); // bind to max width and max height var _maxWidthBinding = new Binding("MaxWidth"); _maxWidthBinding.Mode = BindingMode.OneWay; var _maxHeightBinding = new Binding("MaxHeight"); _maxHeightBinding.Mode = BindingMode.OneWay; _maxWidthBinding.Source = newContent; _maxHeightBinding.Source = newContent; BindingOperations.SetBinding(this, MaxWidthProperty, _maxWidthBinding); BindingOperations.SetBinding(this, MaxHeightProperty, _maxHeightBinding); // bind to min width and min height var _minWidthBinding = new Binding("MinWidth"); _minWidthBinding.Mode = BindingMode.OneWay; var _minHeightBinding = new Binding("MinHeight"); _minHeightBinding.Mode = BindingMode.OneWay; _minWidthBinding.Source = newContent; _minHeightBinding.Source = newContent; BindingOperations.SetBinding(this, MinWidthProperty, _minWidthBinding); BindingOperations.SetBinding(this, MinHeightProperty, _minHeightBinding); } /// <summary> /// Extenders of Viewport3DDecorator can override this function to be notified /// when the Content property changes /// </summary> /// <param name="oldContent">The old value of the Content property</param> /// <param name="newContent">The new value of the Content property</param> protected virtual void OnViewport3DDecoratorContentChange(UIElement oldContent, UIElement newContent) { } /// <summary> /// Returns the child at the specified index. /// </summary> protected override Visual GetVisualChild(int index) { var orginalIndex = index; // see if index is in the pre viewport children if (index < PreViewportChildren.Count) return PreViewportChildren[index]; index -= PreViewportChildren.Count; // see if it's the content if (Content != null && index == 0) return Content; index -= Content == null ? 0 : 1; // see if it's the post viewport children if (index < PostViewportChildren.Count) return PostViewportChildren[index]; // if we didn't return then the index is out of range - throw an error throw new ArgumentOutOfRangeException("index", orginalIndex, "Out of range visual requested"); } /// <summary> /// Updates the DesiredSize of the Viewport3DDecorator /// </summary> /// <param name="constraint">The "upper limit" that the return value should not exceed</param> /// <returns>The desired size of the Viewport3DDecorator</returns> protected override Size MeasureOverride(Size constraint) { var finalSize = new Size(); MeasurePreViewportChildren(constraint); // measure our Viewport3D(Enhancer) if (Content != null) { Content.Measure(constraint); finalSize = Content.DesiredSize; } MeasurePostViewportChildren(constraint); return finalSize; } /// <summary> /// Measures the size of all the PreViewportChildren. If special measuring behavior is needed, this /// method should be overridden. /// </summary> /// <param name="constraint">The "upper limit" on the size of an element</param> protected virtual void MeasurePreViewportChildren(Size constraint) { // measure the pre viewport children MeasureUIElementCollection(PreViewportChildren, constraint); } /// <summary> /// Measures the size of all the PostViewportChildren. If special measuring behavior is needed, this /// method should be overridden. /// </summary> /// <param name="constraint">The "upper limit" on the size of an element</param> protected virtual void MeasurePostViewportChildren(Size constraint) { // measure the post viewport children MeasureUIElementCollection(PostViewportChildren, constraint); } /// <summary> /// Measures all of the UIElements in a UIElementCollection /// </summary> /// <param name="collection">The collection to measure</param> /// <param name="constraint">The "upper limit" on the size of an element</param> private void MeasureUIElementCollection(UIElementCollection collection, Size constraint) { // measure the pre viewport visual visuals foreach (UIElement uiElem in collection) uiElem.Measure(constraint); } /// <summary> /// Arranges the Pre and Post Viewport children, and arranges itself /// </summary> /// <param name="arrangeSize">The final size to use to arrange itself and its children</param> protected override Size ArrangeOverride(Size arrangeSize) { ArrangePreViewportChildren(arrangeSize); // arrange our Viewport3D(Enhancer) if (Content != null) Content.Arrange(new Rect(arrangeSize)); ArrangePostViewportChildren(arrangeSize); return arrangeSize; } /// <summary> /// Arranges all the PreViewportChildren. If special measuring behavior is needed, this /// method should be overridden. /// </summary> /// <param name="arrangeSize">The final size to use to arrange each child</param> protected virtual void ArrangePreViewportChildren(Size arrangeSize) { ArrangeUIElementCollection(PreViewportChildren, arrangeSize); } /// <summary> /// Arranges all the PostViewportChildren. If special measuring behavior is needed, this /// method should be overridden. /// </summary> /// <param name="arrangeSize">The final size to use to arrange each child</param> protected virtual void ArrangePostViewportChildren(Size arrangeSize) { ArrangeUIElementCollection(PostViewportChildren, arrangeSize); } /// <summary> /// Arranges all the UIElements in the passed in UIElementCollection /// </summary> /// <param name="collection">The collection that should be arranged</param> /// <param name="constraint">The final size that element should use to arrange itself and its children</param> private void ArrangeUIElementCollection(UIElementCollection collection, Size constraint) { // measure the pre viewport visual visuals foreach (UIElement uiElem in collection) uiElem.Arrange(new Rect(constraint)); } } }
//----------------------------------------------------------------------- // This file is part of Microsoft Robotics Developer Studio Code Samples. // // Copyright (C) Microsoft Corporation. All rights reserved. // // $File: DriveTypes.cs $ $Revision: 1 $ //----------------------------------------------------------------------- using Microsoft.Ccr.Core; using Microsoft.Dss.Core.Attributes; using Microsoft.Dss.Core.DsspHttp; using Microsoft.Dss.ServiceModel.Dssp; using System; using System.Collections.Generic; using System.ComponentModel; using W3C.Soap; using motor = Microsoft.Robotics.Services.Motor; namespace Microsoft.Robotics.Services.Drive { /// <summary> /// Dss Drive Contract /// </summary> public static class Contract { /// <summary> /// Drive contract /// </summary> public const string Identifier = "http://schemas.microsoft.com/robotics/2006/05/drive.html"; } /// <summary> /// Partners /// </summary> [DataContract] public static class Partners { /// <summary> /// Left Encoder /// </summary> [DataMember] public const string LeftEncoder = "LeftEncoder"; /// <summary> /// Right Encoder /// </summary> [DataMember] public const string RightEncoder = "RightEncoder"; /// <summary> /// Left Motor /// </summary> [DataMember] public const string LeftMotor = "LeftMotor"; /// <summary> /// Right Motor /// </summary> [DataMember] public const string RightMotor = "RightMotor"; } /// <summary> /// Drive Operations Port /// </summary> [ServicePort] public class DriveOperations : PortSet { /// <summary> /// Default constructor /// </summary> public DriveOperations() : base( typeof(DsspDefaultLookup), typeof(DsspDefaultDrop), typeof(Get), typeof(HttpGet), typeof(HttpPost), typeof(ReliableSubscribe), typeof(Subscribe), typeof(Update), typeof(EnableDrive), typeof(SetDrivePower), typeof(SetDriveSpeed), typeof(RotateDegrees), typeof(DriveDistance), typeof(AllStop)) { } /// <summary> /// Untyped post /// </summary> /// <param name="item"></param> public void Post(object item) { base.PostUnknownType(item); } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<DsspDefaultLookup>(DriveOperations portSet) { if (portSet == null) return null; return (Port<DsspDefaultLookup>)portSet[typeof(DsspDefaultLookup)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<DsspDefaultDrop>(DriveOperations portSet) { if (portSet == null) return null; return (Port<DsspDefaultDrop>)portSet[typeof(DsspDefaultDrop)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<HttpGet>(DriveOperations portSet) { if (portSet == null) return null; return (Port<HttpGet>)portSet[typeof(HttpGet)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<HttpPost>(DriveOperations portSet) { if (portSet == null) return null; return (Port<HttpPost>)portSet[typeof(HttpPost)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<Subscribe>(DriveOperations portSet) { if (portSet == null) return null; return (Port<Subscribe>)portSet[typeof(Subscribe)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<Get>(DriveOperations portSet) { if (portSet == null) return null; return (Port<Get>)portSet[typeof(Get)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<Update>(DriveOperations portSet) { if (portSet == null) return null; return (Port<Update>)portSet[typeof(Update)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<ReliableSubscribe>(DriveOperations portSet) { if (portSet == null) return null; return (Port<ReliableSubscribe>)portSet[typeof(ReliableSubscribe)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<EnableDrive>(DriveOperations portSet) { if (portSet == null) return null; return (Port<EnableDrive>)portSet[typeof(EnableDrive)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<SetDrivePower>(DriveOperations portSet) { if (portSet == null) return null; return (Port<SetDrivePower>)portSet[typeof(SetDrivePower)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<SetDriveSpeed>(DriveOperations portSet) { if (portSet == null) return null; return (Port<SetDriveSpeed>)portSet[typeof(SetDriveSpeed)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<RotateDegrees>(DriveOperations portSet) { if (portSet == null) return null; return (Port<RotateDegrees>)portSet[typeof(RotateDegrees)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<DriveDistance>(DriveOperations portSet) { if (portSet == null) return null; return (Port<DriveDistance>)portSet[typeof(DriveDistance)]; } /// <summary> /// Implicit conversion /// </summary> public static implicit operator Port<AllStop>(DriveOperations portSet) { if (portSet == null) return null; return (Port<AllStop>)portSet[typeof(AllStop)]; } } #region Operation Port Definitions /// <summary> /// Operation Retrieve Drive State /// </summary> [Description("Gets the drive's current state.")] public class Get : Get<GetRequestType, PortSet<DriveDifferentialTwoWheelState, Fault>> { } /// <summary> /// Operation Update Drive State /// </summary> [Description("Updates (or indicates an update to) the drive's state.")] public class Update : Update<DriveDifferentialTwoWheelState, PortSet<DefaultUpdateResponseType, Fault>> { /// <summary> /// Default Constructor /// </summary> public Update() { } /// <summary> /// Initialization Constructor /// </summary> /// <param name="state"></param> public Update(DriveDifferentialTwoWheelState state) { this.Body = state; } } /// <summary> /// Operation Enable Drive /// </summary> [Description("Enables (or disables) a drive (or indicates whether a drive is enabled).")] public class EnableDrive : Update<EnableDriveRequest, PortSet<DefaultUpdateResponseType, Fault>> { /// <summary> /// public constructor /// </summary> public EnableDrive() { Body = new EnableDriveRequest(); } } /// <summary> /// Operation Update Motor Power /// </summary> [Description("Sets (or indicates a change to) the drive's power.")] public class SetDrivePower : Update<SetDrivePowerRequest, PortSet<DefaultUpdateResponseType, Fault>> { /// <summary> /// public constructor /// </summary> public SetDrivePower() { } /// <summary> /// SetDrivePower Initialization Constructor /// </summary> /// <param name="body"></param> public SetDrivePower(SetDrivePowerRequest body) { Body = body; } } /// <summary> /// Operation Update Motor Speed /// </summary> [Description("Sets (or indicates) the drive speed.")] public class SetDriveSpeed : Update<SetDriveSpeedRequest, PortSet<DefaultUpdateResponseType, Fault>> { } /// <summary> /// Request the drive to rotate or turn in position (positive values turn counterclockwise). /// </summary> [Description("Request the drive to rotate or turn in position (positive values turn counterclockwise).")] public class RotateDegrees : Update<RotateDegreesRequest, PortSet<DefaultUpdateResponseType, Fault>> { /// <summary> /// Request the drive to rotate or turn in position (positive values turn counterclockwise). /// </summary> public RotateDegrees() { } /// <summary> /// Request the drive to rotate or turn in position (positive values turn counterclockwise). /// </summary> /// <param name="body"></param> public RotateDegrees(RotateDegreesRequest body) { Body = body; } } /// <summary> /// Operation drive a specified distance, then stop /// </summary> [Description("Updates (or indicates and update to) a distance setting for the drive.")] public class DriveDistance : Update<DriveDistanceRequest, PortSet<DefaultUpdateResponseType, Fault>> { /// <summary> /// public constructor /// </summary> public DriveDistance() { } /// <summary> /// DriveDistance Initialization Constructor /// </summary> /// <param name="body"></param> public DriveDistance(DriveDistanceRequest body) { Body = body; } } /// <summary> /// Emergency Stop /// <remarks>overrides long running commands</remarks> /// </summary> [Description("Stops the drive.")] public class AllStop : Update<AllStopRequest, PortSet<DefaultUpdateResponseType, Fault>> { /// <summary> /// public constructor /// </summary> public AllStop() { Body = new AllStopRequest(); } } /// <summary> /// Operation to subscribe to drive notifications /// </summary> public class Subscribe : Subscribe<SubscribeRequestType, PortSet<SubscribeResponseType, Fault>> { } /// <summary> /// Operation to reliable subscribe to drive notifications /// </summary> public class ReliableSubscribe : Subscribe<ReliableSubscribeRequestType, PortSet<SubscribeResponseType, Fault>> { } #endregion #region internal types //====================================================================== // Operations that are internal to a generic differential drive service /// <summary> /// Cancel Pending Drive Operation (used internally) /// <remarks>Used to cancel drive operations that are monitoring the internal drive cancellation port.</remarks> /// <remarks>This type is internal to a service that implements the generic differential drive contract.</remarks> /// <remarks>cancels long running commands (drive distance or rotate degrees)</remarks> /// </summary> [Description("Cancels a pending drive distance or rotate degrees operation.")] [DataContract] public class CancelPendingDriveOperation : Update<CancelPendingDriveOperationRequest, PortSet<DefaultUpdateResponseType, Fault>> { /// <summary> /// public constructor /// </summary> public CancelPendingDriveOperation() { Body = new CancelPendingDriveOperationRequest(); } } #endregion }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookChartRequest. /// </summary> public partial class WorkbookChartRequest : BaseRequest, IWorkbookChartRequest { /// <summary> /// Constructs a new WorkbookChartRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookChartRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookChart using POST. /// </summary> /// <param name="workbookChartToCreate">The WorkbookChart to create.</param> /// <returns>The created WorkbookChart.</returns> public System.Threading.Tasks.Task<WorkbookChart> CreateAsync(WorkbookChart workbookChartToCreate) { return this.CreateAsync(workbookChartToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookChart using POST. /// </summary> /// <param name="workbookChartToCreate">The WorkbookChart to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookChart.</returns> public async System.Threading.Tasks.Task<WorkbookChart> CreateAsync(WorkbookChart workbookChartToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookChart>(workbookChartToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookChart. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookChart. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<WorkbookChart>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookChart. /// </summary> /// <returns>The WorkbookChart.</returns> public System.Threading.Tasks.Task<WorkbookChart> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookChart. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookChart.</returns> public async System.Threading.Tasks.Task<WorkbookChart> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookChart>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookChart using PATCH. /// </summary> /// <param name="workbookChartToUpdate">The WorkbookChart to update.</param> /// <returns>The updated WorkbookChart.</returns> public System.Threading.Tasks.Task<WorkbookChart> UpdateAsync(WorkbookChart workbookChartToUpdate) { return this.UpdateAsync(workbookChartToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookChart using PATCH. /// </summary> /// <param name="workbookChartToUpdate">The WorkbookChart to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookChart.</returns> public async System.Threading.Tasks.Task<WorkbookChart> UpdateAsync(WorkbookChart workbookChartToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookChart>(workbookChartToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartRequest Expand(Expression<Func<WorkbookChart, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartRequest Select(Expression<Func<WorkbookChart, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="workbookChartToInitialize">The <see cref="WorkbookChart"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookChart workbookChartToInitialize) { if (workbookChartToInitialize != null && workbookChartToInitialize.AdditionalData != null) { if (workbookChartToInitialize.Series != null && workbookChartToInitialize.Series.CurrentPage != null) { workbookChartToInitialize.Series.AdditionalData = workbookChartToInitialize.AdditionalData; object nextPageLink; workbookChartToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { workbookChartToInitialize.Series.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Cache { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Cache.Query.Continuous; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cache.Expiry; using Apache.Ignite.Core.Impl.Cache.Query; using Apache.Ignite.Core.Impl.Cache.Query.Continuous; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Transactions; using Apache.Ignite.Core.Impl.Unmanaged; /// <summary> /// Native cache wrapper. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] internal class CacheImpl<TK, TV> : PlatformTarget, ICache<TK, TV>, ICacheInternal, ICacheLockInternal { /** Ignite instance. */ private readonly Ignite _ignite; /** Flag: skip store. */ private readonly bool _flagSkipStore; /** Flag: keep binary. */ private readonly bool _flagKeepBinary; /** Flag: no-retries.*/ private readonly bool _flagNoRetries; /** Flag: partition recover.*/ private readonly bool _flagPartitionRecover; /** Transaction manager. */ private readonly CacheTransactionManager _txManager; /// <summary> /// Constructor. /// </summary> /// <param name="grid">Grid.</param> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="flagSkipStore">Skip store flag.</param> /// <param name="flagKeepBinary">Keep binary flag.</param> /// <param name="flagNoRetries">No-retries mode flag.</param> /// <param name="flagPartitionRecover">Partition recover mode flag.</param> public CacheImpl(Ignite grid, IUnmanagedTarget target, Marshaller marsh, bool flagSkipStore, bool flagKeepBinary, bool flagNoRetries, bool flagPartitionRecover) : base(target, marsh) { Debug.Assert(grid != null); _ignite = grid; _flagSkipStore = flagSkipStore; _flagKeepBinary = flagKeepBinary; _flagNoRetries = flagNoRetries; _flagPartitionRecover = flagPartitionRecover; _txManager = GetConfiguration().AtomicityMode == CacheAtomicityMode.Transactional ? new CacheTransactionManager(grid.GetTransactions()) : null; } /** <inheritDoc /> */ public IIgnite Ignite { get { return _ignite; } } /// <summary> /// Performs async operation. /// </summary> private Task DoOutOpAsync<T1>(CacheOp op, T1 val1) { return DoOutOpAsync<object, T1>((int) op, val1); } /// <summary> /// Performs async operation. /// </summary> private Task<TR> DoOutOpAsync<T1, TR>(CacheOp op, T1 val1) { return DoOutOpAsync<T1, TR>((int) op, val1); } /// <summary> /// Performs async operation. /// </summary> private Task DoOutOpAsync<T1, T2>(CacheOp op, T1 val1, T2 val2) { return DoOutOpAsync<T1, T2, object>((int) op, val1, val2); } /// <summary> /// Performs async operation. /// </summary> private Task<TR> DoOutOpAsync<T1, T2, TR>(CacheOp op, T1 val1, T2 val2) { return DoOutOpAsync<T1, T2, TR>((int) op, val1, val2); } /// <summary> /// Performs async operation. /// </summary> private Task DoOutOpAsync(CacheOp op, Action<BinaryWriter> writeAction = null) { return DoOutOpAsync<object>(op, writeAction); } /// <summary> /// Performs async operation. /// </summary> private Task<T> DoOutOpAsync<T>(CacheOp op, Action<BinaryWriter> writeAction = null, Func<BinaryReader, T> convertFunc = null) { return DoOutOpAsync((int)op, writeAction, IsKeepBinary, convertFunc); } /** <inheritDoc /> */ public string Name { get { return DoInOp<string>((int)CacheOp.GetName); } } /** <inheritDoc /> */ public CacheConfiguration GetConfiguration() { return DoInOp((int) CacheOp.GetConfig, stream => new CacheConfiguration( BinaryUtils.Marshaller.StartUnmarshal(stream))); } /** <inheritDoc /> */ public bool IsEmpty() { return GetSize() == 0; } /** <inheritDoc /> */ public ICache<TK, TV> WithSkipStore() { if (_flagSkipStore) return this; return new CacheImpl<TK, TV>(_ignite, DoOutOpObject((int) CacheOp.WithSkipStore), Marshaller, true, _flagKeepBinary, true, _flagPartitionRecover); } /// <summary> /// Skip store flag getter. /// </summary> internal bool IsSkipStore { get { return _flagSkipStore; } } /** <inheritDoc /> */ public ICache<TK1, TV1> WithKeepBinary<TK1, TV1>() { if (_flagKeepBinary) { var result = this as ICache<TK1, TV1>; if (result == null) throw new InvalidOperationException( "Can't change type of binary cache. WithKeepBinary has been called on an instance of " + "binary cache with incompatible generic arguments."); return result; } return new CacheImpl<TK1, TV1>(_ignite, DoOutOpObject((int) CacheOp.WithKeepBinary), Marshaller, _flagSkipStore, true, _flagNoRetries, _flagPartitionRecover); } /** <inheritDoc /> */ public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc) { IgniteArgumentCheck.NotNull(plc, "plc"); var cache0 = DoOutOpObject((int)CacheOp.WithExpiryPolicy, w => ExpiryPolicySerializer.WritePolicy(w, plc)); return new CacheImpl<TK, TV>(_ignite, cache0, Marshaller, _flagSkipStore, _flagKeepBinary, _flagNoRetries, _flagPartitionRecover); } /** <inheritDoc /> */ public bool IsKeepBinary { get { return _flagKeepBinary; } } /** <inheritDoc /> */ public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args) { DoOutInOpX((int) CacheOp.LoadCache, writer => WriteLoadCacheData(writer, p, args), ReadException); } /** <inheritDoc /> */ public Task LoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args) { return DoOutOpAsync(CacheOp.LoadCacheAsync, writer => WriteLoadCacheData(writer, p, args)); } /** <inheritDoc /> */ public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args) { DoOutInOpX((int) CacheOp.LocLoadCache, writer => WriteLoadCacheData(writer, p, args), ReadException); } /** <inheritDoc /> */ public Task LocalLoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args) { return DoOutOpAsync(CacheOp.LocLoadCacheAsync, writer => WriteLoadCacheData(writer, p, args)); } /// <summary> /// Writes the load cache data to the writer. /// </summary> private void WriteLoadCacheData(BinaryWriter writer, ICacheEntryFilter<TK, TV> p, object[] args) { if (p != null) { var p0 = new CacheEntryFilterHolder(p, (k, v) => p.Invoke(new CacheEntry<TK, TV>((TK) k, (TV) v)), Marshaller, IsKeepBinary); writer.WriteObject(p0); } else writer.WriteObject<CacheEntryFilterHolder>(null); if (args != null && args.Length > 0) { writer.WriteInt(args.Length); foreach (var o in args) writer.WriteObject(o); } else { writer.WriteInt(0); } } /** <inheritDoc /> */ public void LoadAll(IEnumerable<TK> keys, bool replaceExistingValues) { LoadAllAsync(keys, replaceExistingValues).Wait(); } /** <inheritDoc /> */ public Task LoadAllAsync(IEnumerable<TK> keys, bool replaceExistingValues) { return DoOutOpAsync(CacheOp.LoadAll, writer => { writer.WriteBoolean(replaceExistingValues); WriteEnumerable(writer, keys); }); } /** <inheritDoc /> */ public bool ContainsKey(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp(CacheOp.ContainsKey, key); } /** <inheritDoc /> */ public Task<bool> ContainsKeyAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOpAsync<TK, bool>(CacheOp.ContainsKeyAsync, key); } /** <inheritDoc /> */ public bool ContainsKeys(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutOp(CacheOp.ContainsKeys, writer => WriteEnumerable(writer, keys)); } /** <inheritDoc /> */ public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutOpAsync<bool>(CacheOp.ContainsKeysAsync, writer => WriteEnumerable(writer, keys)); } /** <inheritDoc /> */ public TV LocalPeek(TK key, params CachePeekMode[] modes) { IgniteArgumentCheck.NotNull(key, "key"); TV res; if (TryLocalPeek(key, out res)) return res; throw GetKeyNotFoundException(); } /** <inheritDoc /> */ public bool TryLocalPeek(TK key, out TV value, params CachePeekMode[] modes) { IgniteArgumentCheck.NotNull(key, "key"); var res = DoOutInOpX((int)CacheOp.Peek, w => { w.Write(key); w.WriteInt(EncodePeekModes(modes)); }, (s, r) => r == True ? new CacheResult<TV>(Unmarshal<TV>(s)) : new CacheResult<TV>(), ReadException); value = res.Success ? res.Value : default(TV); return res.Success; } /** <inheritDoc /> */ public TV this[TK key] { get { return Get(key); } set { Put(key, value); } } /** <inheritDoc /> */ public TV Get(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOpX((int) CacheOp.Get, w => w.Write(key), (stream, res) => { if (res != True) throw GetKeyNotFoundException(); return Unmarshal<TV>(stream); }, ReadException); } /** <inheritDoc /> */ public Task<TV> GetAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOpAsync(CacheOp.GetAsync, w => w.WriteObject(key), reader => { if (reader != null) return reader.ReadObject<TV>(); throw GetKeyNotFoundException(); }); } /** <inheritDoc /> */ public bool TryGet(TK key, out TV value) { IgniteArgumentCheck.NotNull(key, "key"); var res = DoOutInOpNullable(CacheOp.Get, key); value = res.Value; return res.Success; } /** <inheritDoc /> */ public Task<CacheResult<TV>> TryGetAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOpAsync(CacheOp.GetAsync, w => w.WriteObject(key), reader => GetCacheResult(reader)); } /** <inheritDoc /> */ public ICollection<ICacheEntry<TK, TV>> GetAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutInOpX((int) CacheOp.GetAll, writer => WriteEnumerable(writer, keys), (s, r) => r == True ? ReadGetAllDictionary(Marshaller.StartUnmarshal(s, _flagKeepBinary)) : null, ReadException); } /** <inheritDoc /> */ public Task<ICollection<ICacheEntry<TK, TV>>> GetAllAsync(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutOpAsync(CacheOp.GetAllAsync, w => WriteEnumerable(w, keys), r => ReadGetAllDictionary(r)); } /** <inheritdoc /> */ public void Put(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); DoOutOp(CacheOp.Put, key, val); } /** <inheritDoc /> */ public Task PutAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync(CacheOp.PutAsync, key, val); } /** <inheritDoc /> */ public CacheResult<TV> GetAndPut(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutInOpNullable(CacheOp.GetAndPut, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync(CacheOp.GetAndPutAsync, w => { w.WriteObject(key); w.WriteObject(val); }, r => GetCacheResult(r)); } /** <inheritDoc /> */ public CacheResult<TV> GetAndReplace(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutInOpNullable(CacheOp.GetAndReplace, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync(CacheOp.GetAndReplaceAsync, w => { w.WriteObject(key); w.WriteObject(val); }, r => GetCacheResult(r)); } /** <inheritDoc /> */ public CacheResult<TV> GetAndRemove(TK key) { IgniteArgumentCheck.NotNull(key, "key"); StartTx(); return DoOutInOpNullable(CacheOp.GetAndRemove, key); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndRemoveAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); StartTx(); return DoOutOpAsync(CacheOp.GetAndRemoveAsync, w => w.WriteObject(key), r => GetCacheResult(r)); } /** <inheritdoc /> */ public bool PutIfAbsent(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOp(CacheOp.PutIfAbsent, key, val); } /** <inheritDoc /> */ public Task<bool> PutIfAbsentAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync<TK, TV, bool>(CacheOp.PutIfAbsentAsync, key, val); } /** <inheritdoc /> */ public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutInOpNullable(CacheOp.GetAndPutIfAbsent, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync(CacheOp.GetAndPutIfAbsentAsync, w => { w.WriteObject(key); w.WriteObject(val); }, r => GetCacheResult(r)); } /** <inheritdoc /> */ public bool Replace(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOp(CacheOp.Replace2, key, val); } /** <inheritDoc /> */ public Task<bool> ReplaceAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync<TK, TV, bool>(CacheOp.Replace2Async, key, val); } /** <inheritdoc /> */ public bool Replace(TK key, TV oldVal, TV newVal) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(oldVal, "oldVal"); IgniteArgumentCheck.NotNull(newVal, "newVal"); StartTx(); return DoOutOp(CacheOp.Replace3, key, oldVal, newVal); } /** <inheritDoc /> */ public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(oldVal, "oldVal"); IgniteArgumentCheck.NotNull(newVal, "newVal"); StartTx(); return DoOutOpAsync<bool>(CacheOp.Replace3Async, w => { w.WriteObject(key); w.WriteObject(oldVal); w.WriteObject(newVal); }); } /** <inheritdoc /> */ public void PutAll(IEnumerable<KeyValuePair<TK, TV>> vals) { IgniteArgumentCheck.NotNull(vals, "vals"); StartTx(); DoOutOp(CacheOp.PutAll, writer => WriteDictionary(writer, vals)); } /** <inheritDoc /> */ public Task PutAllAsync(IEnumerable<KeyValuePair<TK, TV>> vals) { IgniteArgumentCheck.NotNull(vals, "vals"); StartTx(); return DoOutOpAsync(CacheOp.PutAllAsync, writer => WriteDictionary(writer, vals)); } /** <inheritdoc /> */ public void LocalEvict(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp(CacheOp.LocEvict, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public void Clear() { DoOutInOp((int) CacheOp.ClearCache); } /** <inheritDoc /> */ public Task ClearAsync() { return DoOutOpAsync(CacheOp.ClearCacheAsync); } /** <inheritdoc /> */ public void Clear(TK key) { IgniteArgumentCheck.NotNull(key, "key"); DoOutOp(CacheOp.Clear, key); } /** <inheritDoc /> */ public Task ClearAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOpAsync(CacheOp.ClearAsync, key); } /** <inheritdoc /> */ public void ClearAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp(CacheOp.ClearAll, writer => WriteEnumerable(writer, keys)); } /** <inheritDoc /> */ public Task ClearAllAsync(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutOpAsync(CacheOp.ClearAllAsync, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public void LocalClear(TK key) { IgniteArgumentCheck.NotNull(key, "key"); DoOutOp(CacheOp.LocalClear, key); } /** <inheritdoc /> */ public void LocalClearAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp(CacheOp.LocalClearAll, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public bool Remove(TK key) { IgniteArgumentCheck.NotNull(key, "key"); StartTx(); return DoOutOp(CacheOp.RemoveObj, key); } /** <inheritDoc /> */ public Task<bool> RemoveAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); StartTx(); return DoOutOpAsync<TK, bool>(CacheOp.RemoveObjAsync, key); } /** <inheritDoc /> */ public bool Remove(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOp(CacheOp.RemoveBool, key, val); } /** <inheritDoc /> */ public Task<bool> RemoveAsync(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); StartTx(); return DoOutOpAsync<TK, TV, bool>(CacheOp.RemoveBoolAsync, key, val); } /** <inheritDoc /> */ public void RemoveAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); StartTx(); DoOutOp(CacheOp.RemoveAll, writer => WriteEnumerable(writer, keys)); } /** <inheritDoc /> */ public Task RemoveAllAsync(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); StartTx(); return DoOutOpAsync(CacheOp.RemoveAllAsync, writer => WriteEnumerable(writer, keys)); } /** <inheritDoc /> */ public void RemoveAll() { StartTx(); DoOutInOp((int) CacheOp.RemoveAll2); } /** <inheritDoc /> */ public Task RemoveAllAsync() { StartTx(); return DoOutOpAsync(CacheOp.RemoveAll2Async); } /** <inheritDoc /> */ public int GetLocalSize(params CachePeekMode[] modes) { return Size0(true, modes); } /** <inheritDoc /> */ public int GetSize(params CachePeekMode[] modes) { return Size0(false, modes); } /** <inheritDoc /> */ public Task<int> GetSizeAsync(params CachePeekMode[] modes) { var modes0 = EncodePeekModes(modes); return DoOutOpAsync<int>(CacheOp.SizeAsync, w => w.WriteInt(modes0)); } /// <summary> /// Internal size routine. /// </summary> /// <param name="loc">Local flag.</param> /// <param name="modes">peek modes</param> /// <returns>Size.</returns> private int Size0(bool loc, params CachePeekMode[] modes) { var modes0 = EncodePeekModes(modes); var op = loc ? CacheOp.SizeLoc : CacheOp.Size; return (int) DoOutInOp((int) op, modes0); } /** <inheritdoc /> */ public TRes Invoke<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(processor, "processor"); StartTx(); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutInOpX((int) CacheOp.Invoke, writer => { writer.Write(key); writer.Write(holder); }, (input, res) => res == True ? Unmarshal<TRes>(input) : default(TRes), ReadException); } /** <inheritDoc /> */ public Task<TRes> InvokeAsync<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(processor, "processor"); StartTx(); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutOpAsync(CacheOp.InvokeAsync, writer => { writer.Write(key); writer.Write(holder); }, r => { if (r == null) return default(TRes); var hasError = r.ReadBoolean(); if (hasError) throw ReadException(r); return r.ReadObject<TRes>(); }); } /** <inheritdoc /> */ public ICollection<ICacheEntryProcessorResult<TK, TRes>> InvokeAll<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(keys, "keys"); IgniteArgumentCheck.NotNull(processor, "processor"); StartTx(); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutInOpX((int) CacheOp.InvokeAll, writer => { WriteEnumerable(writer, keys); writer.Write(holder); }, (input, res) => res == True ? ReadInvokeAllResults<TRes>(Marshaller.StartUnmarshal(input, IsKeepBinary)): null, ReadException); } /** <inheritDoc /> */ public Task<ICollection<ICacheEntryProcessorResult<TK, TRes>>> InvokeAllAsync<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(keys, "keys"); IgniteArgumentCheck.NotNull(processor, "processor"); StartTx(); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutOpAsync(CacheOp.InvokeAllAsync, writer => { WriteEnumerable(writer, keys); writer.Write(holder); }, input => ReadInvokeAllResults<TRes>(input)); } /** <inheritDoc /> */ public T DoOutInOpExtension<T>(int extensionId, int opCode, Action<IBinaryRawWriter> writeAction, Func<IBinaryRawReader, T> readFunc) { return DoOutInOpX((int) CacheOp.Extension, writer => { writer.WriteInt(extensionId); writer.WriteInt(opCode); writeAction(writer); }, (input, res) => res == True ? readFunc(Marshaller.StartUnmarshal(input)) : default(T), ReadException); } /** <inheritdoc /> */ public ICacheLock Lock(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOpX((int) CacheOp.Lock, w => w.Write(key), (stream, res) => new CacheLock(stream.ReadInt(), this), ReadException); } /** <inheritdoc /> */ public ICacheLock LockAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutInOpX((int) CacheOp.LockAll, w => WriteEnumerable(w, keys), (stream, res) => new CacheLock(stream.ReadInt(), this), ReadException); } /** <inheritdoc /> */ public bool IsLocalLocked(TK key, bool byCurrentThread) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp(CacheOp.IsLocalLocked, writer => { writer.Write(key); writer.WriteBoolean(byCurrentThread); }); } /** <inheritDoc /> */ public ICacheMetrics GetMetrics() { return DoInOp((int) CacheOp.GlobalMetrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return new CacheMetricsImpl(reader); }); } /** <inheritDoc /> */ public ICacheMetrics GetMetrics(IClusterGroup clusterGroup) { IgniteArgumentCheck.NotNull(clusterGroup, "clusterGroup"); var prj = clusterGroup as ClusterGroupImpl; if (prj == null) throw new ArgumentException("Unexpected IClusterGroup implementation: " + clusterGroup.GetType()); return prj.GetCacheMetrics(Name); } /** <inheritDoc /> */ public ICacheMetrics GetLocalMetrics() { return DoInOp((int) CacheOp.LocalMetrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return new CacheMetricsImpl(reader); }); } /** <inheritDoc /> */ public Task Rebalance() { return DoOutOpAsync(CacheOp.Rebalance); } /** <inheritDoc /> */ public ICache<TK, TV> WithNoRetries() { if (_flagNoRetries) return this; return new CacheImpl<TK, TV>(_ignite, DoOutOpObject((int) CacheOp.WithNoRetries), Marshaller, _flagSkipStore, _flagKeepBinary, true, _flagPartitionRecover); } /** <inheritDoc /> */ public ICache<TK, TV> WithPartitionRecover() { if (_flagPartitionRecover) return this; return new CacheImpl<TK, TV>(_ignite, DoOutOpObject((int) CacheOp.WithPartitionRecover), Marshaller, _flagSkipStore, _flagKeepBinary, _flagNoRetries, true); } /** <inheritDoc /> */ public ICollection<int> GetLostPartitions() { return DoInOp((int) CacheOp.GetLostPartitions, s => { var cnt = s.ReadInt(); var res = new List<int>(cnt); if (cnt > 0) { for (var i = 0; i < cnt; i++) { res.Add(s.ReadInt()); } } return res; }); } #region Queries /** <inheritDoc /> */ public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry) { return QueryFields(qry, ReadFieldsArrayList); } /// <summary> /// Reads the fields array list. /// </summary> private static IList ReadFieldsArrayList(IBinaryRawReader reader, int count) { IList res = new ArrayList(count); for (var i = 0; i < count; i++) res.Add(reader.ReadObject<object>()); return res; } /** <inheritDoc /> */ public IQueryCursor<T> QueryFields<T>(SqlFieldsQuery qry, Func<IBinaryRawReader, int, T> readerFunc) { IgniteArgumentCheck.NotNull(qry, "qry"); IgniteArgumentCheck.NotNull(readerFunc, "readerFunc"); if (string.IsNullOrEmpty(qry.Sql)) throw new ArgumentException("Sql cannot be null or empty"); var cursor = DoOutOpObject((int) CacheOp.QrySqlFields, writer => { writer.WriteBoolean(qry.Local); writer.WriteString(qry.Sql); writer.WriteInt(qry.PageSize); QueryBase.WriteQueryArgs(writer, qry.Arguments); writer.WriteBoolean(qry.EnableDistributedJoins); writer.WriteBoolean(qry.EnforceJoinOrder); writer.WriteInt((int) qry.Timeout.TotalMilliseconds); writer.WriteBoolean(qry.ReplicatedOnly); writer.WriteBoolean(qry.Colocated); writer.WriteString(qry.Schema); // Schema }); return new FieldsQueryCursor<T>(cursor, Marshaller, _flagKeepBinary, readerFunc); } /** <inheritDoc /> */ public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry) { IgniteArgumentCheck.NotNull(qry, "qry"); var cursor = DoOutOpObject((int) qry.OpId, writer => qry.Write(writer, IsKeepBinary)); return new QueryCursor<TK, TV>(cursor, Marshaller, _flagKeepBinary); } /** <inheritdoc /> */ public IContinuousQueryHandle QueryContinuous(ContinuousQuery<TK, TV> qry) { IgniteArgumentCheck.NotNull(qry, "qry"); return QueryContinuousImpl(qry, null); } /** <inheritdoc /> */ public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry) { IgniteArgumentCheck.NotNull(qry, "qry"); IgniteArgumentCheck.NotNull(initialQry, "initialQry"); return QueryContinuousImpl(qry, initialQry); } /// <summary> /// QueryContinuous implementation. /// </summary> private IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuousImpl(ContinuousQuery<TK, TV> qry, QueryBase initialQry) { qry.Validate(); return new ContinuousQueryHandleImpl<TK, TV>(qry, Marshaller, _flagKeepBinary, writeAction => DoOutOpObject((int) CacheOp.QryContinuous, writeAction), initialQry); } #endregion #region Enumerable support /** <inheritdoc /> */ public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(CachePeekMode[] peekModes) { return new CacheEnumerable<TK, TV>(this, EncodePeekModes(peekModes)); } /** <inheritdoc /> */ public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator() { return new CacheEnumeratorProxy<TK, TV>(this, false, 0); } /** <inheritdoc /> */ IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Create real cache enumerator. /// </summary> /// <param name="loc">Local flag.</param> /// <param name="peekModes">Peek modes for local enumerator.</param> /// <returns>Cache enumerator.</returns> internal CacheEnumerator<TK, TV> CreateEnumerator(bool loc, int peekModes) { if (loc) { var target = DoOutOpObject((int) CacheOp.LocIterator, w => w.WriteInt(peekModes)); return new CacheEnumerator<TK, TV>(target, Marshaller, _flagKeepBinary); } return new CacheEnumerator<TK, TV>(DoOutOpObject((int) CacheOp.Iterator), Marshaller, _flagKeepBinary); } #endregion /** <inheritDoc /> */ protected override T Unmarshal<T>(IBinaryStream stream) { return Marshaller.Unmarshal<T>(stream, _flagKeepBinary); } /// <summary> /// Encodes the peek modes into a single int value. /// </summary> private static int EncodePeekModes(CachePeekMode[] modes) { int modesEncoded = 0; if (modes != null) { foreach (var mode in modes) modesEncoded |= (int) mode; } return modesEncoded; } /// <summary> /// Reads results of InvokeAll operation. /// </summary> /// <typeparam name="T">The type of the result.</typeparam> /// <param name="reader">Stream.</param> /// <returns>Results of InvokeAll operation.</returns> private ICollection<ICacheEntryProcessorResult<TK, T>> ReadInvokeAllResults<T>(BinaryReader reader) { var count = reader.ReadInt(); if (count == -1) return null; var results = new List<ICacheEntryProcessorResult<TK, T>>(count); for (var i = 0; i < count; i++) { var key = reader.ReadObject<TK>(); var hasError = reader.ReadBoolean(); results.Add(hasError ? new CacheEntryProcessorResult<TK, T>(key, ReadException(reader)) : new CacheEntryProcessorResult<TK, T>(key, reader.ReadObject<T>())); } return results; } /// <summary> /// Reads the exception. /// </summary> private Exception ReadException(IBinaryStream stream) { return ReadException(Marshaller.StartUnmarshal(stream)); } /// <summary> /// Reads the exception, either in binary wrapper form, or as a pair of strings. /// </summary> /// <param name="reader">The stream.</param> /// <returns>Exception.</returns> private Exception ReadException(BinaryReader reader) { var item = reader.ReadObject<object>(); var clsName = item as string; if (clsName == null) return new CacheEntryProcessorException((Exception) item); var msg = reader.ReadObject<string>(); var trace = reader.ReadObject<string>(); var inner = reader.ReadBoolean() ? reader.ReadObject<Exception>() : null; return ExceptionUtils.GetException(_ignite, clsName, msg, trace, reader, inner); } /// <summary> /// Read dictionary returned by GET_ALL operation. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Dictionary.</returns> private static ICollection<ICacheEntry<TK, TV>> ReadGetAllDictionary(BinaryReader reader) { if (reader == null) return null; IBinaryStream stream = reader.Stream; if (stream.ReadBool()) { int size = stream.ReadInt(); var res = new List<ICacheEntry<TK, TV>>(size); for (int i = 0; i < size; i++) { TK key = reader.ReadObject<TK>(); TV val = reader.ReadObject<TV>(); res.Add(new CacheEntry<TK, TV>(key, val)); } return res; } return null; } /// <summary> /// Gets the cache result. /// </summary> private static CacheResult<TV> GetCacheResult(BinaryReader reader) { var res = reader == null ? new CacheResult<TV>() : new CacheResult<TV>(reader.ReadObject<TV>()); return res; } /// <summary> /// Throws the key not found exception. /// </summary> private static KeyNotFoundException GetKeyNotFoundException() { return new KeyNotFoundException("The given key was not present in the cache."); } /// <summary> /// Does the out op. /// </summary> private bool DoOutOp<T1>(CacheOp op, T1 x) { return DoOutInOpX((int) op, w => { w.Write(x); }, ReadException); } /// <summary> /// Does the out op. /// </summary> private bool DoOutOp<T1, T2>(CacheOp op, T1 x, T2 y) { return DoOutInOpX((int) op, w => { w.Write(x); w.Write(y); }, ReadException); } /// <summary> /// Does the out op. /// </summary> private bool DoOutOp<T1, T2, T3>(CacheOp op, T1 x, T2 y, T3 z) { return DoOutInOpX((int) op, w => { w.Write(x); w.Write(y); w.Write(z); }, ReadException); } /// <summary> /// Does the out op. /// </summary> private bool DoOutOp(CacheOp op, Action<BinaryWriter> write) { return DoOutInOpX((int) op, write, ReadException); } /// <summary> /// Does the out-in op. /// </summary> private CacheResult<TV> DoOutInOpNullable(CacheOp cacheOp, TK x) { return DoOutInOpX((int)cacheOp, w => w.Write(x), (stream, res) => res == True ? new CacheResult<TV>(Unmarshal<TV>(stream)) : new CacheResult<TV>(), ReadException); } /// <summary> /// Does the out-in op. /// </summary> private CacheResult<TV> DoOutInOpNullable<T1, T2>(CacheOp cacheOp, T1 x, T2 y) { return DoOutInOpX((int)cacheOp, w => { w.Write(x); w.Write(y); }, (stream, res) => res == True ? new CacheResult<TV>(Unmarshal<TV>(stream)) : new CacheResult<TV>(), ReadException); } /** <inheritdoc /> */ public void Enter(long id) { DoOutInOp((int) CacheOp.EnterLock, id); } /** <inheritdoc /> */ public bool TryEnter(long id, TimeSpan timeout) { return DoOutOp((int) CacheOp.TryEnterLock, (IBinaryStream s) => { s.WriteLong(id); s.WriteLong((long) timeout.TotalMilliseconds); }) == True; } /** <inheritdoc /> */ public void Exit(long id) { DoOutInOp((int) CacheOp.ExitLock, id); } /** <inheritdoc /> */ public void Close(long id) { DoOutInOp((int) CacheOp.CloseLock, id); } /// <summary> /// Starts a transaction when applicable. /// </summary> private void StartTx() { if (_txManager != null) _txManager.StartTx(); } } }
using System; using System.IO; namespace ClrTest.Reflection { public interface IILStringCollector { void Process(ILInstruction ilInstruction, string operandString); } public class ReadableILStringToTextWriter : IILStringCollector { protected TextWriter writer; public ReadableILStringToTextWriter(TextWriter writer) { this.writer = writer; } public virtual void Process(ILInstruction ilInstruction, string operandString) { this.writer.WriteLine("IL_{0:x4}: {1,-10} {2}", ilInstruction.Offset, ilInstruction.OpCode.Name, operandString); } } public class RawILStringToTextWriter : ReadableILStringToTextWriter { public RawILStringToTextWriter(TextWriter writer) : base(writer) { } public override void Process(ILInstruction ilInstruction, string operandString) { this.writer.WriteLine("IL_{0:x4}: {1,-4}| {2, -8}", ilInstruction.Offset, ilInstruction.OpCode.Value.ToString("x2"), operandString); } } public abstract class ILInstructionVisitor { public virtual void VisitInlineBrTargetInstruction(InlineBrTargetInstruction inlineBrTargetInstruction) { } public virtual void VisitInlineFieldInstruction(InlineFieldInstruction inlineFieldInstruction) { } public virtual void VisitInlineIInstruction(InlineIInstruction inlineIInstruction) { } public virtual void VisitInlineI8Instruction(InlineI8Instruction inlineI8Instruction) { } public virtual void VisitInlineMethodInstruction(InlineMethodInstruction inlineMethodInstruction) { } public virtual void VisitInlineNoneInstruction(InlineNoneInstruction inlineNoneInstruction) { } public virtual void VisitInlineRInstruction(InlineRInstruction inlineRInstruction) { } public virtual void VisitInlineSigInstruction(InlineSigInstruction inlineSigInstruction) { } public virtual void VisitInlineStringInstruction(InlineStringInstruction inlineStringInstruction) { } public virtual void VisitInlineSwitchInstruction(InlineSwitchInstruction inlineSwitchInstruction) { } public virtual void VisitInlineTokInstruction(InlineTokInstruction inlineTokInstruction) { } public virtual void VisitInlineTypeInstruction(InlineTypeInstruction inlineTypeInstruction) { } public virtual void VisitInlineVarInstruction(InlineVarInstruction inlineVarInstruction) { } public virtual void VisitShortInlineBrTargetInstruction(ShortInlineBrTargetInstruction shortInlineBrTargetInstruction) { } public virtual void VisitShortInlineIInstruction(ShortInlineIInstruction shortInlineIInstruction) { } public virtual void VisitShortInlineRInstruction(ShortInlineRInstruction shortInlineRInstruction) { } public virtual void VisitShortInlineVarInstruction(ShortInlineVarInstruction shortInlineVarInstruction) { } } public class ReadableILStringVisitor : ILInstructionVisitor { protected IFormatProvider formatProvider; protected IILStringCollector collector; public ReadableILStringVisitor(IILStringCollector collector) : this(collector, DefaultFormatProvider.Instance) { } public ReadableILStringVisitor(IILStringCollector collector, IFormatProvider formatProvider) { this.formatProvider = formatProvider; this.collector = collector; } public override void VisitInlineBrTargetInstruction(InlineBrTargetInstruction inlineBrTargetInstruction) { collector.Process(inlineBrTargetInstruction, formatProvider.Label(inlineBrTargetInstruction.TargetOffset)); } public override void VisitInlineFieldInstruction(InlineFieldInstruction inlineFieldInstruction) { string field; try { field = inlineFieldInstruction.Field + "/" + inlineFieldInstruction.Field.DeclaringType; } catch (Exception ex) { field = "!" + ex.Message + "!"; } collector.Process(inlineFieldInstruction, field); } public override void VisitInlineIInstruction(InlineIInstruction inlineIInstruction) { collector.Process(inlineIInstruction, inlineIInstruction.Int32.ToString()); } public override void VisitInlineI8Instruction(InlineI8Instruction inlineI8Instruction) { collector.Process(inlineI8Instruction, inlineI8Instruction.Int64.ToString()); } public override void VisitInlineMethodInstruction(InlineMethodInstruction inlineMethodInstruction) { string method; try { method = inlineMethodInstruction.Method + "/" + inlineMethodInstruction.Method.DeclaringType; } catch (Exception ex) { method = "!" + ex.Message + "!"; } collector.Process(inlineMethodInstruction, method); } public override void VisitInlineNoneInstruction(InlineNoneInstruction inlineNoneInstruction) { collector.Process(inlineNoneInstruction, string.Empty); } public override void VisitInlineRInstruction(InlineRInstruction inlineRInstruction) { collector.Process(inlineRInstruction, inlineRInstruction.Double.ToString()); } public override void VisitInlineSigInstruction(InlineSigInstruction inlineSigInstruction) { collector.Process(inlineSigInstruction, formatProvider.SigByteArrayToString(inlineSigInstruction.Signature)); } public override void VisitInlineStringInstruction(InlineStringInstruction inlineStringInstruction) { collector.Process(inlineStringInstruction, formatProvider.EscapedString(inlineStringInstruction.String)); } public override void VisitInlineSwitchInstruction(InlineSwitchInstruction inlineSwitchInstruction) { collector.Process(inlineSwitchInstruction, formatProvider.MultipleLabels(inlineSwitchInstruction.TargetOffsets)); } public override void VisitInlineTokInstruction(InlineTokInstruction inlineTokInstruction) { string member; try { member = inlineTokInstruction.Member + "/" + inlineTokInstruction.Member.DeclaringType; } catch (Exception ex) { member = "!" + ex.Message + "!"; } collector.Process(inlineTokInstruction, member); } public override void VisitInlineTypeInstruction(InlineTypeInstruction inlineTypeInstruction) { string type; try { type = inlineTypeInstruction.Type.Name; } catch (Exception ex) { type = "!" + ex.Message + "!"; } collector.Process(inlineTypeInstruction, type); } public override void VisitInlineVarInstruction(InlineVarInstruction inlineVarInstruction) { collector.Process(inlineVarInstruction, formatProvider.Argument(inlineVarInstruction.Ordinal)); } public override void VisitShortInlineBrTargetInstruction(ShortInlineBrTargetInstruction shortInlineBrTargetInstruction) { collector.Process(shortInlineBrTargetInstruction, formatProvider.Label(shortInlineBrTargetInstruction.TargetOffset)); } public override void VisitShortInlineIInstruction(ShortInlineIInstruction shortInlineIInstruction) { collector.Process(shortInlineIInstruction, shortInlineIInstruction.Byte.ToString()); } public override void VisitShortInlineRInstruction(ShortInlineRInstruction shortInlineRInstruction) { collector.Process(shortInlineRInstruction, shortInlineRInstruction.Single.ToString()); } public override void VisitShortInlineVarInstruction(ShortInlineVarInstruction shortInlineVarInstruction) { collector.Process(shortInlineVarInstruction, formatProvider.Argument(shortInlineVarInstruction.Ordinal)); } } public class RawILStringVisitor : ReadableILStringVisitor { public RawILStringVisitor(IILStringCollector collector) : this(collector, DefaultFormatProvider.Instance) { } public RawILStringVisitor(IILStringCollector collector, IFormatProvider formatProvider) : base(collector, formatProvider) { } public override void VisitInlineBrTargetInstruction(InlineBrTargetInstruction inlineBrTargetInstruction) { collector.Process(inlineBrTargetInstruction, formatProvider.Int32ToHex(inlineBrTargetInstruction.Delta)); } public override void VisitInlineFieldInstruction(InlineFieldInstruction inlineFieldInstruction) { collector.Process(inlineFieldInstruction, formatProvider.Int32ToHex(inlineFieldInstruction.Token)); } public override void VisitInlineMethodInstruction(InlineMethodInstruction inlineMethodInstruction) { collector.Process(inlineMethodInstruction, formatProvider.Int32ToHex(inlineMethodInstruction.Token)); } public override void VisitInlineSigInstruction(InlineSigInstruction inlineSigInstruction) { collector.Process(inlineSigInstruction, formatProvider.Int32ToHex(inlineSigInstruction.Token)); } public override void VisitInlineStringInstruction(InlineStringInstruction inlineStringInstruction) { collector.Process(inlineStringInstruction, formatProvider.Int32ToHex(inlineStringInstruction.Token)); } public override void VisitInlineSwitchInstruction(InlineSwitchInstruction inlineSwitchInstruction) { collector.Process(inlineSwitchInstruction, "..."); } public override void VisitInlineTokInstruction(InlineTokInstruction inlineTokInstruction) { collector.Process(inlineTokInstruction, formatProvider.Int32ToHex(inlineTokInstruction.Token)); } public override void VisitInlineTypeInstruction(InlineTypeInstruction inlineTypeInstruction) { collector.Process(inlineTypeInstruction, formatProvider.Int32ToHex(inlineTypeInstruction.Token)); } public override void VisitInlineVarInstruction(InlineVarInstruction inlineVarInstruction) { collector.Process(inlineVarInstruction, formatProvider.Int16ToHex(inlineVarInstruction.Ordinal)); } public override void VisitShortInlineBrTargetInstruction(ShortInlineBrTargetInstruction shortInlineBrTargetInstruction) { collector.Process(shortInlineBrTargetInstruction, formatProvider.Int8ToHex(shortInlineBrTargetInstruction.Delta)); } public override void VisitShortInlineVarInstruction(ShortInlineVarInstruction shortInlineVarInstruction) { collector.Process(shortInlineVarInstruction, formatProvider.Int8ToHex(shortInlineVarInstruction.Ordinal)); } } }
using System; using System.Collections; using System.Linq; using System.Text; using NUnit.Framework; // ReSharper disable UnusedMember.Local // ReSharper disable UnusedParameter.Local namespace NetGore.Tests.NetGore { [TestFixture] public class TypeFilterCreatorTests { #region Unit tests [Test] public void AttributeFailTest() { var f1 = new TypeFilterCreator { RequireAttributes = true, MatchAllAttributes = true, Attributes = new Type[] { typeof(DescriptionAttribute), typeof(AttribA) } }; var f2 = new TypeFilterCreator { RequireAttributes = true, MatchAllAttributes = true, Attributes = new Type[] { typeof(DescriptionAttribute), typeof(AttribB) } }; var f3 = new TypeFilterCreator { RequireAttributes = true, MatchAllAttributes = true, Attributes = new Type[] { typeof(DescriptionAttribute) } }; Assert.Throws<TypeFilterException>(() => f1.GetFilter()(typeof(A))); Assert.Throws<TypeFilterException>(() => f2.GetFilter()(typeof(A))); Assert.Throws<TypeFilterException>(() => f3.GetFilter()(typeof(A))); } [Test] public void AttributePassTest() { var f1 = new TypeFilterCreator { RequireAttributes = true, MatchAllAttributes = true, Attributes = new Type[] { typeof(AttribA) } }; var f2 = new TypeFilterCreator { RequireAttributes = true, MatchAllAttributes = true, Attributes = new Type[] { typeof(AttribB) } }; var f3 = new TypeFilterCreator { RequireAttributes = true, MatchAllAttributes = true, Attributes = new Type[] { typeof(AttribA), typeof(AttribB) } }; var f4 = new TypeFilterCreator { RequireAttributes = true, MatchAllAttributes = true, Attributes = new Type[] { typeof(AttribA), typeof(AttribB) } }; Assert.IsTrue(f1.GetFilter()(typeof(A))); Assert.IsTrue(f2.GetFilter()(typeof(A))); Assert.IsTrue(f3.GetFilter()(typeof(A))); Assert.IsTrue(f4.GetFilter()(typeof(A))); } [Test] public void ConstructorFailTest() { var f1 = new TypeFilterCreator { RequireConstructor = true, ConstructorParameters = new Type[] { typeof(object) } }; var f2 = new TypeFilterCreator { RequireConstructor = true, ConstructorParameters = new Type[] { typeof(object), typeof(int) } }; Assert.Throws<TypeFilterException>(() => f1.GetFilter()(typeof(A))); Assert.Throws<TypeFilterException>(() => f2.GetFilter()(typeof(A))); } [Test] public void ConstructorPassTest() { var f1 = new TypeFilterCreator { RequireConstructor = true, ConstructorParameters = new Type[] { typeof(object), typeof(string) } }; var f2 = new TypeFilterCreator { RequireConstructor = true, ConstructorParameters = Type.EmptyTypes }; Assert.IsTrue(f1.GetFilter()(typeof(A))); Assert.IsTrue(f2.GetFilter()(typeof(A))); } [Test] public void CustomFilterTest() { var f1 = new TypeFilterCreator { CustomFilter = (x => !x.IsPublic) }; var f2 = new TypeFilterCreator { CustomFilter = (x => x == typeof(object)) }; Assert.IsTrue(f1.GetFilter()(typeof(A))); Assert.IsFalse(f1.GetFilter()(typeof(object))); Assert.IsFalse(f2.GetFilter()(typeof(A))); Assert.IsTrue(f2.GetFilter()(typeof(object))); } [Test] public void InterfaceFailTest() { var f1 = new TypeFilterCreator { RequireInterfaces = true, MatchAllInterfaces = true, Interfaces = new Type[] { typeof(IEnumerable), typeof(Ia) } }; var f2 = new TypeFilterCreator { RequireInterfaces = true, MatchAllInterfaces = true, Interfaces = new Type[] { typeof(IEnumerable), typeof(Ib) } }; var f3 = new TypeFilterCreator { RequireInterfaces = true, MatchAllInterfaces = true, Interfaces = new Type[] { typeof(IEnumerable), typeof(Ia), typeof(Ib) } }; var f4 = new TypeFilterCreator { RequireInterfaces = true, MatchAllInterfaces = true, Interfaces = new Type[] { typeof(IEnumerable), typeof(Ia), typeof(Ib) } }; var f5 = new TypeFilterCreator { RequireInterfaces = true, MatchAllInterfaces = false, Interfaces = new Type[] { typeof(IEnumerable) } }; Assert.Throws<TypeFilterException>(() => f1.GetFilter()(typeof(A))); Assert.Throws<TypeFilterException>(() => f2.GetFilter()(typeof(A))); Assert.Throws<TypeFilterException>(() => f3.GetFilter()(typeof(A))); Assert.Throws<TypeFilterException>(() => f4.GetFilter()(typeof(A))); Assert.Throws<TypeFilterException>(() => f5.GetFilter()(typeof(A))); } [Test] public void InterfacePassTest() { var f1 = new TypeFilterCreator { RequireInterfaces = true, MatchAllInterfaces = true, Interfaces = new Type[] { typeof(Ia) } }; var f2 = new TypeFilterCreator { RequireInterfaces = true, MatchAllInterfaces = true, Interfaces = new Type[] { typeof(Ib) } }; var f3 = new TypeFilterCreator { RequireInterfaces = true, MatchAllInterfaces = true, Interfaces = new Type[] { typeof(Ia), typeof(Ib) } }; var f4 = new TypeFilterCreator { RequireInterfaces = true, MatchAllInterfaces = true, Interfaces = new Type[] { typeof(Ia), typeof(Ib) } }; Assert.IsTrue(f1.GetFilter()(typeof(A))); Assert.IsTrue(f2.GetFilter()(typeof(A))); Assert.IsTrue(f3.GetFilter()(typeof(A))); Assert.IsTrue(f4.GetFilter()(typeof(A))); } [Test] public void IsAbstractFailTest() { var f1 = new TypeFilterCreator { IsAbstract = false }; Assert.IsFalse(f1.GetFilter()(typeof(baseClass))); } [Test] public void IsAbstractNullTest() { var f1 = new TypeFilterCreator { IsAbstract = null }; Assert.IsTrue(f1.GetFilter()(typeof(int))); } [Test] public void IsAbstractPassTest() { var f1 = new TypeFilterCreator { IsAbstract = true }; Assert.IsTrue(f1.GetFilter()(typeof(baseClass))); } [Test] public void IsClassFailTest() { var f1 = new TypeFilterCreator { IsClass = false }; Assert.IsFalse(f1.GetFilter()(typeof(A))); } [Test] public void IsClassNullTest() { var f1 = new TypeFilterCreator { IsClass = null }; Assert.IsTrue(f1.GetFilter()(typeof(int))); } [Test] public void IsClassPassTest() { var f1 = new TypeFilterCreator { IsClass = true }; Assert.IsTrue(f1.GetFilter()(typeof(A))); } [Test] public void IsInterfaceFailTest() { var f1 = new TypeFilterCreator { IsInterface = false }; Assert.IsFalse(f1.GetFilter()(typeof(Ia))); } [Test] public void IsInterfaceNullTest() { var f1 = new TypeFilterCreator { IsInterface = null }; Assert.IsTrue(f1.GetFilter()(typeof(int))); } [Test] public void IsInterfacePassTest() { var f1 = new TypeFilterCreator { IsInterface = true }; Assert.IsTrue(f1.GetFilter()(typeof(Ia))); } [Test] public void SubclassFailTest() { var f1 = new TypeFilterCreator { Subclass = typeof(StringBuilder) }; var f2 = new TypeFilterCreator { Subclass = typeof(Ia) }; Assert.IsFalse(f1.GetFilter()(typeof(A))); Assert.IsFalse(f2.GetFilter()(typeof(A))); } [Test] public void SubclassPassTest() { var f1 = new TypeFilterCreator { Subclass = typeof(baseClass) }; var f2 = new TypeFilterCreator { Subclass = typeof(object) }; Assert.IsTrue(f1.GetFilter()(typeof(A))); Assert.IsTrue(f2.GetFilter()(typeof(A))); } #endregion [AttribA] [AttribB] class A : baseClass, Ia, Ib { public A(object a, string b) { } A() { } } sealed class AttribA : Attribute { } sealed class AttribB : Attribute { } interface Ia { } interface Ib { } abstract class baseClass { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime; using System.Xml; namespace System.ServiceModel.Channels { internal abstract class BufferedMessageData : IBufferedMessageData { private ArraySegment<byte> _buffer; private BufferManager _bufferManager; private int _refCount; private int _outstandingReaders; private bool _multipleUsers; private RecycledMessageState _messageState; private SynchronizedPool<RecycledMessageState> _messageStatePool; public BufferedMessageData(SynchronizedPool<RecycledMessageState> messageStatePool) { _messageStatePool = messageStatePool; } public ArraySegment<byte> Buffer { get { return _buffer; } } public BufferManager BufferManager { get { return _bufferManager; } } public virtual XmlDictionaryReaderQuotas Quotas { get { return XmlDictionaryReaderQuotas.Max; } } public abstract MessageEncoder MessageEncoder { get; } private object ThisLock { get { return this; } } public void EnableMultipleUsers() { _multipleUsers = true; } public void Close() { if (_multipleUsers) { lock (ThisLock) { if (--_refCount == 0) { DoClose(); } } } else { DoClose(); } } private void DoClose() { _bufferManager.ReturnBuffer(_buffer.Array); if (_outstandingReaders == 0) { _bufferManager = null; _buffer = new ArraySegment<byte>(); OnClosed(); } } public void DoReturnMessageState(RecycledMessageState messageState) { if (_messageState == null) { _messageState = messageState; } else { _messageStatePool.Return(messageState); } } private void DoReturnXmlReader(XmlDictionaryReader reader) { ReturnXmlReader(reader); _outstandingReaders--; } public RecycledMessageState DoTakeMessageState() { RecycledMessageState messageState = _messageState; if (messageState != null) { _messageState = null; return messageState; } else { return _messageStatePool.Take(); } } private XmlDictionaryReader DoTakeXmlReader() { XmlDictionaryReader reader = TakeXmlReader(); _outstandingReaders++; return reader; } public XmlDictionaryReader GetMessageReader() { if (_multipleUsers) { lock (ThisLock) { return DoTakeXmlReader(); } } else { return DoTakeXmlReader(); } } public void OnXmlReaderClosed(XmlDictionaryReader reader) { if (_multipleUsers) { lock (ThisLock) { DoReturnXmlReader(reader); } } else { DoReturnXmlReader(reader); } } protected virtual void OnClosed() { } public RecycledMessageState TakeMessageState() { if (_multipleUsers) { lock (ThisLock) { return DoTakeMessageState(); } } else { return DoTakeMessageState(); } } protected abstract XmlDictionaryReader TakeXmlReader(); public void Open() { lock (ThisLock) { _refCount++; } } public void Open(ArraySegment<byte> buffer, BufferManager bufferManager) { _refCount = 1; _bufferManager = bufferManager; _buffer = buffer; _multipleUsers = false; } protected abstract void ReturnXmlReader(XmlDictionaryReader xmlReader); public void ReturnMessageState(RecycledMessageState messageState) { if (_multipleUsers) { lock (ThisLock) { DoReturnMessageState(messageState); } } else { DoReturnMessageState(messageState); } } } }
// // BEncodedList.cs // // Authors: // Alan McGovern [email protected] // // Copyright (C) 2006 Alan McGovern // // 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; using System.IO; namespace ResumeEditor.BEncoding { /// <summary> /// Class representing a BEncoded list /// </summary> public class BEncodedList : BEncodedValue, IList<BEncodedValue> { #region Member Variables private List<BEncodedValue> list; #endregion #region Constructors /// <summary> /// Create a new BEncoded List with default capacity /// </summary> public BEncodedList() : this(new List<BEncodedValue>()) { } /// <summary> /// Create a new BEncoded List with the supplied capacity /// </summary> /// <param name="capacity">The initial capacity</param> public BEncodedList(int capacity) : this(new List<BEncodedValue>(capacity)) { } public BEncodedList(IEnumerable<BEncodedValue> list) { if (list == null) throw new ArgumentNullException("list"); this.list = new List<BEncodedValue>(list); } private BEncodedList(List<BEncodedValue> value) { this.list = value; } #endregion #region Encode/Decode Methods /// <summary> /// Encodes the list to a byte[] /// </summary> /// <param name="buffer">The buffer to encode the list to</param> /// <param name="offset">The offset to start writing the data at</param> /// <returns></returns> public override int Encode(byte[] buffer, int offset) { int written = 0; buffer[offset] = (byte)'l'; written++; for (int i = 0; i < this.list.Count; i++) written += this.list[i].Encode(buffer, offset + written); buffer[offset + written] = (byte)'e'; written++; return written; } /// <summary> /// Decodes a BEncodedList from the given StreamReader /// </summary> /// <param name="reader"></param> internal override void DecodeInternal(RawReader reader) { if (reader.ReadByte() != 'l') // Remove the leading 'l' throw new BEncodingException("Invalid data found. Aborting"); while ((reader.PeekByte() != -1) && (reader.PeekByte() != 'e')) list.Add(BEncodedValue.Decode(reader)); if (reader.ReadByte() != 'e') // Remove the trailing 'e' throw new BEncodingException("Invalid data found. Aborting"); } #endregion #region Helper Methods /// <summary> /// Returns the size of the list in bytes /// </summary> /// <returns></returns> public override int LengthInBytes() { int length = 0; length += 1; // Lists start with 'l' for (int i=0; i < this.list.Count; i++) length += this.list[i].LengthInBytes(); length += 1; // Lists end with 'e' return length; } #endregion #region Overridden Methods public override bool Equals(object obj) { BEncodedList other = obj as BEncodedList; if (other == null) return false; for (int i = 0; i < this.list.Count; i++) if (!this.list[i].Equals(other.list[i])) return false; return true; } public override int GetHashCode() { int result = 0; for (int i = 0; i < list.Count; i++) result ^= list[i].GetHashCode(); return result; } public override string ToString() { return System.Text.Encoding.UTF8.GetString(Encode()); } #endregion #region IList methods public void Add(BEncodedValue item) { this.list.Add(item); } public void AddRange (IEnumerable<BEncodedValue> collection) { list.AddRange (collection); } public void Clear() { this.list.Clear(); } public bool Contains(BEncodedValue item) { return this.list.Contains(item); } public void CopyTo(BEncodedValue[] array, int arrayIndex) { this.list.CopyTo(array, arrayIndex); } public int Count { get { return this.list.Count; } } public int IndexOf(BEncodedValue item) { return this.list.IndexOf(item); } public void Insert(int index, BEncodedValue item) { this.list.Insert(index, item); } public bool IsReadOnly { get { return false; } } public bool Remove(BEncodedValue item) { return this.list.Remove(item); } public void RemoveAt(int index) { this.list.RemoveAt(index); } public BEncodedValue this[int index] { get { return this.list[index]; } set { this.list[index] = value; } } public IEnumerator<BEncodedValue> GetEnumerator() { return this.list.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion } }
using System; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Engines { /** * an implementation of Rijndael, based on the documentation and reference implementation * by Paulo Barreto, Vincent Rijmen, for v2.0 August '99. * <p> * Note: this implementation is based on information prior to readonly NIST publication. * </p> */ public class RijndaelEngine : IBlockCipher { private static readonly int MAXROUNDS = 14; private static readonly int MAXKC = (256/4); private static readonly byte[] Logtable = { 0, 0, 25, 1, 50, 2, 26, 198, 75, 199, 27, 104, 51, 238, 223, 3, 100, 4, 224, 14, 52, 141, 129, 239, 76, 113, 8, 200, 248, 105, 28, 193, 125, 194, 29, 181, 249, 185, 39, 106, 77, 228, 166, 114, 154, 201, 9, 120, 101, 47, 138, 5, 33, 15, 225, 36, 18, 240, 130, 69, 53, 147, 218, 142, 150, 143, 219, 189, 54, 208, 206, 148, 19, 92, 210, 241, 64, 70, 131, 56, 102, 221, 253, 48, 191, 6, 139, 98, 179, 37, 226, 152, 34, 136, 145, 16, 126, 110, 72, 195, 163, 182, 30, 66, 58, 107, 40, 84, 250, 133, 61, 186, 43, 121, 10, 21, 155, 159, 94, 202, 78, 212, 172, 229, 243, 115, 167, 87, 175, 88, 168, 80, 244, 234, 214, 116, 79, 174, 233, 213, 231, 230, 173, 232, 44, 215, 117, 122, 235, 22, 11, 245, 89, 203, 95, 176, 156, 169, 81, 160, 127, 12, 246, 111, 23, 196, 73, 236, 216, 67, 31, 45, 164, 118, 123, 183, 204, 187, 62, 90, 251, 96, 177, 134, 59, 82, 161, 108, 170, 85, 41, 157, 151, 178, 135, 144, 97, 190, 220, 252, 188, 149, 207, 205, 55, 63, 91, 209, 83, 57, 132, 60, 65, 162, 109, 71, 20, 42, 158, 93, 86, 242, 211, 171, 68, 17, 146, 217, 35, 32, 46, 137, 180, 124, 184, 38, 119, 153, 227, 165, 103, 74, 237, 222, 197, 49, 254, 24, 13, 99, 140, 128, 192, 247, 112, 7 }; private static readonly byte[] Alogtable = { 0, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1, }; private static readonly byte[] S = { 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22, }; private static readonly byte[] Si = { 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125, }; private static readonly byte[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; static readonly byte[][] shifts0 = new byte [][] { new byte[]{ 0, 8, 16, 24 }, new byte[]{ 0, 8, 16, 24 }, new byte[]{ 0, 8, 16, 24 }, new byte[]{ 0, 8, 16, 32 }, new byte[]{ 0, 8, 24, 32 } }; static readonly byte[][] shifts1 = { new byte[]{ 0, 24, 16, 8 }, new byte[]{ 0, 32, 24, 16 }, new byte[]{ 0, 40, 32, 24 }, new byte[]{ 0, 48, 40, 24 }, new byte[]{ 0, 56, 40, 32 } }; /** * multiply two elements of GF(2^m) * needed for MixColumn and InvMixColumn */ private byte Mul0x2( int b) { if (b != 0) { return Alogtable[25 + (Logtable[b] & 0xff)]; } else { return 0; } } private byte Mul0x3( int b) { if (b != 0) { return Alogtable[1 + (Logtable[b] & 0xff)]; } else { return 0; } } private byte Mul0x9( int b) { if (b >= 0) { return Alogtable[199 + b]; } else { return 0; } } private byte Mul0xb( int b) { if (b >= 0) { return Alogtable[104 + b]; } else { return 0; } } private byte Mul0xd( int b) { if (b >= 0) { return Alogtable[238 + b]; } else { return 0; } } private byte Mul0xe( int b) { if (b >= 0) { return Alogtable[223 + b]; } else { return 0; } } /** * xor corresponding text input and round key input bytes */ private void KeyAddition( long[] rk) { A0 ^= rk[0]; A1 ^= rk[1]; A2 ^= rk[2]; A3 ^= rk[3]; } private long Shift( long r, int shift) { //return (((long)((ulong) r >> shift) | (r << (BC - shift)))) & BC_MASK; ulong temp = (ulong) r >> shift; // NB: This corrects for Mono Bug #79087 (fixed in 1.1.17) if (shift > 31) { temp &= 0xFFFFFFFFUL; } return ((long) temp | (r << (BC - shift))) & BC_MASK; } /** * Row 0 remains unchanged * The other three rows are shifted a variable amount */ private void ShiftRow( byte[] shiftsSC) { A1 = Shift(A1, shiftsSC[1]); A2 = Shift(A2, shiftsSC[2]); A3 = Shift(A3, shiftsSC[3]); } private long ApplyS( long r, byte[] box) { long res = 0; for (int j = 0; j < BC; j += 8) { res |= (long)(box[(int)((r >> j) & 0xff)] & 0xff) << j; } return res; } /** * Replace every byte of the input by the byte at that place * in the nonlinear S-box */ private void Substitution( byte[] box) { A0 = ApplyS(A0, box); A1 = ApplyS(A1, box); A2 = ApplyS(A2, box); A3 = ApplyS(A3, box); } /** * Mix the bytes of every column in a linear way */ private void MixColumn() { long r0, r1, r2, r3; r0 = r1 = r2 = r3 = 0; for (int j = 0; j < BC; j += 8) { int a0 = (int)((A0 >> j) & 0xff); int a1 = (int)((A1 >> j) & 0xff); int a2 = (int)((A2 >> j) & 0xff); int a3 = (int)((A3 >> j) & 0xff); r0 |= (long)((Mul0x2(a0) ^ Mul0x3(a1) ^ a2 ^ a3) & 0xff) << j; r1 |= (long)((Mul0x2(a1) ^ Mul0x3(a2) ^ a3 ^ a0) & 0xff) << j; r2 |= (long)((Mul0x2(a2) ^ Mul0x3(a3) ^ a0 ^ a1) & 0xff) << j; r3 |= (long)((Mul0x2(a3) ^ Mul0x3(a0) ^ a1 ^ a2) & 0xff) << j; } A0 = r0; A1 = r1; A2 = r2; A3 = r3; } /** * Mix the bytes of every column in a linear way * This is the opposite operation of Mixcolumn */ private void InvMixColumn() { long r0, r1, r2, r3; r0 = r1 = r2 = r3 = 0; for (int j = 0; j < BC; j += 8) { int a0 = (int)((A0 >> j) & 0xff); int a1 = (int)((A1 >> j) & 0xff); int a2 = (int)((A2 >> j) & 0xff); int a3 = (int)((A3 >> j) & 0xff); // // pre-lookup the log table // a0 = (a0 != 0) ? (Logtable[a0 & 0xff] & 0xff) : -1; a1 = (a1 != 0) ? (Logtable[a1 & 0xff] & 0xff) : -1; a2 = (a2 != 0) ? (Logtable[a2 & 0xff] & 0xff) : -1; a3 = (a3 != 0) ? (Logtable[a3 & 0xff] & 0xff) : -1; r0 |= (long)((Mul0xe(a0) ^ Mul0xb(a1) ^ Mul0xd(a2) ^ Mul0x9(a3)) & 0xff) << j; r1 |= (long)((Mul0xe(a1) ^ Mul0xb(a2) ^ Mul0xd(a3) ^ Mul0x9(a0)) & 0xff) << j; r2 |= (long)((Mul0xe(a2) ^ Mul0xb(a3) ^ Mul0xd(a0) ^ Mul0x9(a1)) & 0xff) << j; r3 |= (long)((Mul0xe(a3) ^ Mul0xb(a0) ^ Mul0xd(a1) ^ Mul0x9(a2)) & 0xff) << j; } A0 = r0; A1 = r1; A2 = r2; A3 = r3; } /** * Calculate the necessary round keys * The number of calculations depends on keyBits and blockBits */ private long[][] GenerateWorkingKey( byte[] key) { int KC; int t, rconpointer = 0; int keyBits = key.Length * 8; byte[,] tk = new byte[4,MAXKC]; //long[,] W = new long[MAXROUNDS+1,4]; long[][] W = new long[MAXROUNDS+1][]; for (int i = 0; i < MAXROUNDS+1; i++) W[i] = new long[4]; switch (keyBits) { case 128: KC = 4; break; case 160: KC = 5; break; case 192: KC = 6; break; case 224: KC = 7; break; case 256: KC = 8; break; default : throw new ArgumentException("Key length not 128/160/192/224/256 bits."); } if (keyBits >= blockBits) { ROUNDS = KC + 6; } else { ROUNDS = (BC / 8) + 6; } // // copy the key into the processing area // int index = 0; for (int i = 0; i < key.Length; i++) { tk[i % 4,i / 4] = key[index++]; } t = 0; // // copy values into round key array // for (int j = 0; (j < KC) && (t < (ROUNDS+1)*(BC / 8)); j++, t++) { for (int i = 0; i < 4; i++) { W[t / (BC / 8)][i] |= (long)(tk[i,j] & 0xff) << ((t * 8) % BC); } } // // while not enough round key material calculated // calculate new values // while (t < (ROUNDS+1)*(BC/8)) { for (int i = 0; i < 4; i++) { tk[i,0] ^= S[tk[(i+1)%4,KC-1] & 0xff]; } tk[0,0] ^= (byte) rcon[rconpointer++]; if (KC <= 6) { for (int j = 1; j < KC; j++) { for (int i = 0; i < 4; i++) { tk[i,j] ^= tk[i,j-1]; } } } else { for (int j = 1; j < 4; j++) { for (int i = 0; i < 4; i++) { tk[i,j] ^= tk[i,j-1]; } } for (int i = 0; i < 4; i++) { tk[i,4] ^= S[tk[i,3] & 0xff]; } for (int j = 5; j < KC; j++) { for (int i = 0; i < 4; i++) { tk[i,j] ^= tk[i,j-1]; } } } // // copy values into round key array // for (int j = 0; (j < KC) && (t < (ROUNDS+1)*(BC/8)); j++, t++) { for (int i = 0; i < 4; i++) { W[t / (BC/8)][i] |= (long)(tk[i,j] & 0xff) << ((t * 8) % (BC)); } } } return W; } private int BC; private long BC_MASK; private int ROUNDS; private int blockBits; private long[][] workingKey; private long A0, A1, A2, A3; private bool forEncryption; private byte[] shifts0SC; private byte[] shifts1SC; /** * default constructor - 128 bit block size. */ public RijndaelEngine() : this(128) {} /** * basic constructor - set the cipher up for a given blocksize * * @param blocksize the blocksize in bits, must be 128, 192, or 256. */ public RijndaelEngine( int blockBits) { switch (blockBits) { case 128: BC = 32; BC_MASK = 0xffffffffL; shifts0SC = shifts0[0]; shifts1SC = shifts1[0]; break; case 160: BC = 40; BC_MASK = 0xffffffffffL; shifts0SC = shifts0[1]; shifts1SC = shifts1[1]; break; case 192: BC = 48; BC_MASK = 0xffffffffffffL; shifts0SC = shifts0[2]; shifts1SC = shifts1[2]; break; case 224: BC = 56; BC_MASK = 0xffffffffffffffL; shifts0SC = shifts0[3]; shifts1SC = shifts1[3]; break; case 256: BC = 64; BC_MASK = unchecked( (long)0xffffffffffffffffL); shifts0SC = shifts0[4]; shifts1SC = shifts1[4]; break; default: throw new ArgumentException("unknown blocksize to Rijndael"); } this.blockBits = blockBits; } /** * initialise a Rijndael cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (typeof(KeyParameter).IsInstanceOfType(parameters)) { workingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey()); this.forEncryption = forEncryption; return; } throw new ArgumentException("invalid parameter passed to Rijndael init - " + parameters.GetType().ToString()); } public string AlgorithmName { get { return "Rijndael"; } } public bool IsPartialBlockOkay { get { return false; } } public int GetBlockSize() { return BC / 2; } public int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) { throw new InvalidOperationException("Rijndael engine not initialised"); } if ((inOff + (BC / 2)) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + (BC / 2)) > output.Length) { throw new DataLengthException("output buffer too short"); } UnPackBlock(input, inOff); if (forEncryption) { EncryptBlock(workingKey); } else { DecryptBlock(workingKey); } PackBlock(output, outOff); return BC / 2; } public void Reset() { } private void UnPackBlock( byte[] bytes, int off) { int index = off; A0 = (long)(bytes[index++] & 0xff); A1 = (long)(bytes[index++] & 0xff); A2 = (long)(bytes[index++] & 0xff); A3 = (long)(bytes[index++] & 0xff); for (int j = 8; j != BC; j += 8) { A0 |= (long)(bytes[index++] & 0xff) << j; A1 |= (long)(bytes[index++] & 0xff) << j; A2 |= (long)(bytes[index++] & 0xff) << j; A3 |= (long)(bytes[index++] & 0xff) << j; } } private void PackBlock( byte[] bytes, int off) { int index = off; for (int j = 0; j != BC; j += 8) { bytes[index++] = (byte)(A0 >> j); bytes[index++] = (byte)(A1 >> j); bytes[index++] = (byte)(A2 >> j); bytes[index++] = (byte)(A3 >> j); } } private void EncryptBlock( long[][] rk) { int r; // // begin with a key addition // KeyAddition(rk[0]); // // ROUNDS-1 ordinary rounds // for (r = 1; r < ROUNDS; r++) { Substitution(S); ShiftRow(shifts0SC); MixColumn(); KeyAddition(rk[r]); } // // Last round is special: there is no MixColumn // Substitution(S); ShiftRow(shifts0SC); KeyAddition(rk[ROUNDS]); } private void DecryptBlock( long[][] rk) { int r; // To decrypt: apply the inverse operations of the encrypt routine, // in opposite order // // (KeyAddition is an involution: it 's equal to its inverse) // (the inverse of Substitution with table S is Substitution with the inverse table of S) // (the inverse of Shiftrow is Shiftrow over a suitable distance) // // First the special round: // without InvMixColumn // with extra KeyAddition // KeyAddition(rk[ROUNDS]); Substitution(Si); ShiftRow(shifts1SC); // // ROUNDS-1 ordinary rounds // for (r = ROUNDS-1; r > 0; r--) { KeyAddition(rk[r]); InvMixColumn(); Substitution(Si); ShiftRow(shifts1SC); } // // End with the extra key addition // KeyAddition(rk[0]); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Registry { using System; using System.Collections.Generic; using System.Security.AccessControl; using System.Text; /// <summary> /// A key within a registry hive. /// </summary> public sealed class RegistryKey { private RegistryHive _hive; private KeyNodeCell _cell; internal RegistryKey(RegistryHive hive, KeyNodeCell cell) { _hive = hive; _cell = cell; } /// <summary> /// Gets the name of this key. /// </summary> public string Name { get { RegistryKey parent = Parent; if (parent != null && ((parent.Flags & RegistryKeyFlags.Root) == 0)) { return parent.Name + @"\" + _cell.Name; } else { return _cell.Name; } } } /// <summary> /// Gets the number of child keys. /// </summary> public int SubKeyCount { get { return _cell.NumSubKeys; } } /// <summary> /// Gets the number of values in this key. /// </summary> public int ValueCount { get { return _cell.NumValues; } } /// <summary> /// Gets the time the key was last modified. /// </summary> public DateTime Timestamp { get { return _cell.Timestamp; } } /// <summary> /// Gets the parent key, or <c>null</c> if this is the root key. /// </summary> public RegistryKey Parent { get { if ((_cell.Flags & RegistryKeyFlags.Root) == 0) { return new RegistryKey(_hive, _hive.GetCell<KeyNodeCell>(_cell.ParentIndex)); } else { return null; } } } /// <summary> /// Gets the flags of this registry key. /// </summary> public RegistryKeyFlags Flags { get { return _cell.Flags; } } /// <summary> /// Gets the class name of this registry key. /// </summary> /// <remarks>Class name is rarely used.</remarks> public string ClassName { get { if (_cell.ClassNameIndex > 0) { return Encoding.Unicode.GetString(_hive.RawCellData(_cell.ClassNameIndex, _cell.ClassNameLength)); } return null; } } /// <summary> /// Gets an enumerator over all sub child keys. /// </summary> public IEnumerable<RegistryKey> SubKeys { get { if (_cell.NumSubKeys != 0) { ListCell list = _hive.GetCell<ListCell>(_cell.SubKeysIndex); foreach (var key in list.EnumerateKeys()) { yield return new RegistryKey(_hive, key); } } } } /// <summary> /// Gets an enumerator over all values in this key. /// </summary> private IEnumerable<RegistryValue> Values { get { if (_cell.NumValues != 0) { byte[] valueList = _hive.RawCellData(_cell.ValueListIndex, _cell.NumValues * 4); for (int i = 0; i < _cell.NumValues; ++i) { int valueIndex = Utilities.ToInt32LittleEndian(valueList, i * 4); yield return new RegistryValue(_hive, _hive.GetCell<ValueCell>(valueIndex)); } } } } /// <summary> /// Gets the Security Descriptor applied to the registry key. /// </summary> /// <returns>The security descriptor as a RegistrySecurity instance.</returns> public RegistrySecurity GetAccessControl() { if (_cell.SecurityIndex > 0) { SecurityCell secCell = _hive.GetCell<SecurityCell>(_cell.SecurityIndex); return secCell.SecurityDescriptor; } return null; } /// <summary> /// Gets the names of all child sub keys. /// </summary> /// <returns>The names of the sub keys.</returns> public string[] GetSubKeyNames() { List<string> names = new List<string>(); if (_cell.NumSubKeys != 0) { _hive.GetCell<ListCell>(_cell.SubKeysIndex).EnumerateKeys(names); } return names.ToArray(); } /// <summary> /// Gets a named value stored within this key. /// </summary> /// <param name="name">The name of the value to retrieve.</param> /// <returns>The value as a .NET object.</returns> /// <remarks>The mapping from registry type of .NET type is as follows: /// <list type="table"> /// <listheader> /// <term>Value Type</term> /// <term>.NET type</term> /// </listheader> /// <item> /// <description>String</description> /// <description>string</description> /// </item> /// <item> /// <description>ExpandString</description> /// <description>string</description> /// </item> /// <item> /// <description>Link</description> /// <description>string</description> /// </item> /// <item> /// <description>DWord</description> /// <description>uint</description> /// </item> /// <item> /// <description>DWordBigEndian</description> /// <description>uint</description> /// </item> /// <item> /// <description>MultiString</description> /// <description>string[]</description> /// </item> /// <item> /// <description>QWord</description> /// <description>ulong</description> /// </item> /// </list> /// </remarks> public object GetValue(string name) { return GetValue(name, null, Microsoft.Win32.RegistryValueOptions.None); } /// <summary> /// Gets a named value stored within this key. /// </summary> /// <param name="name">The name of the value to retrieve.</param> /// <param name="defaultValue">The default value to return, if no existing value is stored.</param> /// <returns>The value as a .NET object.</returns> /// <remarks>The mapping from registry type of .NET type is as follows: /// <list type="table"> /// <listheader> /// <term>Value Type</term> /// <term>.NET type</term> /// </listheader> /// <item> /// <description>String</description> /// <description>string</description> /// </item> /// <item> /// <description>ExpandString</description> /// <description>string</description> /// </item> /// <item> /// <description>Link</description> /// <description>string</description> /// </item> /// <item> /// <description>DWord</description> /// <description>uint</description> /// </item> /// <item> /// <description>DWordBigEndian</description> /// <description>uint</description> /// </item> /// <item> /// <description>MultiString</description> /// <description>string[]</description> /// </item> /// <item> /// <description>QWord</description> /// <description>ulong</description> /// </item> /// </list> /// </remarks> public object GetValue(string name, object defaultValue) { return GetValue(name, defaultValue, Microsoft.Win32.RegistryValueOptions.None); } /// <summary> /// Gets a named value stored within this key. /// </summary> /// <param name="name">The name of the value to retrieve.</param> /// <param name="defaultValue">The default value to return, if no existing value is stored.</param> /// <param name="options">Flags controlling how the value is processed before it's returned.</param> /// <returns>The value as a .NET object.</returns> /// <remarks>The mapping from registry type of .NET type is as follows: /// <list type="table"> /// <listheader> /// <term>Value Type</term> /// <term>.NET type</term> /// </listheader> /// <item> /// <description>String</description> /// <description>string</description> /// </item> /// <item> /// <description>ExpandString</description> /// <description>string</description> /// </item> /// <item> /// <description>Link</description> /// <description>string</description> /// </item> /// <item> /// <description>DWord</description> /// <description>uint</description> /// </item> /// <item> /// <description>DWordBigEndian</description> /// <description>uint</description> /// </item> /// <item> /// <description>MultiString</description> /// <description>string[]</description> /// </item> /// <item> /// <description>QWord</description> /// <description>ulong</description> /// </item> /// </list> /// </remarks> public object GetValue(string name, object defaultValue, Microsoft.Win32.RegistryValueOptions options) { RegistryValue regVal = GetRegistryValue(name); if (regVal != null) { if (regVal.DataType == RegistryValueType.ExpandString && (options & Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames) == 0) { return Environment.ExpandEnvironmentVariables((string)regVal.Value); } else { return regVal.Value; } } return defaultValue; } /// <summary> /// Sets a named value stored within this key. /// </summary> /// <param name="name">The name of the value to store.</param> /// <param name="value">The value to store.</param> public void SetValue(string name, object value) { SetValue(name, value, RegistryValueType.None); } /// <summary> /// Sets a named value stored within this key. /// </summary> /// <param name="name">The name of the value to store.</param> /// <param name="value">The value to store.</param> /// <param name="valueType">The registry type of the data.</param> public void SetValue(string name, object value, RegistryValueType valueType) { RegistryValue valObj = GetRegistryValue(name); if (valObj == null) { valObj = AddRegistryValue(name); } valObj.SetValue(value, valueType); } /// <summary> /// Deletes a named value stored within this key. /// </summary> /// <param name="name">The name of the value to delete.</param> public void DeleteValue(string name) { DeleteValue(name, true); } /// <summary> /// Deletes a named value stored within this key. /// </summary> /// <param name="name">The name of the value to delete.</param> /// <param name="throwOnMissingValue">Throws ArgumentException if <c>name</c> doesn't exist.</param> public void DeleteValue(string name, bool throwOnMissingValue) { bool foundValue = false; if (_cell.NumValues != 0) { byte[] valueList = _hive.RawCellData(_cell.ValueListIndex, _cell.NumValues * 4); int i = 0; while (i < _cell.NumValues) { int valueIndex = Utilities.ToInt32LittleEndian(valueList, i * 4); ValueCell valueCell = _hive.GetCell<ValueCell>(valueIndex); if (string.Compare(valueCell.Name, name, StringComparison.OrdinalIgnoreCase) == 0) { foundValue = true; _hive.FreeCell(valueIndex); _cell.NumValues--; _hive.UpdateCell(_cell, false); break; } ++i; } // Move following value's to fill gap if (i < _cell.NumValues) { while (i < _cell.NumValues) { int valueIndex = Utilities.ToInt32LittleEndian(valueList, (i + 1) * 4); Utilities.WriteBytesLittleEndian(valueIndex, valueList, i * 4); ++i; } _hive.WriteRawCellData(_cell.ValueListIndex, valueList, 0, _cell.NumValues * 4); } // TODO: Update maxbytes for value name and value content if this was the largest value for either. // Windows seems to repair this info, if not accurate, though. } if (throwOnMissingValue && !foundValue) { throw new ArgumentException("No such value: " + name, "name"); } } /// <summary> /// Gets the type of a named value. /// </summary> /// <param name="name">The name of the value to inspect.</param> /// <returns>The value's type.</returns> public RegistryValueType GetValueType(string name) { RegistryValue regVal = GetRegistryValue(name); if (regVal != null) { return regVal.DataType; } return RegistryValueType.None; } /// <summary> /// Gets the names of all values in this key. /// </summary> /// <returns>An array of strings containing the value names.</returns> public string[] GetValueNames() { List<string> names = new List<string>(); foreach (var value in Values) { names.Add(value.Name); } return names.ToArray(); } /// <summary> /// Creates or opens a subkey. /// </summary> /// <param name="subkey">The relative path the the subkey.</param> /// <returns>The subkey.</returns> public RegistryKey CreateSubKey(string subkey) { if (string.IsNullOrEmpty(subkey)) { return this; } string[] split = subkey.Split(new char[] { '\\' }, 2); int cellIndex = FindSubKeyCell(split[0]); if (cellIndex < 0) { KeyNodeCell newKeyCell = new KeyNodeCell(split[0], _cell.Index); newKeyCell.SecurityIndex = _cell.SecurityIndex; ReferenceSecurityCell(newKeyCell.SecurityIndex); _hive.UpdateCell(newKeyCell, true); LinkSubKey(split[0], newKeyCell.Index); if (split.Length == 1) { return new RegistryKey(_hive, newKeyCell); } else { return new RegistryKey(_hive, newKeyCell).CreateSubKey(split[1]); } } else { KeyNodeCell cell = _hive.GetCell<KeyNodeCell>(cellIndex); if (split.Length == 1) { return new RegistryKey(_hive, cell); } else { return new RegistryKey(_hive, cell).CreateSubKey(split[1]); } } } /// <summary> /// Opens a sub key. /// </summary> /// <param name="path">The relative path to the sub key.</param> /// <returns>The sub key, or <c>null</c> if not found.</returns> public RegistryKey OpenSubKey(string path) { if (string.IsNullOrEmpty(path)) { return this; } string[] split = path.Split(new char[] { '\\' }, 2); int cellIndex = FindSubKeyCell(split[0]); if (cellIndex < 0) { return null; } else { KeyNodeCell cell = _hive.GetCell<KeyNodeCell>(cellIndex); if (split.Length == 1) { return new RegistryKey(_hive, cell); } else { return new RegistryKey(_hive, cell).OpenSubKey(split[1]); } } } /// <summary> /// Deletes a subkey and any child subkeys recursively. The string subkey is not case-sensitive. /// </summary> /// <param name="subkey">The subkey to delete.</param> public void DeleteSubKeyTree(string subkey) { RegistryKey subKeyObj = OpenSubKey(subkey); if (subKeyObj == null) { return; } if ((subKeyObj.Flags & RegistryKeyFlags.Root) != 0) { throw new ArgumentException("Attempt to delete root key"); } foreach (var child in subKeyObj.GetSubKeyNames()) { subKeyObj.DeleteSubKeyTree(child); } DeleteSubKey(subkey); } /// <summary> /// Deletes the specified subkey. The string subkey is not case-sensitive. /// </summary> /// <param name="subkey">The subkey to delete.</param> public void DeleteSubKey(string subkey) { DeleteSubKey(subkey, true); } /// <summary> /// Deletes the specified subkey. The string subkey is not case-sensitive. /// </summary> /// <param name="subkey">The subkey to delete.</param> /// <param name="throwOnMissingSubKey"><c>true</c> to throw an argument exception if <c>subkey</c> doesn't exist.</param> public void DeleteSubKey(string subkey, bool throwOnMissingSubKey) { if (string.IsNullOrEmpty(subkey)) { throw new ArgumentException("Invalid SubKey", "subkey"); } string[] split = subkey.Split(new char[] { '\\' }, 2); int subkeyCellIndex = FindSubKeyCell(split[0]); if (subkeyCellIndex < 0) { if (throwOnMissingSubKey) { throw new ArgumentException("No such SubKey", "subkey"); } else { return; } } KeyNodeCell subkeyCell = _hive.GetCell<KeyNodeCell>(subkeyCellIndex); if (split.Length == 1) { if (subkeyCell.NumSubKeys != 0) { throw new InvalidOperationException("The registry key has subkeys"); } if (subkeyCell.ClassNameIndex != -1) { _hive.FreeCell(subkeyCell.ClassNameIndex); subkeyCell.ClassNameIndex = -1; subkeyCell.ClassNameLength = 0; } if (subkeyCell.SecurityIndex != -1) { DereferenceSecurityCell(subkeyCell.SecurityIndex); subkeyCell.SecurityIndex = -1; } if (subkeyCell.SubKeysIndex != -1) { FreeSubKeys(subkeyCell); } if (subkeyCell.ValueListIndex != -1) { FreeValues(subkeyCell); } UnlinkSubKey(subkey); _hive.FreeCell(subkeyCellIndex); _hive.UpdateCell(_cell, false); } else { new RegistryKey(_hive, subkeyCell).DeleteSubKey(split[1], throwOnMissingSubKey); } } private RegistryValue GetRegistryValue(string name) { if (name != null && name.Length == 0) { name = null; } if (_cell.NumValues != 0) { byte[] valueList = _hive.RawCellData(_cell.ValueListIndex, _cell.NumValues * 4); for (int i = 0; i < _cell.NumValues; ++i) { int valueIndex = Utilities.ToInt32LittleEndian(valueList, i * 4); ValueCell cell = _hive.GetCell<ValueCell>(valueIndex); if (string.Compare(cell.Name, name, StringComparison.OrdinalIgnoreCase) == 0) { return new RegistryValue(_hive, cell); } } } return null; } private RegistryValue AddRegistryValue(string name) { byte[] valueList = _hive.RawCellData(_cell.ValueListIndex, _cell.NumValues * 4); if (valueList == null) { valueList = new byte[0]; } int insertIdx = 0; while (insertIdx < _cell.NumValues) { int valueCellIndex = Utilities.ToInt32LittleEndian(valueList, insertIdx * 4); ValueCell cell = _hive.GetCell<ValueCell>(valueCellIndex); if (string.Compare(name, cell.Name, StringComparison.OrdinalIgnoreCase) < 0) { break; } ++insertIdx; } // Allocate a new value cell (note _hive.UpdateCell does actual allocation). ValueCell valueCell = new ValueCell(name); _hive.UpdateCell(valueCell, true); // Update the value list, re-allocating if necessary byte[] newValueList = new byte[(_cell.NumValues * 4) + 4]; Array.Copy(valueList, 0, newValueList, 0, insertIdx * 4); Utilities.WriteBytesLittleEndian(valueCell.Index, newValueList, insertIdx * 4); Array.Copy(valueList, insertIdx * 4, newValueList, (insertIdx * 4) + 4, (_cell.NumValues - insertIdx) * 4); if (_cell.ValueListIndex == -1 || !_hive.WriteRawCellData(_cell.ValueListIndex, newValueList, 0, newValueList.Length)) { int newListCellIndex = _hive.AllocateRawCell(Utilities.RoundUp(newValueList.Length, 8)); _hive.WriteRawCellData(newListCellIndex, newValueList, 0, newValueList.Length); if (_cell.ValueListIndex != -1) { _hive.FreeCell(_cell.ValueListIndex); } _cell.ValueListIndex = newListCellIndex; } // Record the new value and save this cell _cell.NumValues++; _hive.UpdateCell(_cell, false); // Finally, set the data in the value cell return new RegistryValue(_hive, valueCell); } private int FindSubKeyCell(string name) { if (_cell.NumSubKeys != 0) { ListCell listCell = _hive.GetCell<ListCell>(_cell.SubKeysIndex); int cellIndex; if (listCell.FindKey(name, out cellIndex) == 0) { return cellIndex; } } return -1; } private void LinkSubKey(string name, int cellIndex) { if (_cell.SubKeysIndex == -1) { SubKeyHashedListCell newListCell = new SubKeyHashedListCell(_hive, "lf"); newListCell.Add(name, cellIndex); _hive.UpdateCell(newListCell, true); _cell.NumSubKeys = 1; _cell.SubKeysIndex = newListCell.Index; } else { ListCell list = _hive.GetCell<ListCell>(_cell.SubKeysIndex); _cell.SubKeysIndex = list.LinkSubKey(name, cellIndex); _cell.NumSubKeys++; } _hive.UpdateCell(_cell, false); } private void UnlinkSubKey(string name) { if (_cell.SubKeysIndex == -1 || _cell.NumSubKeys == 0) { throw new InvalidOperationException("No subkey list"); } ListCell list = _hive.GetCell<ListCell>(_cell.SubKeysIndex); _cell.SubKeysIndex = list.UnlinkSubKey(name); _cell.NumSubKeys--; } private void ReferenceSecurityCell(int cellIndex) { SecurityCell sc = _hive.GetCell<SecurityCell>(cellIndex); sc.UsageCount++; _hive.UpdateCell(sc, false); } private void DereferenceSecurityCell(int cellIndex) { SecurityCell sc = _hive.GetCell<SecurityCell>(cellIndex); sc.UsageCount--; if (sc.UsageCount == 0) { SecurityCell prev = _hive.GetCell<SecurityCell>(sc.PreviousIndex); prev.NextIndex = sc.NextIndex; _hive.UpdateCell(prev, false); SecurityCell next = _hive.GetCell<SecurityCell>(sc.NextIndex); next.PreviousIndex = sc.PreviousIndex; _hive.UpdateCell(next, false); _hive.FreeCell(cellIndex); } else { _hive.UpdateCell(sc, false); } } private void FreeValues(KeyNodeCell cell) { if (cell.NumValues != 0 && cell.ValueListIndex != -1) { byte[] valueList = _hive.RawCellData(cell.ValueListIndex, cell.NumValues * 4); for (int i = 0; i < cell.NumValues; ++i) { int valueIndex = Utilities.ToInt32LittleEndian(valueList, i * 4); _hive.FreeCell(valueIndex); } _hive.FreeCell(cell.ValueListIndex); cell.ValueListIndex = -1; cell.NumValues = 0; cell.MaxValDataBytes = 0; cell.MaxValNameBytes = 0; } } private void FreeSubKeys(KeyNodeCell subkeyCell) { if (subkeyCell.SubKeysIndex == -1) { throw new InvalidOperationException("No subkey list"); } Cell list = _hive.GetCell<Cell>(subkeyCell.SubKeysIndex); SubKeyIndirectListCell indirectList = list as SubKeyIndirectListCell; if (indirectList != null) { ////foreach (int listIndex in indirectList.CellIndexes) for (int i = 0; i < indirectList.CellIndexes.Count; ++i) { int listIndex = indirectList.CellIndexes[i]; _hive.FreeCell(listIndex); } } _hive.FreeCell(list.Index); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Xunit.Performance; using System; using System.Linq; using System.Runtime.CompilerServices; using System.Reflection; using System.Collections.Generic; using Xunit; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] namespace Inlining { public static class ConstantArgsLong { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 100000; #endif // Longs feeding math operations. // // Inlining in Bench0xp should enable constant folding // Inlining in Bench0xn will not enable constant folding static long Five = 5; static long Ten = 10; static long Id(long x) { return x; } static long F00(long x) { return x * x; } static bool Bench00p() { long t = 10; long f = F00(t); return (f == 100); } static bool Bench00n() { long t = Ten; long f = F00(t); return (f == 100); } static bool Bench00p1() { long t = Id(10); long f = F00(t); return (f == 100); } static bool Bench00n1() { long t = Id(Ten); long f = F00(t); return (f == 100); } static bool Bench00p2() { long t = Id(10); long f = F00(Id(t)); return (f == 100); } static bool Bench00n2() { long t = Id(Ten); long f = F00(Id(t)); return (f == 100); } static bool Bench00p3() { long t = 10; long f = F00(Id(Id(t))); return (f == 100); } static bool Bench00n3() { long t = Ten; long f = F00(Id(Id(t))); return (f == 100); } static bool Bench00p4() { long t = 5; long f = F00(2 * t); return (f == 100); } static bool Bench00n4() { long t = Five; long f = F00(2 * t); return (f == 100); } static long F01(long x) { return 1000 / x; } static bool Bench01p() { long t = 10; long f = F01(t); return (f == 100); } static bool Bench01n() { long t = Ten; long f = F01(t); return (f == 100); } static long F02(long x) { return 20 * (x / 2); } static bool Bench02p() { long t = 10; long f = F02(t); return (f == 100); } static bool Bench02n() { long t = Ten; long f = F02(t); return (f == 100); } static long F03(long x) { return 91 + 1009 % x; } static bool Bench03p() { long t = 10; long f = F03(t); return (f == 100); } static bool Bench03n() { long t = Ten; long f = F03(t); return (f == 100); } static long F04(long x) { return 50 * (x % 4); } static bool Bench04p() { long t = 10; long f = F04(t); return (f == 100); } static bool Bench04n() { long t = Ten; long f = F04(t); return (f == 100); } static long F05(long x) { return (1 << (int) x) - 924; } static bool Bench05p() { long t = 10; long f = F05(t); return (f == 100); } static bool Bench05n() { long t = Ten; long f = F05(t); return (f == 100); } static long F051(long x) { return (102400 >> (int) x); } static bool Bench05p1() { long t = 10; long f = F051(t); return (f == 100); } static bool Bench05n1() { long t = Ten; long f = F051(t); return (f == 100); } static long F06(long x) { return -x + 110; } static bool Bench06p() { long t = 10; long f = F06(t); return (f == 100); } static bool Bench06n() { long t = Ten; long f = F06(t); return (f == 100); } static long F07(long x) { return ~x + 111; } static bool Bench07p() { long t = 10; long f = F07(t); return (f == 100); } static bool Bench07n() { long t = Ten; long f = F07(t); return (f == 100); } static long F071(long x) { return (x ^ -1) + 111; } static bool Bench07p1() { long t = 10; long f = F071(t); return (f == 100); } static bool Bench07n1() { long t = Ten; long f = F071(t); return (f == 100); } static long F08(long x) { return (x & 0x7) + 98; } static bool Bench08p() { long t = 10; long f = F08(t); return (f == 100); } static bool Bench08n() { long t = Ten; long f = F08(t); return (f == 100); } static long F09(long x) { return (x | 0x7) + 85; } static bool Bench09p() { long t = 10; long f = F09(t); return (f == 100); } static bool Bench09n() { long t = Ten; long f = F09(t); return (f == 100); } // Longs feeding comparisons. // // Inlining in Bench1xp should enable branch optimization // Inlining in Bench1xn will not enable branch optimization static long F10(long x) { return x == 10 ? 100 : 0; } static bool Bench10p() { long t = 10; long f = F10(t); return (f == 100); } static bool Bench10n() { long t = Ten; long f = F10(t); return (f == 100); } static long F101(long x) { return x != 10 ? 0 : 100; } static bool Bench10p1() { long t = 10; long f = F101(t); return (f == 100); } static bool Bench10n1() { long t = Ten; long f = F101(t); return (f == 100); } static long F102(long x) { return x >= 10 ? 100 : 0; } static bool Bench10p2() { long t = 10; long f = F102(t); return (f == 100); } static bool Bench10n2() { long t = Ten; long f = F102(t); return (f == 100); } static long F103(long x) { return x <= 10 ? 100 : 0; } static bool Bench10p3() { long t = 10; long f = F103(t); return (f == 100); } static bool Bench10n3() { long t = Ten; long f = F102(t); return (f == 100); } static long F11(long x) { if (x == 10) { return 100; } else { return 0; } } static bool Bench11p() { long t = 10; long f = F11(t); return (f == 100); } static bool Bench11n() { long t = Ten; long f = F11(t); return (f == 100); } static long F111(long x) { if (x != 10) { return 0; } else { return 100; } } static bool Bench11p1() { long t = 10; long f = F111(t); return (f == 100); } static bool Bench11n1() { long t = Ten; long f = F111(t); return (f == 100); } static long F112(long x) { if (x > 10) { return 0; } else { return 100; } } static bool Bench11p2() { long t = 10; long f = F112(t); return (f == 100); } static bool Bench11n2() { long t = Ten; long f = F112(t); return (f == 100); } static long F113(long x) { if (x < 10) { return 0; } else { return 100; } } static bool Bench11p3() { long t = 10; long f = F113(t); return (f == 100); } static bool Bench11n3() { long t = Ten; long f = F113(t); return (f == 100); } // Ununsed (or effectively unused) parameters // // Simple callee analysis may overstate inline benefit static long F20(long x) { return 100; } static bool Bench20p() { long t = 10; long f = F20(t); return (f == 100); } static bool Bench20p1() { long t = Ten; long f = F20(t); return (f == 100); } static long F21(long x) { return -x + 100 + x; } static bool Bench21p() { long t = 10; long f = F21(t); return (f == 100); } static bool Bench21n() { long t = Ten; long f = F21(t); return (f == 100); } static long F211(long x) { return x - x + 100; } static bool Bench21p1() { long t = 10; long f = F211(t); return (f == 100); } static bool Bench21n1() { long t = Ten; long f = F211(t); return (f == 100); } static long F22(long x) { if (x > 0) { return 100; } return 100; } static bool Bench22p() { long t = 10; long f = F22(t); return (f == 100); } static bool Bench22p1() { long t = Ten; long f = F22(t); return (f == 100); } static long F23(long x) { if (x > 0) { return 90 + x; } return 100; } static bool Bench23p() { long t = 10; long f = F23(t); return (f == 100); } static bool Bench23n() { long t = Ten; long f = F23(t); return (f == 100); } // Multiple parameters static long F30(long x, long y) { return y * y; } static bool Bench30p() { long t = 10; long f = F30(t, t); return (f == 100); } static bool Bench30n() { long t = Ten; long f = F30(t, t); return (f == 100); } static bool Bench30p1() { long s = Ten; long t = 10; long f = F30(s, t); return (f == 100); } static bool Bench30n1() { long s = 10; long t = Ten; long f = F30(s, t); return (f == 100); } static bool Bench30p2() { long s = 10; long t = 10; long f = F30(s, t); return (f == 100); } static bool Bench30n2() { long s = Ten; long t = Ten; long f = F30(s, t); return (f == 100); } static bool Bench30p3() { long s = 10; long t = s; long f = F30(s, t); return (f == 100); } static bool Bench30n3() { long s = Ten; long t = s; long f = F30(s, t); return (f == 100); } static long F31(long x, long y, long z) { return z * z; } static bool Bench31p() { long t = 10; long f = F31(t, t, t); return (f == 100); } static bool Bench31n() { long t = Ten; long f = F31(t, t, t); return (f == 100); } static bool Bench31p1() { long r = Ten; long s = Ten; long t = 10; long f = F31(r, s, t); return (f == 100); } static bool Bench31n1() { long r = 10; long s = 10; long t = Ten; long f = F31(r, s, t); return (f == 100); } static bool Bench31p2() { long r = 10; long s = 10; long t = 10; long f = F31(r, s, t); return (f == 100); } static bool Bench31n2() { long r = Ten; long s = Ten; long t = Ten; long f = F31(r, s, t); return (f == 100); } static bool Bench31p3() { long r = 10; long s = r; long t = s; long f = F31(r, s, t); return (f == 100); } static bool Bench31n3() { long r = Ten; long s = r; long t = s; long f = F31(r, s, t); return (f == 100); } // Two args, both used static long F40(long x, long y) { return x * x + y * y - 100; } static bool Bench40p() { long t = 10; long f = F40(t, t); return (f == 100); } static bool Bench40n() { long t = Ten; long f = F40(t, t); return (f == 100); } static bool Bench40p1() { long s = Ten; long t = 10; long f = F40(s, t); return (f == 100); } static bool Bench40p2() { long s = 10; long t = Ten; long f = F40(s, t); return (f == 100); } static long F41(long x, long y) { return x * y; } static bool Bench41p() { long t = 10; long f = F41(t, t); return (f == 100); } static bool Bench41n() { long t = Ten; long f = F41(t, t); return (f == 100); } static bool Bench41p1() { long s = 10; long t = Ten; long f = F41(s, t); return (f == 100); } static bool Bench41p2() { long s = Ten; long t = 10; long f = F41(s, t); return (f == 100); } private static IEnumerable<object[]> MakeArgs(params string[] args) { return args.Select(arg => new object[] { arg }); } public static IEnumerable<object[]> TestFuncs = MakeArgs( "Bench00p", "Bench00n", "Bench00p1", "Bench00n1", "Bench00p2", "Bench00n2", "Bench00p3", "Bench00n3", "Bench00p4", "Bench00n4", "Bench01p", "Bench01n", "Bench02p", "Bench02n", "Bench03p", "Bench03n", "Bench04p", "Bench04n", "Bench05p", "Bench05n", "Bench05p1", "Bench05n1", "Bench06p", "Bench06n", "Bench07p", "Bench07n", "Bench07p1", "Bench07n1", "Bench08p", "Bench08n", "Bench09p", "Bench09n", "Bench10p", "Bench10n", "Bench10p1", "Bench10n1", "Bench10p2", "Bench10n2", "Bench10p3", "Bench10n3", "Bench11p", "Bench11n", "Bench11p1", "Bench11n1", "Bench11p2", "Bench11n2", "Bench11p3", "Bench11n3", "Bench20p", "Bench20p1", "Bench21p", "Bench21n", "Bench21p1", "Bench21n1", "Bench22p", "Bench22p1", "Bench23p", "Bench23n", "Bench30p", "Bench30n", "Bench30p1", "Bench30n1", "Bench30p2", "Bench30n2", "Bench30p3", "Bench30n3", "Bench31p", "Bench31n", "Bench31p1", "Bench31n1", "Bench31p2", "Bench31n2", "Bench31p3", "Bench31n3", "Bench40p", "Bench40n", "Bench40p1", "Bench40p2", "Bench41p", "Bench41n", "Bench41p1", "Bench41p2" ); static Func<bool> LookupFunc(object o) { TypeInfo t = typeof(ConstantArgsLong).GetTypeInfo(); MethodInfo m = t.GetDeclaredMethod((string) o); return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>; } [Benchmark] [MemberData(nameof(TestFuncs))] public static void Test(object funcName) { Func<bool> f = LookupFunc(funcName); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Iterations; i++) { f(); } } } } static bool TestBase(Func<bool> f) { bool result = true; for (int i = 0; i < Iterations; i++) { result &= f(); } return result; } public static int Main() { bool result = true; foreach(object[] o in TestFuncs) { string funcName = (string) o[0]; Func<bool> func = LookupFunc(funcName); bool thisResult = TestBase(func); if (!thisResult) { Console.WriteLine("{0} failed", funcName); } result &= thisResult; } return (result ? 100 : -1); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core.Pipeline; using Azure.Identity; using NUnit.Framework; using System; using System.Threading; using System.Threading.Tasks; using System.Net.Http; namespace Azure.Security.KeyVault.Secrets.Samples { /// <summary> /// Samples that are used in the associated README.md file. /// </summary> public partial class Snippets { #pragma warning disable IDE1006 // Naming Styles private SecretClient client; #pragma warning restore IDE1006 // Naming Styles [OneTimeSetUp] public void CreateClient() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = TestEnvironment.KeyVaultUrl; #region Snippet:CreateSecretClient // Create a new secret client using the default credential from Azure.Identity using environment variables previously set, // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID. var client = new SecretClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential()); // Create a new secret using the secret client. KeyVaultSecret secret = client.SetSecret("secret-name", "secret-value"); // Retrieve a secret using the secret client. secret = client.GetSecret("secret-name"); #endregion this.client = client; } [Test] public void CreateSecret() { #region Snippet:CreateSecret KeyVaultSecret secret = client.SetSecret("secret-name", "secret-value"); Console.WriteLine(secret.Name); Console.WriteLine(secret.Value); Console.WriteLine(secret.Properties.Version); Console.WriteLine(secret.Properties.Enabled); #endregion } [Test] public async Task CreateSecretAsync() { #region Snippet:CreateSecretAsync KeyVaultSecret secret = await client.SetSecretAsync("secret-name", "secret-value"); Console.WriteLine(secret.Name); Console.WriteLine(secret.Value); #endregion } [Test] public void RetrieveSecret() { // Make sure a secret exists. This will create a new version if "secret-name" already exists. client.SetSecret("secret-name", "secret-value"); #region Snippet:RetrieveSecret KeyVaultSecret secret = client.GetSecret("secret-name"); Console.WriteLine(secret.Name); Console.WriteLine(secret.Value); #endregion } [Test] public void UpdateSecret() { // Make sure a secret exists. This will create a new version if "secret-name" already exists. client.SetSecret("secret-name", "secret-value"); #region Snippet:UpdateSecret KeyVaultSecret secret = client.GetSecret("secret-name"); // Clients may specify the content type of a secret to assist in interpreting the secret data when its retrieved. secret.Properties.ContentType = "text/plain"; // You can specify additional application-specific metadata in the form of tags. secret.Properties.Tags["foo"] = "updated tag"; SecretProperties updatedSecretProperties = client.UpdateSecretProperties(secret.Properties); Console.WriteLine(updatedSecretProperties.Name); Console.WriteLine(updatedSecretProperties.Version); Console.WriteLine(updatedSecretProperties.ContentType); #endregion } [Test] public void ListSecrets() { #region Snippet:ListSecrets Pageable<SecretProperties> allSecrets = client.GetPropertiesOfSecrets(); foreach (SecretProperties secretProperties in allSecrets) { Console.WriteLine(secretProperties.Name); } #endregion } [Test] public async Task ListSecretsAsync() { #region Snippet:ListSecretsAsync AsyncPageable<SecretProperties> allSecrets = client.GetPropertiesOfSecretsAsync(); await foreach (SecretProperties secretProperties in allSecrets) { Console.WriteLine(secretProperties.Name); } #endregion } [Test] public void NotFound() { #region Snippet:SecretNotFound try { KeyVaultSecret secret = client.GetSecret("some_secret"); } catch (RequestFailedException ex) { Console.WriteLine(ex.ToString()); } #endregion } [Ignore("The secret is deleted and purged on tear down of this text fixture.")] public void DeleteSecret() { #region Snippet:DeleteSecret DeleteSecretOperation operation = client.StartDeleteSecret("secret-name"); DeletedSecret secret = operation.Value; Console.WriteLine(secret.Name); Console.WriteLine(secret.Value); #endregion } [OneTimeTearDown] public async Task DeleteAndPurgeSecretAsync() { #region Snippet:DeleteAndPurgeSecretAsync DeleteSecretOperation operation = await client.StartDeleteSecretAsync("secret-name"); // You only need to wait for completion if you want to purge or recover the secret. await operation.WaitForCompletionAsync(); DeletedSecret secret = operation.Value; await client.PurgeDeletedSecretAsync(secret.Name); #endregion } [Ignore("The secret is deleted and purged on tear down of this text fixture.")] public void DeleteAndPurgeSecret() { #region Snippet:DeleteAndPurgeSecret DeleteSecretOperation operation = client.StartDeleteSecret("secret-name"); // You only need to wait for completion if you want to purge or recover the secret. // You should call `UpdateStatus` in another thread or after doing additional work like pumping messages. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } DeletedSecret secret = operation.Value; client.PurgeDeletedSecret(secret.Name); #endregion } [Ignore("Used only for the migration guide")] private async Task MigrationGuide() { #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_Create SecretClient client = new SecretClient( new Uri("https://myvault.vault.azure.net"), new DefaultAzureCredential()); #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_Create #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_CreateWithOptions using (HttpClient httpClient = new HttpClient()) { SecretClientOptions options = new SecretClientOptions { Transport = new HttpClientTransport(httpClient) }; //@@SecretClient client = new SecretClient( /*@@*/ SecretClient _ = new SecretClient( new Uri("https://myvault.vault.azure.net"), new DefaultAzureCredential(), options); } #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_CreateWithOptions { #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_SetSecret KeyVaultSecret secret = await client.SetSecretAsync("secret-name", "secret-value"); #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_SetSecret } { #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_GetSecret // Get the latest secret value. KeyVaultSecret secret = await client.GetSecretAsync("secret-name"); // Get a specific secret value. KeyVaultSecret secretVersion = await client.GetSecretAsync("secret-name", "e43af03a7cbc47d4a4e9f11540186048"); #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_GetSecret } { #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_ListSecrets // List all secrets asynchronously. await foreach (SecretProperties item in client.GetPropertiesOfSecretsAsync()) { KeyVaultSecret secret = await client.GetSecretAsync(item.Name); } // List all secrets synchronously. foreach (SecretProperties item in client.GetPropertiesOfSecrets()) { KeyVaultSecret secret = client.GetSecret(item.Name); } #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_ListSecrets } { #region Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_DeleteSecret // Delete the secret. DeleteSecretOperation deleteOperation = await client.StartDeleteSecretAsync("secret-name"); // Purge or recover the deleted secret if soft delete is enabled. if (deleteOperation.Value.RecoveryId != null) { // Deleting a secret does not happen immediately. Wait for the secret to be deleted. DeletedSecret deletedSecret = await deleteOperation.WaitForCompletionAsync(); // Purge the deleted secret. await client.PurgeDeletedSecretAsync(deletedSecret.Name); // You can also recover the deleted secret using StartRecoverDeletedSecretAsync, // which returns RecoverDeletedSecretOperation you can await like DeleteSecretOperation above. } #endregion Snippet:Azure_Security_KeyVault_Secrets_Snippets_MigrationGuide_DeleteSecret } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Rhino.DistributedHashTable.Client; using Rhino.DistributedHashTable.Exceptions; using Rhino.DistributedHashTable.Hosting; using Rhino.DistributedHashTable.Internal; using Rhino.DistributedHashTable.Parameters; using Rhino.PersistentHashTable; using Xunit; namespace Rhino.DistributedHashTable.ClusterTests { public class ClusterTests { // we have to do this ugliness because the cluster is in a state of flux right now // with segments moving & topology changes public static void RepeatWhileThereAreTopologyChangedErrors(Action action) { for (int i = 0; i < 10; i++) { try { action(); return; } catch (TopologyVersionDoesNotMatchException) { Thread.Sleep(250); } } throw new InvalidOperationException( "Could not execute action because we got too many TopologyVersionDoesNotMatchException"); } #region Nested type: JoiningToCluster public class JoiningToCluster : FullIntegrationTest, IDisposable { private readonly DistributedHashTableMasterHost masterHost; private readonly Uri masterUri = new Uri("rhino.dht://" + Environment.MachineName + ":2200/master"); private readonly DistributedHashTableStorageHost storageHostA; private readonly DistributedHashTableStorageHost storageHostB; public JoiningToCluster() { masterHost = new DistributedHashTableMasterHost(); storageHostA = new DistributedHashTableStorageHost(masterUri); storageHostB = new DistributedHashTableStorageHost(masterUri, "nodeB", 2203); masterHost.Start(); storageHostA.Start(); } #region IDisposable Members public void Dispose() { storageHostB.Dispose(); storageHostA.Dispose(); masterHost.Dispose(); } #endregion [Fact] public void AfterBothNodesJoinedWillAutomaticallyReplicateToBackupNode() { storageHostB.Start(); var masterProxy = new DistributedHashTableMasterClient(masterUri); Topology topology; for (int i = 0; i < 50; i++) { topology = masterProxy.GetTopology(); int count = topology.Segments .Where(x => x.AssignedEndpoint == storageHostA.Endpoint) .Count(); if (count == 4096) break; Thread.Sleep(500); } topology = masterProxy.GetTopology(); int segment = topology.Segments.First(x => x.AssignedEndpoint == storageHostA.Endpoint).Index; RepeatWhileThereAreTopologyChangedErrors(() => { using (var nodeA = new DistributedHashTableStorageClient(storageHostA.Endpoint)) { nodeA.Put(topology.Version, new ExtendedPutRequest { Bytes = new byte[] {2, 2, 0, 0}, Key = "abc", Segment = segment }); } }); RepeatWhileThereAreTopologyChangedErrors(() => { using (var nodeB = new DistributedHashTableStorageClient(storageHostB.Endpoint)) { topology = masterProxy.GetTopology(); Value[][] values = null; for (int i = 0; i < 100; i++) { values = nodeB.Get(topology.Version, new ExtendedGetRequest { Key = "abc", Segment = segment }); if (values[0].Length != 0) break; Thread.Sleep(250); } Assert.Equal(new byte[] {2, 2, 0, 0}, values[0][0].Data); } }); } [Fact] public void CanReadValueFromBackupNodeThatUsedToBeTheSegmentOwner() { storageHostB.Start(); var masterProxy = new DistributedHashTableMasterClient(masterUri); Topology topology; for (int i = 0; i < 50; i++) { topology = masterProxy.GetTopology(); int count = topology.Segments .Where(x => x.AssignedEndpoint == storageHostA.Endpoint) .Count(); if (count == 4096) break; Thread.Sleep(500); } int segment = 0; RepeatWhileThereAreTopologyChangedErrors(() => { topology = masterProxy.GetTopology(); segment = topology.Segments.First(x => x.AssignedEndpoint == storageHostA.Endpoint).Index; using (var nodeA = new DistributedHashTableStorageClient(storageHostA.Endpoint)) { nodeA.Put(topology.Version, new ExtendedPutRequest { Bytes = new byte[] {2, 2, 0, 0}, Key = "abc", Segment = segment }); } }); RepeatWhileThereAreTopologyChangedErrors(() => { using (var nodeB = new DistributedHashTableStorageClient(storageHostB.Endpoint)) { topology = masterProxy.GetTopology(); Value[][] values = null; for (int i = 0; i < 100; i++) { values = nodeB.Get(topology.Version, new ExtendedGetRequest { Key = "abc", Segment = segment }); if (values[0].Length != 0) break; Thread.Sleep(250); } Assert.Equal(new byte[] {2, 2, 0, 0}, values[0][0].Data); } }); using (var nodeA = new DistributedHashTableStorageClient(storageHostA.Endpoint)) { topology = masterProxy.GetTopology(); Value[][] values = nodeA.Get(topology.Version, new ExtendedGetRequest { Key = "abc", Segment = segment }); Assert.Equal(new byte[] {2, 2, 0, 0}, values[0][0].Data); } } [Fact] public void TwoNodesCanJoinToTheCluster() { storageHostB.Start(); int countOfSegmentsInA = 0; int countOfSegmentsInB = 0; var masterProxy = new DistributedHashTableMasterClient(masterUri); for (int i = 0; i < 50; i++) { Topology topology = masterProxy.GetTopology(); Dictionary<NodeEndpoint, int> results = topology.Segments.GroupBy(x => x.AssignedEndpoint) .Select(x => new {x.Key, Count = x.Count()}) .ToDictionary(x => x.Key, x => x.Count); results.TryGetValue(storageHostA.Endpoint, out countOfSegmentsInA); results.TryGetValue(storageHostB.Endpoint, out countOfSegmentsInB); if (countOfSegmentsInA == countOfSegmentsInB && countOfSegmentsInB == 4096) return; Thread.Sleep(500); } Assert.True(false, "Should have found two nodes sharing responsability for the geometry: " + countOfSegmentsInA + " - " + countOfSegmentsInB); } [Fact] public void AfterTwoNodesJoinTheClusterEachSegmentHasBackup() { storageHostB.Start(); var masterProxy = new DistributedHashTableMasterClient(masterUri); Topology topology; for (int i = 0; i < 50; i++) { topology = masterProxy.GetTopology(); bool allSegmentsHaveBackups = topology.Segments.All(x => x.Backups.Count > 0); if (allSegmentsHaveBackups) break; Thread.Sleep(500); } topology = masterProxy.GetTopology(); Assert.True( topology.Segments.All(x => x.Backups.Count > 0) ); } [Fact] public void WillReplicateValuesToSecondJoin() { var masterProxy = new DistributedHashTableMasterClient(masterUri); using (var nodeA = new DistributedHashTableStorageClient(storageHostA.Endpoint)) { Topology topology = masterProxy.GetTopology(); nodeA.Put(topology.Version, new ExtendedPutRequest { Bytes = new byte[] {2, 2, 0, 0}, Key = "abc", Segment = 1 }); } storageHostB.Start(); //will replicate all odd segments here now for (int i = 0; i < 500; i++) { Topology topology = masterProxy.GetTopology(); if (topology.Segments[1].AssignedEndpoint == storageHostB.Endpoint) break; Thread.Sleep(500); } Value[][] values = null; RepeatWhileThereAreTopologyChangedErrors(() => { using (var nodeB = new DistributedHashTableStorageClient(storageHostB.Endpoint)) { Topology topology = masterProxy.GetTopology(); values = nodeB.Get(topology.Version, new ExtendedGetRequest { Key = "abc", Segment = 1 }); } }); Assert.Equal(new byte[] {2, 2, 0, 0}, values[0][0].Data); } } #endregion } }
using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Worker; using Moq; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Xunit; using System.Threading; namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker { public sealed class JobRunnerL0 { private IExecutionContext _jobEc; private JobRunner _jobRunner; private JobInitializeResult _initResult = new JobInitializeResult(); private AgentJobRequestMessage _message; private CancellationTokenSource _tokenSource; private Mock<IJobServer> _jobServer; private Mock<IJobServerQueue> _jobServerQueue; private Mock<IVstsAgentWebProxy> _proxyConfig; private Mock<IConfigurationStore> _config; private Mock<ITaskServer> _taskServer; private Mock<IExtensionManager> _extensions; private Mock<IStepsRunner> _stepRunner; private Mock<IJobExtension> _jobExtension; private Mock<IPagingLogger> _logger; private Mock<ITempDirectoryManager> _temp; private TestHostContext CreateTestContext([CallerMemberName] String testName = "") { var hc = new TestHostContext(this, testName); _jobEc = new Agent.Worker.ExecutionContext(); _config = new Mock<IConfigurationStore>(); _extensions = new Mock<IExtensionManager>(); _jobExtension = new Mock<IJobExtension>(); _jobServer = new Mock<IJobServer>(); _jobServerQueue = new Mock<IJobServerQueue>(); _proxyConfig = new Mock<IVstsAgentWebProxy>(); _taskServer = new Mock<ITaskServer>(); _stepRunner = new Mock<IStepsRunner>(); _logger = new Mock<IPagingLogger>(); _temp = new Mock<ITempDirectoryManager>(); if (_tokenSource != null) { _tokenSource.Dispose(); _tokenSource = null; } _tokenSource = new CancellationTokenSource(); var expressionManager = new ExpressionManager(); expressionManager.Initialize(hc); hc.SetSingleton<IExpressionManager>(expressionManager); _jobRunner = new JobRunner(); _jobRunner.Initialize(hc); TaskOrchestrationPlanReference plan = new TaskOrchestrationPlanReference(); TimelineReference timeline = new Timeline(Guid.NewGuid()); JobEnvironment environment = new JobEnvironment(); environment.Variables[Constants.Variables.System.Culture] = "en-US"; environment.SystemConnection = new ServiceEndpoint() { Url = new Uri("https://test.visualstudio.com"), Authorization = new EndpointAuthorization() { Scheme = "Test", } }; environment.SystemConnection.Authorization.Parameters["AccessToken"] = "token"; List<TaskInstance> tasks = new List<TaskInstance>(); Guid JobId = Guid.NewGuid(); _message = new AgentJobRequestMessage(plan, timeline, JobId, testName, testName, environment, tasks); _extensions.Setup(x => x.GetExtensions<IJobExtension>()). Returns(new[] { _jobExtension.Object }.ToList()); _initResult.PreJobSteps.Clear(); _initResult.JobSteps.Clear(); _initResult.PostJobStep.Clear(); _jobExtension.Setup(x => x.InitializeJob(It.IsAny<IExecutionContext>(), It.IsAny<AgentJobRequestMessage>())). Returns(Task.FromResult(_initResult)); _jobExtension.Setup(x => x.HostType) .Returns<string>(null); _proxyConfig.Setup(x => x.ProxyAddress) .Returns(string.Empty); var settings = new AgentSettings { AgentId = 1, AgentName = "agent1", ServerUrl = "https://test.visualstudio.com", WorkFolder = "_work", }; _config.Setup(x => x.GetSettings()) .Returns(settings); _logger.Setup(x => x.Setup(It.IsAny<Guid>(), It.IsAny<Guid>())); hc.SetSingleton(_config.Object); hc.SetSingleton(_jobServer.Object); hc.SetSingleton(_jobServerQueue.Object); hc.SetSingleton(_proxyConfig.Object); hc.SetSingleton(_taskServer.Object); hc.SetSingleton(_stepRunner.Object); hc.SetSingleton(_extensions.Object); hc.SetSingleton(_temp.Object); hc.EnqueueInstance<IExecutionContext>(_jobEc); hc.EnqueueInstance<IPagingLogger>(_logger.Object); return hc; } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task JobExtensionInitializeFailure() { using (TestHostContext hc = CreateTestContext()) { _jobExtension.Setup(x => x.InitializeJob(It.IsAny<IExecutionContext>(), It.IsAny<AgentJobRequestMessage>())) .Throws(new Exception()); await _jobRunner.RunAsync(_message, _tokenSource.Token); Assert.Equal(TaskResult.Failed, _jobEc.Result); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.IsAny<IList<IStep>>(), JobRunStage.PreJob), Times.Never); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task JobExtensionInitializeCancelled() { using (TestHostContext hc = CreateTestContext()) { _jobExtension.Setup(x => x.InitializeJob(It.IsAny<IExecutionContext>(), It.IsAny<AgentJobRequestMessage>())) .Throws(new OperationCanceledException()); _tokenSource.Cancel(); await _jobRunner.RunAsync(_message, _tokenSource.Token); Assert.Equal(TaskResult.Canceled, _jobEc.Result); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.IsAny<IList<IStep>>(), JobRunStage.PreJob), Times.Never); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task SkipJobStepsWhenPreJobStepsFail() { using (TestHostContext hc = CreateTestContext()) { _stepRunner.Setup(x => x.RunAsync(_jobEc, _initResult.PreJobSteps, JobRunStage.PreJob)) .Callback(() => { _jobEc.Result = TaskResult.Failed; }) .Returns(Task.CompletedTask); await _jobRunner.RunAsync(_message, _tokenSource.Token); Assert.Equal(TaskResult.Failed, _jobEc.Result); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.PreJobSteps)), JobRunStage.PreJob), Times.Once); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.JobSteps)), JobRunStage.Main), Times.Never); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task SkipJobStepsWhenPreJobStepsCancelled() { using (TestHostContext hc = CreateTestContext()) { _stepRunner.Setup(x => x.RunAsync(_jobEc, _initResult.PreJobSteps, JobRunStage.PreJob)) .Callback(() => { _jobEc.Result = TaskResult.Canceled; }) .Returns(Task.CompletedTask); await _jobRunner.RunAsync(_message, _tokenSource.Token); Assert.Equal(TaskResult.Canceled, _jobEc.Result); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.PreJobSteps)), JobRunStage.PreJob), Times.Once); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.JobSteps)), JobRunStage.Main), Times.Never); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task RunPostJobStepsEvenPreJobStepsFail() { using (TestHostContext hc = CreateTestContext()) { _stepRunner.Setup(x => x.RunAsync(_jobEc, _initResult.PreJobSteps, JobRunStage.PreJob)) .Callback(() => { _jobEc.Result = TaskResult.Failed; }) .Returns(Task.CompletedTask); ; await _jobRunner.RunAsync(_message, _tokenSource.Token); Assert.Equal(TaskResult.Failed, _jobEc.Result); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.PreJobSteps)), JobRunStage.PreJob), Times.Once); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.PostJobStep)), JobRunStage.PostJob), Times.Once); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task RunPostJobStepsEvenPreJobStepsCancelled() { using (TestHostContext hc = CreateTestContext()) { _stepRunner.Setup(x => x.RunAsync(_jobEc, _initResult.PreJobSteps, JobRunStage.PreJob)) .Callback(() => { _jobEc.Result = TaskResult.Canceled; }) .Returns(Task.CompletedTask); ; await _jobRunner.RunAsync(_message, _tokenSource.Token); Assert.Equal(TaskResult.Canceled, _jobEc.Result); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.PreJobSteps)), JobRunStage.PreJob), Times.Once); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.PostJobStep)), JobRunStage.PostJob), Times.Once); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task RunPostJobStepsEvenJobStepsFail() { using (TestHostContext hc = CreateTestContext()) { _stepRunner.Setup(x => x.RunAsync(_jobEc, _initResult.PreJobSteps, JobRunStage.PreJob)) .Returns(Task.CompletedTask); _stepRunner.Setup(x => x.RunAsync(_jobEc, _initResult.JobSteps, JobRunStage.Main)) .Callback(() => { _jobEc.Result = TaskResult.Failed; }) .Returns(Task.CompletedTask); ; await _jobRunner.RunAsync(_message, _tokenSource.Token); Assert.Equal(TaskResult.Failed, _jobEc.Result); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.PreJobSteps)), JobRunStage.PreJob), Times.Once); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.JobSteps)), JobRunStage.Main), Times.Once); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.PostJobStep)), JobRunStage.PostJob), Times.Once); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task RunPostJobStepsEvenJobStepsCancelled() { using (TestHostContext hc = CreateTestContext()) { _stepRunner.Setup(x => x.RunAsync(_jobEc, _initResult.PreJobSteps, JobRunStage.PreJob)) .Returns(Task.CompletedTask); _stepRunner.Setup(x => x.RunAsync(_jobEc, _initResult.JobSteps, JobRunStage.Main)) .Callback(() => { _jobEc.Result = TaskResult.Canceled; }) .Returns(Task.CompletedTask); ; await _jobRunner.RunAsync(_message, _tokenSource.Token); Assert.Equal(TaskResult.Canceled, _jobEc.Result); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.PreJobSteps)), JobRunStage.PreJob), Times.Once); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.JobSteps)), JobRunStage.Main), Times.Once); _stepRunner.Verify(x => x.RunAsync(It.IsAny<IExecutionContext>(), It.Is<IList<IStep>>(s => s.Equals(_initResult.PostJobStep)), JobRunStage.PostJob), Times.Once); } } } }
namespace zlib { using System; internal sealed class Inflate { static Inflate() { byte[] buffer1 = new byte[4]; buffer1[2] = (byte) SupportClass.Identity((long) 0xff); buffer1[3] = (byte) SupportClass.Identity((long) 0xff); Inflate.mark = buffer1; } public Inflate() { this.was = new long[1]; } internal int inflate(ZStream z, int f) { if (((z == null) || (z.istate == null)) || (z.next_in == null)) { return -2; } f = (f == 4) ? -5 : 0; int num1 = -5; Label_0024: switch (z.istate.mode) { case 0: if (z.avail_in == 0) { return num1; } num1 = f; z.avail_in--; z.total_in++; if (((z.istate.method = z.next_in[z.next_in_index++]) & 15) != 8) { z.istate.mode = 13; z.msg = "unknown compression method"; z.istate.marker = 5; goto Label_0024; } if (((z.istate.method >> 4) + 8) > z.istate.wbits) { z.istate.mode = 13; z.msg = "invalid window size"; z.istate.marker = 5; goto Label_0024; } z.istate.mode = 1; break; case 1: break; case 2: goto Label_01EE; case 3: goto Label_0258; case 4: goto Label_02CA; case 5: goto Label_033B; case 6: z.istate.mode = 13; z.msg = "need dictionary"; z.istate.marker = 0; return -2; case 7: num1 = z.istate.blocks.proc(z, num1); if (num1 != -3) { if (num1 == 0) { num1 = f; } if (num1 != 1) { return num1; } num1 = f; z.istate.blocks.reset(z, z.istate.was); if (z.istate.nowrap != 0) { z.istate.mode = 12; goto Label_0024; } z.istate.mode = 8; goto Label_0468; } z.istate.mode = 13; z.istate.marker = 0; goto Label_0024; case 8: goto Label_0468; case 9: goto Label_04D3; case 10: goto Label_0546; case 11: goto Label_05B8; case 12: goto Label_0667; case 13: return -3; default: return -2; } if (z.avail_in == 0) { return num1; } num1 = f; z.avail_in--; z.total_in++; int num2 = z.next_in[z.next_in_index++] & 0xff; if ((((z.istate.method << 8) + num2) % 0x1f) != 0) { z.istate.mode = 13; z.msg = "incorrect header check"; z.istate.marker = 5; goto Label_0024; } if ((num2 & 0x20) == 0) { z.istate.mode = 7; goto Label_0024; } z.istate.mode = 2; Label_01EE: if (z.avail_in == 0) { return num1; } num1 = f; z.avail_in--; z.total_in++; z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 0x18) & -16777216; z.istate.mode = 3; Label_0258: if (z.avail_in == 0) { return num1; } num1 = f; z.avail_in--; z.total_in++; z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 0x10) & 0xff0000; z.istate.mode = 4; Label_02CA: if (z.avail_in == 0) { return num1; } num1 = f; z.avail_in--; z.total_in++; z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00; z.istate.mode = 5; Label_033B: if (z.avail_in == 0) { return num1; } num1 = f; z.avail_in--; z.total_in++; z.istate.need += z.next_in[z.next_in_index++] & 0xff; z.adler = z.istate.need; z.istate.mode = 6; return 2; Label_0468: if (z.avail_in == 0) { return num1; } num1 = f; z.avail_in--; z.total_in++; z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 0x18) & -16777216; z.istate.mode = 9; Label_04D3: if (z.avail_in == 0) { return num1; } num1 = f; z.avail_in--; z.total_in++; z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 0x10) & 0xff0000; z.istate.mode = 10; Label_0546: if (z.avail_in == 0) { return num1; } num1 = f; z.avail_in--; z.total_in++; z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00; z.istate.mode = 11; Label_05B8: if (z.avail_in == 0) { return num1; } num1 = f; z.avail_in--; z.total_in++; z.istate.need += z.next_in[z.next_in_index++] & 0xff; if (((int) z.istate.was[0]) != ((int) z.istate.need)) { z.istate.mode = 13; z.msg = "incorrect data check"; z.istate.marker = 5; goto Label_0024; } z.istate.mode = 12; Label_0667: return 1; } internal int inflateEnd(ZStream z) { if (this.blocks != null) { this.blocks.free(z); } this.blocks = null; return 0; } internal int inflateInit(ZStream z, int w) { z.msg = null; this.blocks = null; this.nowrap = 0; if (w < 0) { w = -w; this.nowrap = 1; } if ((w < 8) || (w > 15)) { this.inflateEnd(z); return -2; } this.wbits = w; z.istate.blocks = new InfBlocks(z, (z.istate.nowrap != 0) ? null : this, 1 << (w & 0x1f)); this.inflateReset(z); return 0; } internal int inflateReset(ZStream z) { if ((z == null) || (z.istate == null)) { return -2; } z.total_in = z.total_out = 0; z.msg = null; z.istate.mode = (z.istate.nowrap != 0) ? 7 : 0; z.istate.blocks.reset(z, null); return 0; } internal int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength) { int num1 = 0; int num2 = dictLength; if (((z == null) || (z.istate == null)) || (z.istate.mode != 6)) { return -2; } if (z._adler.adler32((long) 1, dictionary, 0, dictLength) != z.adler) { return -3; } z.adler = z._adler.adler32((long) 0, null, 0, 0); if (num2 >= (1 << (z.istate.wbits & 0x1f))) { num2 = (1 << (z.istate.wbits & 0x1f)) - 1; num1 = dictLength - num2; } z.istate.blocks.set_dictionary(dictionary, num1, num2); z.istate.mode = 7; return 0; } internal int inflateSync(ZStream z) { if ((z == null) || (z.istate == null)) { return -2; } if (z.istate.mode != 13) { z.istate.mode = 13; z.istate.marker = 0; } int num1 = z.avail_in; if (num1 == 0) { return -5; } int num2 = z.next_in_index; int num3 = z.istate.marker; while ((num1 != 0) && (num3 < 4)) { if (z.next_in[num2] == Inflate.mark[num3]) { num3++; } else if (z.next_in[num2] != 0) { num3 = 0; } else { num3 = 4 - num3; } num2++; num1--; } z.total_in += num2 - z.next_in_index; z.next_in_index = num2; z.avail_in = num1; z.istate.marker = num3; if (num3 != 4) { return -3; } long num4 = z.total_in; long num5 = z.total_out; this.inflateReset(z); z.total_in = num4; z.total_out = num5; z.istate.mode = 7; return 0; } internal int inflateSyncPoint(ZStream z) { if (((z != null) && (z.istate != null)) && (z.istate.blocks != null)) { return z.istate.blocks.sync_point(); } return -2; } private const int BAD = 13; internal InfBlocks blocks; private const int BLOCKS = 7; private const int CHECK1 = 11; private const int CHECK2 = 10; private const int CHECK3 = 9; private const int CHECK4 = 8; private const int DICT0 = 6; private const int DICT1 = 5; private const int DICT2 = 4; private const int DICT3 = 3; private const int DICT4 = 2; private const int DONE = 12; private const int FLAG = 1; private static byte[] mark; internal int marker; private const int MAX_WBITS = 15; internal int method; private const int METHOD = 0; internal int mode; internal long need; internal int nowrap; private const int PRESET_DICT = 0x20; internal long[] was; internal int wbits; private const int Z_BUF_ERROR = -5; private const int Z_DATA_ERROR = -3; private const int Z_DEFLATED = 8; private const int Z_ERRNO = -1; internal const int Z_FINISH = 4; internal const int Z_FULL_FLUSH = 3; private const int Z_MEM_ERROR = -4; private const int Z_NEED_DICT = 2; internal const int Z_NO_FLUSH = 0; private const int Z_OK = 0; internal const int Z_PARTIAL_FLUSH = 1; private const int Z_STREAM_END = 1; private const int Z_STREAM_ERROR = -2; internal const int Z_SYNC_FLUSH = 2; private const int Z_VERSION_ERROR = -6; } }
// 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.Text; namespace System.IO { /// <summary>Contains internal path helpers that are shared between many projects.</summary> internal static partial class PathInternal { /// <summary> /// Returns true if the path ends in a directory separator. /// </summary> internal static bool EndsInDirectorySeparator(ReadOnlySpan<char> path) => path.Length > 0 && IsDirectorySeparator(path[path.Length - 1]); /// <summary> /// Returns true if the path starts in a directory separator. /// </summary> internal static bool StartsWithDirectorySeparator(ReadOnlySpan<char> path) => path.Length > 0 && IsDirectorySeparator(path[0]); internal static string EnsureTrailingSeparator(string path) => EndsInDirectorySeparator(path.AsSpan()) ? path : path + DirectorySeparatorCharAsString; internal static string TrimEndingDirectorySeparator(string path) => EndsInDirectorySeparator(path.AsSpan()) && !IsRoot(path.AsSpan()) ? path.Substring(0, path.Length - 1) : path; internal static ReadOnlySpan<char> TrimEndingDirectorySeparator(ReadOnlySpan<char> path) => EndsInDirectorySeparator(path) && !IsRoot(path) ? path.Slice(0, path.Length - 1) : path; internal static bool IsRoot(ReadOnlySpan<char> path) => path.Length == GetRootLength(path); /// <summary> /// Get the common path length from the start of the string. /// </summary> internal static int GetCommonPathLength(string first, string second, bool ignoreCase) { int commonChars = EqualStartingCharacterCount(first, second, ignoreCase: ignoreCase); // If nothing matches if (commonChars == 0) return commonChars; // Or we're a full string and equal length or match to a separator if (commonChars == first.Length && (commonChars == second.Length || IsDirectorySeparator(second[commonChars]))) return commonChars; if (commonChars == second.Length && IsDirectorySeparator(first[commonChars])) return commonChars; // It's possible we matched somewhere in the middle of a segment e.g. C:\Foodie and C:\Foobar. while (commonChars > 0 && !IsDirectorySeparator(first[commonChars - 1])) commonChars--; return commonChars; } /// <summary> /// Gets the count of common characters from the left optionally ignoring case /// </summary> internal static unsafe int EqualStartingCharacterCount(string first, string second, bool ignoreCase) { if (string.IsNullOrEmpty(first) || string.IsNullOrEmpty(second)) return 0; int commonChars = 0; fixed (char* f = first) fixed (char* s = second) { char* l = f; char* r = s; char* leftEnd = l + first.Length; char* rightEnd = r + second.Length; while (l != leftEnd && r != rightEnd && (*l == *r || (ignoreCase && char.ToUpperInvariant((*l)) == char.ToUpperInvariant((*r))))) { commonChars++; l++; r++; } } return commonChars; } /// <summary> /// Returns true if the two paths have the same root /// </summary> internal static bool AreRootsEqual(string first, string second, StringComparison comparisonType) { int firstRootLength = GetRootLength(first.AsSpan()); int secondRootLength = GetRootLength(second.AsSpan()); return firstRootLength == secondRootLength && string.Compare( strA: first, indexA: 0, strB: second, indexB: 0, length: firstRootLength, comparisonType: comparisonType) == 0; } /// <summary> /// Try to remove relative segments from the given path (without combining with a root). /// </summary> /// <param name="path">Input path</param> /// <param name="rootLength">The length of the root of the given path</param> internal static string RemoveRelativeSegments(string path, int rootLength) { Span<char> initialBuffer = stackalloc char[260 /* PathInternal.MaxShortPath */]; ValueStringBuilder sb = new ValueStringBuilder(initialBuffer); if (RemoveRelativeSegments(path.AsSpan(), rootLength, ref sb)) { path = sb.ToString(); } sb.Dispose(); return path; } /// <summary> /// Try to remove relative segments from the given path (without combining with a root). /// </summary> /// <param name="path">Input path</param> /// <param name="rootLength">The length of the root of the given path</param> /// <param name="sb">String builder that will store the result</param> /// <returns>"true" if the path was modified</returns> internal static bool RemoveRelativeSegments(ReadOnlySpan<char> path, int rootLength, ref ValueStringBuilder sb) { Debug.Assert(rootLength > 0); bool flippedSeparator = false; int skip = rootLength; // We treat "\.." , "\." and "\\" as a relative segment. We want to collapse the first separator past the root presuming // the root actually ends in a separator. Otherwise the first segment for RemoveRelativeSegments // in cases like "\\?\C:\.\" and "\\?\C:\..\", the first segment after the root will be ".\" and "..\" which is not considered as a relative segment and hence not be removed. if (PathInternal.IsDirectorySeparator(path[skip - 1])) skip--; // Remove "//", "/./", and "/../" from the path by copying each character to the output, // except the ones we're removing, such that the builder contains the normalized path // at the end. if (skip > 0) { sb.Append(path.Slice(0, skip)); } for (int i = skip; i < path.Length; i++) { char c = path[i]; if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length) { // Skip this character if it's a directory separator and if the next character is, too, // e.g. "parent//child" => "parent/child" if (PathInternal.IsDirectorySeparator(path[i + 1])) { continue; } // Skip this character and the next if it's referring to the current directory, // e.g. "parent/./child" => "parent/child" if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) && path[i + 1] == '.') { i++; continue; } // Skip this character and the next two if it's referring to the parent directory, // e.g. "parent/child/../grandchild" => "parent/grandchild" if (i + 2 < path.Length && (i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) && path[i + 1] == '.' && path[i + 2] == '.') { // Unwind back to the last slash (and if there isn't one, clear out everything). int s; for (s = sb.Length - 1; s >= skip; s--) { if (PathInternal.IsDirectorySeparator(sb[s])) { sb.Length = (i + 3 >= path.Length && s == skip) ? s + 1 : s; // to avoid removing the complete "\tmp\" segment in cases like \\?\C:\tmp\..\, C:\tmp\.. break; } } if (s < skip) { sb.Length = skip; } i += 2; continue; } } // Normalize the directory separator if needed if (c != PathInternal.DirectorySeparatorChar && c == PathInternal.AltDirectorySeparatorChar) { c = PathInternal.DirectorySeparatorChar; flippedSeparator = true; } sb.Append(c); } // If we haven't changed the source path, return the original if (!flippedSeparator && sb.Length == path.Length) { return false; } // We may have eaten the trailing separator from the root when we started and not replaced it if (skip != rootLength && sb.Length < rootLength) { sb.Append(path[rootLength - 1]); } return true; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The Windows Forms user interface layer for the DotSpatial.Symbology library. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 5/1/2009 9:07:49 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// DashControl /// </summary> public class DashControl : Control { #region Events /// <summary> /// Occurs any time any action has occured that changes the pattern. /// </summary> public event EventHandler PatternChanged; #endregion #region Private Variables private readonly Timer _highlightTimer; private SizeF _blockSize; private Color _buttonDownDarkColor; private Color _buttonDownLitColor; private Color _buttonUpDarkColor; private Color _butttonUpLitColor; private List<SquareButton> _horizontalButtons; DashSliderHorizontal _horizontalSlider; private Color _lineColor; private double _lineWidth; private List<SquareButton> _verticalButtons; DashSliderVertical _verticalSlider; #endregion #region Constructors /// <summary> /// Creates a new instance of DashControl /// </summary> public DashControl() { _blockSize.Width = 10F; _blockSize.Height = 10F; _horizontalSlider = new DashSliderHorizontal(); _horizontalSlider.Size = new SizeF(_blockSize.Width, _blockSize.Height * 3 / 2); _verticalSlider = new DashSliderVertical(); _verticalSlider.Size = new SizeF(_blockSize.Width * 3 / 2, _blockSize.Height); _buttonDownDarkColor = SystemColors.ControlDark; _buttonDownLitColor = SystemColors.ControlDark; _buttonUpDarkColor = SystemColors.Control; _butttonUpLitColor = SystemColors.Control; _highlightTimer = new Timer(); _highlightTimer.Interval = 100; _highlightTimer.Tick += HighlightTimerTick; } #endregion #region Methods #endregion #region Properties /// <summary> /// Gets or sets the boolean pattern for the horizontal patterns that control the custom /// dash style. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool[] DashButtons { get { bool[] result = new bool[_horizontalButtons.Count]; for (int i = 0; i < _horizontalButtons.Count; i++) { result[i] = _horizontalButtons[i].IsDown; } return result; } set { SetHorizontalPattern(value); } } /// <summary> /// Gets or sets the boolean pattern for the vertical patterns that control the custom /// compound array. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool[] CompoundButtons { get { bool[] result = new bool[_verticalButtons.Count]; for (int i = 0; i < _verticalButtons.Count; i++) { result[i] = _verticalButtons[i].IsDown; } return result; } set { SetVerticalPattern(value); } } /// <summary> /// Gets or sets the color for all the buttons when they are pressed and inactive /// </summary> [Description("Gets or sets the base color for all the buttons when they are pressed and inactive")] public Color ButtonDownDarkColor { get { return _buttonDownDarkColor; } set { _buttonDownDarkColor = value; } } /// <summary> /// Gets or sets the base color for all the buttons when they are pressed and active /// </summary> [Description("Gets or sets the base color for all the buttons when they are pressed and active")] public Color ButtonDownLitColor { get { return _buttonDownLitColor; } set { _buttonDownLitColor = value; } } /// <summary> /// Gets or sets the base color for all the buttons when they are not pressed and not active. /// </summary> [Description("Gets or sets the base color for all the buttons when they are not pressed and not active.")] public Color ButtonUpDarkColor { get { return _buttonUpDarkColor; } set { _buttonUpDarkColor = value; } } /// <summary> /// Gets or sets the base color for all the buttons when they are not pressed but are active. /// </summary> [Description("Gets or sets the base color for all the buttons when they are not pressed but are active.")] public Color ButtonUpLitColor { get { return _butttonUpLitColor; } set { _butttonUpLitColor = value; } } /// <summary> /// Gets or sets the line width for the actual line being described, regardless of scale mode. /// </summary> public double LineWidth { get { return _lineWidth; } set { _lineWidth = value; } } /// <summary> /// Gets the width of a square in the same units used for the line width. /// </summary> public double SquareWidth { get { return _lineWidth * Width / _blockSize.Width; } } /// <summary> /// Gets the height of the square /// </summary> public double SquareHeight { get { return _lineWidth * Height / _blockSize.Height; } } /// <summary> /// Gets or sets the position of the sliders. The X describes the horizontal placement /// of the horizontal slider, while the Y describes the vertical placement of the vertical slider. /// </summary> [Description("Gets or sets the position of the sliders. The X describes the horizontal placement of the horizontal slider, while the Y describes the vertical placement of the vertical slider."), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public DashSliderHorizontal HorizontalSlider { get { return _horizontalSlider; } set { _horizontalSlider = value; } } /// <summary> /// Gets or sets the floating point size of each block in pixels. /// </summary> [Description("Gets or sets the floating point size of each block in pixels.")] public SizeF BlockSize { get { return _blockSize; } set { _blockSize = value; if (HorizontalSlider != null) HorizontalSlider.Size = new SizeF(_blockSize.Width, _blockSize.Height * 3 / 2); if (VerticalSlider != null) VerticalSlider.Size = new SizeF(_blockSize.Width * 3 / 2, _blockSize.Height); } } /// <summary> /// Gets or sets the color of the line /// </summary> [Description("Gets or sets the color that should be used for the filled sections of the line.")] public Color LineColor { get { return _lineColor; } set { _lineColor = value; } } /// <summary> /// Gets or sets the vertical Slider /// </summary> [Description("Gets or sets the image to use as the vertical slider. If this is null, a simple triangle will be used."), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public DashSliderVertical VerticalSlider { get { return _verticalSlider; } set { _verticalSlider = value; } } /// <summary> /// /// </summary> /// <returns></returns> public float[] GetDashPattern() { bool pressed = true; List<float> pattern = new List<float>(); float previousPosition = 0F; int i = 0; foreach (SquareButton button in _horizontalButtons) { if (button.IsDown != pressed) { float position = (i / ((float)_verticalButtons.Count)); if (position == 0) position = .0000001f; pattern.Add(position - previousPosition); previousPosition = position; pressed = !pressed; } i++; } float final = (i / (float)_verticalButtons.Count); if (final == 0) final = 0.000001F; pattern.Add(final - previousPosition); if (pattern.Count % 2 == 1) pattern.Add(.00001F); if (pattern.Count == 0) return null; return pattern.ToArray(); } /// <summary> /// /// </summary> public float[] GetCompoundArray() { bool pressed = false; List<float> pattern = new List<float>(); int i = 0; foreach (SquareButton button in _verticalButtons) { if (button.IsDown != pressed) { float position = i / (float)_verticalButtons.Count; pattern.Add(position); pressed = !pressed; } i++; } if (pressed) { pattern.Add(1F); } if (pattern.Count == 0) return null; return pattern.ToArray(); } /// <summary> /// Sets the pattern of squares for this pen by working with the given dash and compound patterns. /// </summary> /// <param name="stroke">Completely defines the ICartographicStroke that is being used to set the pattern.</param> public void SetPattern(ICartographicStroke stroke) { _lineColor = stroke.Color; _lineWidth = stroke.Width; if (stroke.DashButtons == null) { _horizontalButtons = null; _horizontalSlider.Position = new PointF(50F, 0F); } else { SetHorizontalPattern(stroke.DashButtons); } if (stroke.CompoundButtons == null) { _verticalButtons = null; _verticalSlider.Position = new PointF(0F, 20F); } else { SetVerticalPattern(stroke.CompoundButtons); } CalculatePattern(); Invalidate(); } /// <summary> /// Sets the horizontal pattern for this control /// </summary> /// <param name="buttonPattern"></param> protected virtual void SetHorizontalPattern(bool[] buttonPattern) { _horizontalSlider.Position = new PointF((buttonPattern.Length + 1) * _blockSize.Width, 0); _horizontalButtons = new List<SquareButton>(); for (int i = 0; i < buttonPattern.Length; i++) { SquareButton sq = new SquareButton(); sq.Bounds = new RectangleF((i + 1) * _blockSize.Width, 0, _blockSize.Width, _blockSize.Height); sq.ColorDownDark = _buttonDownDarkColor; sq.ColorDownLit = _buttonDownLitColor; sq.ColorUpDark = _buttonUpDarkColor; sq.ColorUpLit = _butttonUpLitColor; sq.IsDown = buttonPattern[i]; _horizontalButtons.Add(sq); } } /// <summary> /// Sets the vertical pattern for this control /// </summary> /// <param name="buttonPattern"></param> protected virtual void SetVerticalPattern(bool[] buttonPattern) { _verticalSlider.Position = new PointF(0, (buttonPattern.Length + 1) * _blockSize.Width); _verticalButtons = new List<SquareButton>(); for (int i = 0; i < buttonPattern.Length; i++) { SquareButton sq = new SquareButton(); sq.Bounds = new RectangleF(0, (i + 1) * _blockSize.Width, _blockSize.Width, _blockSize.Height); sq.ColorDownDark = _buttonDownDarkColor; sq.ColorDownLit = _buttonDownLitColor; sq.ColorUpDark = _buttonUpDarkColor; sq.ColorUpLit = _butttonUpLitColor; sq.IsDown = buttonPattern[i]; _verticalButtons.Add(sq); } } #endregion #region Protected Methods /// <summary> /// Occurs when the dash control needs to calculate the pattern /// </summary> protected override void OnCreateControl() { base.OnCreateControl(); CalculatePattern(); } /// <summary> /// Prevent flicker /// </summary> /// <param name="pevent"></param> protected override void OnPaintBackground(PaintEventArgs pevent) { //base.OnPaintBackground(pevent); } /// <summary> /// Creates a bitmap to draw to instead of drawing directly to the image. /// </summary> /// <param name="e"></param> protected override void OnPaint(PaintEventArgs e) { Rectangle clip = new Rectangle(); if (clip.IsEmpty) clip = ClientRectangle; Bitmap bmp = new Bitmap(clip.Width, clip.Height); Graphics g = Graphics.FromImage(bmp); g.TranslateTransform(clip.X, clip.Y); g.Clear(BackColor); OnDraw(g, e.ClipRectangle); g.Dispose(); e.Graphics.DrawImage(bmp, clip, clip, GraphicsUnit.Pixel); } /// <summary> /// Actually controls the basic drawing control. /// </summary> /// <param name="g"></param> /// <param name="clipRectangle"></param> protected virtual void OnDraw(Graphics g, Rectangle clipRectangle) { Brush b = new SolidBrush(LineColor); foreach (SquareButton vButton in _verticalButtons) { foreach (SquareButton hButton in _horizontalButtons) { float x = hButton.Bounds.X; float y = vButton.Bounds.Y; if (hButton.IsDown && vButton.IsDown) { g.FillRectangle(b, x, y, _blockSize.Width, _blockSize.Height); } else { g.FillRectangle(Brushes.White, x, y, _blockSize.Width, _blockSize.Height); } g.DrawRectangle(Pens.Gray, x, y, _blockSize.Width, _blockSize.Height); } } for (int v = 0; v < Height / _blockSize.Height; v++) { float y = v * _blockSize.Height; if (y < clipRectangle.Y - _blockSize.Height) continue; if (y > clipRectangle.Bottom + _blockSize.Height) continue; for (int u = 0; u < Width / _blockSize.Width; u++) { float x = u * _blockSize.Width; if (x < clipRectangle.X - _blockSize.Width) continue; if (x > clipRectangle.Right + _blockSize.Width) continue; g.DrawRectangle(Pens.Gray, x, y, _blockSize.Width, _blockSize.Height); } } foreach (SquareButton button in _horizontalButtons) { button.Draw(g, clipRectangle); } foreach (SquareButton button in _verticalButtons) { button.Draw(g, clipRectangle); } _horizontalSlider.Draw(g, clipRectangle); _verticalSlider.Draw(g, clipRectangle); } /// <summary> /// Handles the mouse down event /// </summary> /// <param name="e"></param> protected override void OnMouseDown(MouseEventArgs e) { // Sliders have priority over buttons if (e.Button != MouseButtons.Left) return; if (VerticalSlider.Bounds.Contains(new PointF(e.X, e.Y))) { VerticalSlider.IsDragging = true; return; // Vertical is drawn on top, so if they are both selected, select vertical } if (HorizontalSlider.Bounds.Contains(new PointF(e.X, e.Y))) { HorizontalSlider.IsDragging = true; return; } base.OnMouseDown(e); } /// <summary> /// Handles mouse movement /// </summary> /// <param name="e"></param> protected override void OnMouseMove(MouseEventArgs e) { _highlightTimer.Stop(); // Activate buttons only if the mouse is over them. Inactivate them otherwise. bool invalid = UpdateHighlight(e.Location); // Sliders RectangleF area = new RectangleF(); if (HorizontalSlider.IsDragging) { area = HorizontalSlider.Bounds; PointF loc = HorizontalSlider.Position; loc.X = e.X; HorizontalSlider.Position = loc; area = RectangleF.Union(area, HorizontalSlider.Bounds); } area.Inflate(10F, 10F); if (invalid == false) Invalidate(new Region(area)); if (VerticalSlider.IsDragging) { area = VerticalSlider.Bounds; PointF loc = VerticalSlider.Position; loc.Y = e.Y; VerticalSlider.Position = loc; area = RectangleF.Union(area, VerticalSlider.Bounds); } area.Inflate(10F, 10F); if (invalid == false) Invalidate(new Region(area)); if (invalid) Invalidate(); base.OnMouseMove(e); _highlightTimer.Start(); } /// <summary> /// Handles the mouse up event /// </summary> /// <param name="e"></param> protected override void OnMouseUp(MouseEventArgs e) { if (e.Button == MouseButtons.Right) return; bool invalid = false; bool handled = false; if (_horizontalSlider.IsDragging) { CalculatePattern(); _horizontalSlider.IsDragging = false; invalid = true; handled = true; } if (_verticalSlider.IsDragging) { CalculatePattern(); _verticalSlider.IsDragging = false; invalid = true; handled = true; } if (handled == false) { foreach (SquareButton button in _horizontalButtons) { invalid = invalid || button.UpdatePressed(e.Location); } foreach (SquareButton button in _verticalButtons) { invalid = invalid || button.UpdatePressed(e.Location); } } if (invalid) { Invalidate(); OnPatternChanged(); } base.OnMouseUp(e); } /// <summary> /// Fires the pattern changed event. /// </summary> protected virtual void OnPatternChanged() { if (PatternChanged != null) PatternChanged(this, EventArgs.Empty); } /// <summary> /// Forces a calculation during the resizing that changes the pattern squares. /// </summary> /// <param name="e"></param> protected override void OnResize(EventArgs e) { base.OnResize(e); CalculatePattern(); } #endregion #region Event Handlers private void HighlightTimerTick(object sender, EventArgs e) { Point pt = PointToClient(MousePosition); // If the mouse is still in the control, then the mouse move is enough // to update the highlight. if (ClientRectangle.Contains(pt) == false) { _highlightTimer.Stop(); UpdateHighlight(pt); } } #endregion #region Private Functions /// <summary> /// Updates the highlight based on mouse position. /// </summary> /// <returns></returns> private bool UpdateHighlight(Point location) { bool invalid = false; foreach (SquareButton button in _horizontalButtons) { invalid = invalid || button.UpdateLight(location); } foreach (SquareButton button in _verticalButtons) { invalid = invalid || button.UpdateLight(location); } return invalid; } private void CalculatePattern() { // Horizontal PointF loc = HorizontalSlider.Position; if (loc.X > Width) loc.X = Width; int hCount = (int)Math.Ceiling(loc.X / _blockSize.Width); loc.X = hCount * _blockSize.Width; HorizontalSlider.Position = loc; List<SquareButton> newButtonsH = new List<SquareButton>(); int start = 1; if (_horizontalButtons != null) { int minLen = Math.Min(_horizontalButtons.Count, hCount - 1); for (int i = 0; i < minLen; i++) { newButtonsH.Add(_horizontalButtons[i]); } start = minLen + 1; } for (int j = start; j < hCount; j++) { SquareButton sq = new SquareButton(); sq.Bounds = new RectangleF(j * _blockSize.Width, 0, _blockSize.Width, _blockSize.Height); sq.ColorDownDark = _buttonDownDarkColor; sq.ColorDownLit = _buttonDownLitColor; sq.ColorUpDark = _buttonUpDarkColor; sq.ColorUpLit = _butttonUpLitColor; sq.IsDown = true; newButtonsH.Add(sq); } _horizontalButtons = newButtonsH; // Vertical loc = VerticalSlider.Position; if (loc.Y > Height) loc.Y = Height; int vCount = (int)Math.Ceiling(loc.Y / _blockSize.Height); loc.Y = (vCount) * _blockSize.Height; VerticalSlider.Position = loc; List<SquareButton> buttons = new List<SquareButton>(); start = 1; if (_verticalButtons != null) { int minLen = Math.Min(_verticalButtons.Count, vCount - 1); for (int i = 0; i < minLen; i++) { buttons.Add(_verticalButtons[i]); } start = minLen + 1; } for (int j = start; j < vCount; j++) { SquareButton sq = new SquareButton(); sq.Bounds = new RectangleF(0, j * _blockSize.Height, _blockSize.Width, _blockSize.Height); sq.ColorDownDark = _buttonDownDarkColor; sq.ColorDownLit = _buttonDownLitColor; sq.ColorUpDark = _buttonUpDarkColor; sq.ColorUpLit = _butttonUpLitColor; sq.IsDown = true; buttons.Add(sq); } _verticalButtons = buttons; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using AutoFixture.Idioms; using AutoFixture.Kernel; using TestTypeFoundation; using Xunit; namespace AutoFixture.IdiomsUnitTest { public partial class GuardClauseAssertionTest { private static Type[] UnguardedOpenGenericTypes => new[] { typeof(ClassContraint<>), typeof(CertainClassContraint<>), typeof(CertainClassAndInterfacesContraint<>), typeof(MultipleGenericArguments<,>), typeof(AbstractTypeAndInterfacesContraint<>), typeof(OpenGenericTestType<>).BaseType, typeof(ConstructedGenericTestType<>).BaseType, typeof(InternalProtectedConstructorTestConstraint<>), typeof(ModestConstructorTestConstraint<>), typeof(ConstructorMatchTestType<,>), typeof(MethodMatchTestType<,>), typeof(ByRefTestType<>) }; public static TheoryData<MemberRef<ConstructorInfo>> ConstructorsOnUnguardedOpenGenericTypes => MakeTheoryData( UnguardedOpenGenericTypes .SelectMany(t => t.GetConstructors()) .Select(c => new MemberRef<ConstructorInfo>(c))); [Theory, MemberData(nameof(ConstructorsOnUnguardedOpenGenericTypes))] public void VerifyConstructorOnUnguardedGenericThrows(MemberRef<ConstructorInfo> ctorRef) { // Arrange var constructorInfo = ctorRef.Member; var sut = new GuardClauseAssertion(new Fixture { OmitAutoProperties = true }); // Act // Assert var e = Assert.Throws<GuardClauseException>(() => sut.Verify(constructorInfo)); Assert.Contains("Are you missing a Guard Clause?", e.Message); } public static TheoryData<MemberRef<MethodInfo>> MethodsOnUnguardedOpenGenericTypes => MakeTheoryData( UnguardedOpenGenericTypes .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) // Skip getters and setters .Where(m => !m.Name.StartsWith("get_") && !m.Name.StartsWith("set_")) .Select(m => new MemberRef<MethodInfo>(m))); [Theory, MemberData(nameof(MethodsOnUnguardedOpenGenericTypes))] public void VerifyMethodOnUnguardedGenericThrows(MemberRef<MethodInfo> methodRef) { // Arrange var methodInfo = methodRef.Member; var sut = new GuardClauseAssertion(new Fixture { OmitAutoProperties = true }); // Act // Assert var e = Assert.Throws<GuardClauseException>(() => sut.Verify(methodInfo)); Assert.Contains("Are you missing a Guard Clause?", e.Message); } public static TheoryData<MemberRef<PropertyInfo>> PropertiesOnUnguardedOpenGenericTypes => MakeTheoryData( UnguardedOpenGenericTypes .SelectMany(t => t.GetProperties()) .Select(c => new MemberRef<PropertyInfo>(c))); [Theory, MemberData(nameof(PropertiesOnUnguardedOpenGenericTypes))] public void VerifyPropertyOnUnguardedGenericThrows(MemberRef<PropertyInfo> propertyRef) { // Arrange var propertyInfo = propertyRef.Member; var sut = new GuardClauseAssertion(new Fixture { OmitAutoProperties = true }); // Act // Assert var e = Assert.Throws<GuardClauseException>(() => sut.Verify(propertyInfo)); Assert.Contains("Are you missing a Guard Clause?", e.Message); } private static Type[] GuardedOpenGenericTypes => new[] { typeof(NoContraint<>), typeof(InterfacesContraint<>), typeof(StructureAndInterfacesContraint<>), typeof(ParameterizedConstructorTestConstraint<>), typeof(UnclosedGenericMethodTestType<>), typeof(NestedGenericParameterTestType<,>) }; public static TheoryData<MemberRef<ConstructorInfo>> ConstructorsOnGuardedOpenGenericTypes => MakeTheoryData( GuardedOpenGenericTypes .SelectMany(t => t.GetConstructors()) .Select(c => new MemberRef<ConstructorInfo>(c))); [Theory, MemberData(nameof(ConstructorsOnGuardedOpenGenericTypes))] public void VerifyConstructorOnGuardedGenericDoesNotThrow(MemberRef<ConstructorInfo> ctorRef) { // Arrange var constructor = ctorRef.Member; var sut = new GuardClauseAssertion(new Fixture()); // Act // Assert Assert.Null(Record.Exception(() => sut.Verify(constructor))); } public static TheoryData<MemberRef<MethodInfo>> MethodsOnGuardedOpenGenericTypes => MakeTheoryData( GuardedOpenGenericTypes .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) // Skip getters and setters .Where(m => !m.Name.StartsWith("get_") && !m.Name.StartsWith("set_")) .Select(m => new MemberRef<MethodInfo>(m))); [Theory, MemberData(nameof(MethodsOnGuardedOpenGenericTypes))] public void VerifyMethodOnGuardedGenericDoesNotThrow(MemberRef<MethodInfo> methodRef) { // Arrange var methodInfo = methodRef.Member; var sut = new GuardClauseAssertion(new Fixture()); // Act // Assert Assert.Null(Record.Exception(() => sut.Verify(methodInfo))); } public static TheoryData<MemberRef<PropertyInfo>> PropertiesOnGuardedOpenGenericTypes => MakeTheoryData( GuardedOpenGenericTypes .SelectMany(t => t.GetProperties()) .Select(c => new MemberRef<PropertyInfo>(c))); [Theory, MemberData(nameof(PropertiesOnGuardedOpenGenericTypes))] public void VerifyPropertyOnGuardedGenericDoesNotThrow(MemberRef<PropertyInfo> propertyRef) { // Arrange var propertyInfo = propertyRef.Member; var sut = new GuardClauseAssertion(new Fixture()); // Act // Assert Assert.Null(Record.Exception(() => sut.Verify(propertyInfo))); } [Fact] public void VerifyUnguardedConstructorOnGenericHavingNoAccessibleConstructorGenericArgumentThrows() { // Arrange var sut = new GuardClauseAssertion(new Fixture()); var constructorInfo = typeof(NoAccessibleConstructorTestConstraint<>).GetConstructors().Single(); // Act // Assert var e = Assert.Throws<ArgumentException>(() => sut.Verify(constructorInfo)); Assert.Equal( "Cannot create a dummy type because the base type " + "'AutoFixture.IdiomsUnitTest.GuardClauseAssertionTest+NoAccessibleConstructorTestType' " + "does not have any accessible constructor.", e.Message); } [Fact] public void DynamicDummyTypeIfReturnMethodIsCalledReturnsAnonymousValue() { // Arrange Fixture fixture = new Fixture(); var objectValue = fixture.Freeze<object>(); var intValue = fixture.Freeze<int>(); bool mockVerification = false; var behaviorExpectation = new DelegatingBehaviorExpectation() { OnVerify = c => { var dynamicInstance = (IDynamicInstanceTestType)GetParameters(c).ElementAt(0); Assert.Equal(objectValue, dynamicInstance.Property); Assert.Equal(intValue, dynamicInstance.ReturnMethod(null, 123)); mockVerification = true; } }; var sut = new GuardClauseAssertion(fixture, behaviorExpectation); var methodInfo = typeof(DynamicInstanceTestConstraint<>).GetMethod("Method"); // Act sut.Verify(methodInfo); // Assert Assert.True(mockVerification, "mock verification."); } [Fact] public void DynamicDummyTypeIfVoidMethodIsCalledDoesNotThrows() { // Arrange bool mockVerification = false; var behaviorExpectation = new DelegatingBehaviorExpectation { OnVerify = c => { var dynamicInstance = (IDynamicInstanceTestType)GetParameters(c).ElementAt(0); Assert.Null(Record.Exception(() => dynamicInstance.VoidMethod(null, 123))); Assert.Null(Record.Exception(() => { dynamicInstance.Property = new object(); })); mockVerification = true; } }; var sut = new GuardClauseAssertion(new Fixture(), behaviorExpectation); var methodInfo = typeof(DynamicInstanceTestConstraint<>).GetMethod("Method"); // Act sut.Verify(methodInfo); // Assert Assert.True(mockVerification, "mock verification."); } [Fact] public void VerifyMethodOnGenericManyTimeLoadsOnlyUniqueAssemblies() { // Arrange var sut = new GuardClauseAssertion(new Fixture()); MethodInfo methodInfo = typeof(NoContraint<>).GetMethod(nameof(NoContraint<object>.Method)); var assembliesBefore = AppDomain.CurrentDomain.GetAssemblies(); // Act sut.Verify(methodInfo); sut.Verify(methodInfo); sut.Verify(methodInfo); // Assert var assembliesAfter = AppDomain.CurrentDomain.GetAssemblies(); Assert.Equal(assembliesBefore, assembliesAfter); } private class NoContraint<T> { public NoContraint(T argument) { } public T Property { get; set; } public void Method(T argument) { } } private class InterfacesContraint<T> where T : IInterfaceTestType, IEnumerable<object> { public InterfacesContraint(T argument) { } public T Property { get; set; } public void Method(T argument) { } } private class StructureAndInterfacesContraint<T> where T : struct, IInterfaceTestType, IEnumerable<object> { public StructureAndInterfacesContraint(T argument) { } public T Property { get; set; } public void Method(T argument) { } } public interface IInterfaceTestType { event EventHandler TestEvent; object Property { get; set; } void Method(object argument); TResult GenericMethod<TValue, TResult>(TValue argument) where TValue : ICloneable where TResult : class, ICloneable; } private class ClassContraint<T> where T : class { public ClassContraint(T argument) { } public T Property { get; set; } public void Method(T argument) { } } private class CertainClassContraint<T> where T : ConcreteType { public CertainClassContraint(T argument) { } public T Property { get; set; } public void Method(T argument) { } } private class CertainClassAndInterfacesContraint<T> where T : ConcreteType, IInterfaceTestType, IEnumerable<object> { public CertainClassAndInterfacesContraint(T argument) { } public T Property { get; set; } public void Method(T argument) { } } private class MultipleGenericArguments<T1, T2> where T1 : class { public MultipleGenericArguments(T1 argument1, T2 argument2) { } public T1 Property { get; set; } public void Method(T1 argument1, T2 argument2) { } } private class AbstractTypeAndInterfacesContraint<T> where T : AbstractTestType, IInterfaceTestType, IEnumerable<object> { public AbstractTypeAndInterfacesContraint(T argument) { } public T Property { get; set; } public void Method(T argument) { } } public abstract class AbstractTestType { public abstract event EventHandler TestEvent; protected abstract event EventHandler ProtectedTestEvent; public abstract object Property { get; set; } protected abstract object ProtectedProperty { get; set; } public abstract void Method(object argument); protected abstract void ProtectedMethod(object argument); } private class OpenGenericTestType<T> : OpenGenericTestTypeBase<T> where T : class { public OpenGenericTestType(T argument) : base(argument) { } } private class OpenGenericTestTypeBase<T> { public OpenGenericTestTypeBase(T argument) { } public T Property { get; set; } public void Method(T argument) { } } private class ConstructedGenericTestType<T> : ConstructedGenericTestTypeBase<string, T> where T : class { public ConstructedGenericTestType(string argument1, T argument2) : base(argument1, argument2) { } } private class ConstructedGenericTestTypeBase<T1, T2> { public ConstructedGenericTestTypeBase(T1 argument1, T2 argument2) { } public T1 Property1 { get; set; } public T2 Property2 { get; set; } public void Method(T1 argument1, T2 argument2) { } } private class ParameterizedConstructorTestConstraint<T> where T : ParameterizedConstructorTestType, new() { public void Method(T argument, object test) { if (argument == null) throw new ArgumentNullException(nameof(argument)); if (argument.Argument1 == null || argument.Argument2 == null) { throw new ArgumentException("The constructor of the base type should be called with anonymous values."); } if (test == null) { throw new ArgumentNullException(nameof(test)); } } } public class ParameterizedConstructorTestType { // to test duplicating with the SpecimenBuilder field of a dummy type. public static ISpecimenBuilder SpecimenBuilder = null; public ParameterizedConstructorTestType(object argument1, string argument2) { this.Argument1 = argument1; this.Argument2 = argument2; } public object Argument1 { get; } public string Argument2 { get; } } private class InternalProtectedConstructorTestConstraint<T> where T : InternalProtectedConstructorTestType { public InternalProtectedConstructorTestConstraint(T argument) { } } private class ModestConstructorTestConstraint<T> where T : ModestConstructorTestType { public ModestConstructorTestConstraint(T argument) { } } public abstract class ModestConstructorTestType { protected ModestConstructorTestType(object argument1, int argument2) { throw new InvalidOperationException("Should use the modest constructor."); } protected ModestConstructorTestType(object argument1, string argument2, int argument3) { throw new InvalidOperationException("Should use the modest constructor."); } protected ModestConstructorTestType(object argument) { } } public class NoAccessibleConstructorTestType { private NoAccessibleConstructorTestType() { } } private class NoAccessibleConstructorTestConstraint<T> where T : NoAccessibleConstructorTestType { public NoAccessibleConstructorTestConstraint(T argument) { } } public class DynamicInstanceTestConstraint<T> where T : IDynamicInstanceTestType { public void Method(T argument) { } } public interface IDynamicInstanceTestType { object Property { get; set; } int VoidMethod(object argument1, int argument2); int ReturnMethod(object argument1, int argument2); } private class UnclosedGenericMethodTestType<T1> where T1 : class { public void Method<T2, T3, T4>(T1 argument1, int argument2, T2 argument3, T3 argument4, T4 argument5) where T2 : class where T4 : class { if (argument1 == null) { throw new ArgumentNullException(nameof(argument1)); } if (argument3 == null) { throw new ArgumentNullException(nameof(argument3)); } if (argument5 == null) { throw new ArgumentNullException(nameof(argument5)); } } } private class ConstructorMatchTestType<T1, T2> where T1 : class { public ConstructorMatchTestType(T1 argument) { } public ConstructorMatchTestType(T1 argument1, T2 argument2) { } public ConstructorMatchTestType(T1 argument1, T1 argument2) { } public ConstructorMatchTestType(T2 argument1, object argument2) { } } private class MethodMatchTestType<T1, T2> where T1 : class { public MethodMatchTestType(T1 argument) { } public void Method(T1 argument) { } public void Method(T1 argument1, T2 argument2) { } public void Method(T2 argument1, object argument2) { } public void Method<T3>(T1 argument1, object argument2) where T3 : class { } public void Method<T3>(int argument1, T3 argument2) where T3 : class { } public void Method<T3>(T1 argument1, T3 argument2) where T3 : class { } } private class ByRefTestType<T1> where T1 : class { public ByRefTestType(T1 argument) { } public void Method(ref T1 argument) { } public void Method<T2>(ref T2 argument) where T2 : class { } public void Method(ref T1 argument1, int argument2) { } public void Method(T1 argument1, int argument2) { } } private class NestedGenericParameterTestType<T1, T2> { public NestedGenericParameterTestType(IEnumerable<T1> arg) { if (arg == null) throw new ArgumentNullException(nameof(arg)); } public NestedGenericParameterTestType(IEnumerable<IEnumerable<T2>> arg) { if (arg == null) throw new ArgumentNullException(nameof(arg)); } public NestedGenericParameterTestType(T1 arg1, Func<T1, IEnumerable<T2>> arg2) { if (arg2 == null) throw new ArgumentNullException(nameof(arg2)); } public NestedGenericParameterTestType(T1[] arg) { if (arg == null) throw new ArgumentNullException(nameof(arg)); } public NestedGenericParameterTestType(T1[,] arg) { if (arg == null) throw new ArgumentNullException(nameof(arg)); } public NestedGenericParameterTestType(T1[][] arg) { if (arg == null) throw new ArgumentNullException(nameof(arg)); } public NestedGenericParameterTestType(T1[,][][] arg) { if (arg == null) throw new ArgumentNullException(nameof(arg)); } public NestedGenericParameterTestType(Func<T1, IEnumerable<IEnumerable<T2>>, T1[][]> arg1, T2 arg2) { if (arg1 == null) throw new ArgumentNullException(nameof(arg1)); } } } }
using UnityEngine; namespace UnExt { public static class VectorExtensions { #region Vector3 extension methods /// <summary> /// Magnitude of the vector in the XZ plane. /// </summary> /// <param name="v">Vector to calculate the magnitude of.</param> /// <returns>The magnitude of v in the XZ plane.</returns> public static float magnitudeXZ(this Vector3 v) { return new Vector2( v.x, v.z ).magnitude; } /// <summary> /// Squared magnitude of the vector in the XZ plane. /// </summary> /// <param name="v">Vector to calculate the magnitude of.</param> /// <returns>The squared magnitude of v in the XZ plane.</returns> public static float sqrMagnitudeXZ(this Vector3 v) { return new Vector2( v.x, v.z ).sqrMagnitude; } /// <summary> /// Magnitude of the vector in the XY plane. /// </summary> /// <param name="v">Vector to calculate the magnitude of.</param> /// <returns>The magnitude of v in the XY plane.</returns> public static float magnitudeXY(this Vector3 v) { return new Vector2( v.x, v.y ).magnitude; } /// <summary> /// Squared magnitude of the vector in the XY plane. /// </summary> /// <param name="v">Vector to calculate the magnitude of.</param> /// <returns>The squared magnitude of v in the XY plane.</returns> public static float sqrMagnitudeXY(this Vector3 v) { return new Vector2( v.x, v.y ).sqrMagnitude; } /// <summary> /// Magnitude of the vector in the YZ plane. /// </summary> /// <param name="v">Vector to calculate the magnitude of.</param> /// <returns>The magnitude of v in the YZ plane.</returns> public static float magnitudeYZ(this Vector3 v) { return new Vector2( v.y, v.z ).magnitude; } /// <summary> /// Squared magnitude of the vector in the YZ plane. /// </summary> /// <param name="v">Vector to calculate the magnitude of.</param> /// <returns>The squared magnitude of v in the YZ plane.</returns> public static float sqrMagnitudeYZ(this Vector3 v) { return new Vector2( v.y, v.z ).sqrMagnitude; } /// <summary> /// Distance to a second point, in the XZ plane. /// </summary> /// <param name="v">Origin point.</param> /// <param name="u">Destination point.</param> /// <returns>The distance from origin to destination in the XZ plane.</returns> public static float distanceXZ(this Vector3 v, Vector3 u) { return (u - v).magnitudeXZ(); } /// <summary> /// Squared distance to a second point, in the XZ plane. /// </summary> /// <param name="v">Origin point.</param> /// <param name="u">Destination point.</param> /// <returns>The squared distance from origin to destination in the XZ plane.</returns> public static float sqrDistanceXZ(this Vector3 v, Vector3 u) { return (u - v).sqrMagnitudeXZ(); } /// <summary> /// Distance to a second point, in the XY plane. /// </summary> /// <param name="v">Origin point.</param> /// <param name="u">Destination point.</param> /// <returns>The distance from origin to destination in the XY plane.</returns> public static float distanceXY(this Vector3 v, Vector3 u) { return (u - v).magnitudeXY(); } /// <summary> /// Squared distance to a second point, in the XY plane. /// </summary> /// <param name="v">Origin point.</param> /// <param name="u">Destination point.</param> /// <returns>The squared distance from origin to destination in the XY plane.</returns> public static float sqrDistanceXY(this Vector3 v, Vector3 u) { return (u - v).sqrMagnitudeXY(); } /// <summary> /// Distance to a second point, in the YZ plane. /// </summary> /// <param name="v">Origin point.</param> /// <param name="u">Destination point.</param> /// <returns>The distance from origin to destination in the YZ plane.</returns> public static float distanceYZ(this Vector3 v, Vector3 u) { return (u - v).magnitudeYZ(); } /// <summary> /// Squared distance to a second point, in the YZ plane. /// </summary> /// <param name="v">Origin point.</param> /// <param name="u">Destination point.</param> /// <returns>The squared distance from origin to destination in the YZ plane.</returns> public static float sqrDistanceYZ(this Vector3 v, Vector3 u) { return (u - v).sqrMagnitudeYZ(); } /// <summary> /// Distance to a second point. /// </summary> /// <param name="v">Origin point.</param> /// <param name="u">Destination point.</param> /// <returns>The distance from origin to destination.</returns> public static float distance(this Vector3 v, Vector3 u) { return (u - v).magnitude; } /// <summary> /// Squared distance to a second point. /// </summary> /// <param name="v">Origin point.</param> /// <param name="u">Destination point.</param> /// <returns>The squared distance from origin to destination.</returns> public static float sqrDistance(this Vector3 v, Vector3 u) { return (u - v).sqrMagnitude; } /// <summary> /// Calculate the projection of a vector into the plane defined by the given normal /// and containing the origin. /// </summary> /// <param name="v">Vector to project.</param> /// <param name="normal">Normal defining the plane to project on.</param> /// <returns>The vector resulting from projecting v on the plane.</returns> public static Vector3 Project(this Vector3 v, Vector3 normal) { return v - v.Dot( normal ) * normal; } /// <summary> /// Project this point into a plane defined by the given position and rotation. /// </summary> /// <param name="v"></param> /// <param name="position">Reference position of the plane.</param> /// <param name="rotation">Rotation of the plane.</param> /// <returns>The point's projection into the plane.</returns> public static Vector3 Project(this Vector3 v, Vector3 position, Quaternion rotation) { var localv = rotation.Inverse() * v; var localPos = rotation.Inverse() * position; localv.z = localPos.z; return rotation * localv; } /// <summary> /// Calculate the magnitude of a vector's projection on an arbitrary plane. /// </summary> /// <param name="v"></param> /// <param name="normal">Normal defining the plane to project on.</param> /// <returns>The magnitude of the vector's projection on the plane.</returns> public static float magnitude(this Vector3 v, Vector3 normal) { return v.Project( normal ).magnitude; } /// <summary> /// Calculate the squared magnitude of a vector's projection on an arbitrary plane. /// </summary> /// <param name="v"></param> /// <param name="normal">Normal defining the plane to project on.</param> /// <returns>The squared magnitude of the vector's projection on the plane.</returns> public static float sqrMagnitude(this Vector3 v, Vector3 normal) { return v.Project( normal ).sqrMagnitude; } /// <summary> /// Calculate the distance between two points' projections on an arbitrary plane. /// </summary> /// <param name="v"></param> /// <param name="normal">Normal defining the plane to project on.</param> /// <returns>The distance between the two points on the plane.</returns> public static float distance(this Vector3 v, Vector3 u, Vector3 normal) { return v.distance( u, Vector3.zero, Quaternion.LookRotation( normal ) ); } /// <summary> /// Calculate the distance between two point's projections on a plane. /// </summary> /// <param name="v"></param> /// <param name="u"></param> /// <param name="planePos">An arbitrary point inside the plane.</param> /// <param name="planeRot">The plane's rotation.</param> /// <returns>The distance of both points' projection in the plane.</returns> public static float distance(this Vector3 v, Vector3 u, Vector3 planePos, Quaternion planeRot) { var localv = v.Project( planePos, planeRot ); var localu = u.Project( planePos, planeRot ); return localv.distance( localu ); } /// <summary> /// Calculate the squared distance between two points' projections on an arbitrary plane. /// </summary> /// <param name="v"></param> /// <param name="normal">Normal defining the plane to project on.</param> /// <returns>The squared distance between the two points on the plane.</returns> public static float sqrDistance(this Vector3 v, Vector3 u, Vector3 normal) { var localv = v.Project( normal ); var localu = u.Project( normal ); return localv.distance( localu ); } /// <summary> /// Calculate the squared distance between two point's projections on a plane. /// </summary> /// <param name="v"></param> /// <param name="u"></param> /// <param name="planePos">An arbitrary point inside the plane.</param> /// <param name="planeRot">The plane's rotation.</param> /// <returns>The squared distance of both points' projection in the plane.</returns> public static float sqrDistance(this Vector3 v, Vector3 u, Vector3 planePos, Quaternion planeRot) { var localv = v.Project( planePos, planeRot ); var localu = u.Project( planePos, planeRot ); return localv.sqrDistance( localu ); } /// <summary> /// Calculate the dot product of a couple of vectors. /// i.e. the product of their magnitudes and the cosine between both vectors. /// </summary> /// <param name="v"></param> /// <param name="u"></param> /// <returns>The dot product of v and u.</returns> public static float Dot(this Vector3 v, Vector3 u) { return Vector3.Dot( v, u ); } /// <summary> /// Calculate the cross product of two vectors. /// i.e. a vector pointing in the direction of the normal /// of the plane defined by both vectors, following the lowest angle between both, /// and of magnitude the area of the parallelogram with both vectors as its sides. /// </summary> /// <param name="v"></param> /// <param name="u"></param> /// <returns>The cross product of v and u.</returns> public static Vector3 Cross(this Vector3 v, Vector3 u) { return Vector3.Cross( v, u ); } /// <summary> /// Rotate a point around the origin. /// </summary> /// <param name="point">Vector to rotate.</param> /// <param name="angle">Angle to rotate.</param> /// <returns>The result of rotating point.</returns> public static Vector3 Rotate(this Vector3 point, Quaternion angle) { return angle * point; } /// <summary> /// Rotate a point around another. /// </summary> /// <param name="point">Point to rotate.</param> /// <param name="origin">Reference for rotation.</param> /// <param name="angle">Angle to rotate.</param> /// <returns>The result of rotating point around origin.</returns> public static Vector3 RotateAround(this Vector3 point, Vector3 origin, Quaternion angle) { return angle * (point - origin) + origin; } /// <summary> /// Change a point's base to a reference's local space. /// </summary> /// <param name="point">Point to transform.</param> /// <param name="refPoint">World space centre of new base.</param> /// <param name="refRotation">World space rotation of new base.</param> /// <returns>The position of the point in the new base.</returns> public static Vector3 InverseTransformPoint(this Vector3 point, Vector3 refPoint, Quaternion refRotation) { return point.RotateAround(refPoint, refRotation.Inverse()) - refPoint; } /// <summary> /// Change a point's base to world space from a reference base. /// </summary> /// <param name="point">Point to transform.</param> /// <param name="refPoint">World space centre of point's current base.</param> /// <param name="refRotation">World space rotation of point's current base.</param> /// <returns>The position of the point in world space.</returns> public static Vector3 TransformPoint(this Vector3 point, Vector3 refPoint, Quaternion refRotation) { return (point + refPoint).RotateAround(refPoint, refRotation); } /// <summary> /// Calculate the angle, in degrees, between a vector and a point. /// The point of reference is (0, 0, 0), with angle calculated from direction. /// </summary> /// <param name="direction">Direction vector. It indicates the direction from which to measure the angle.</param> /// <param name="point">Point to measure the angle to.</param> /// <returns>The angle from the vector to the point, in degrees, in the range [-180, 180].</returns> public static float AngleTo(this Vector3 direction, Vector3 point) { return Vector3.Angle(direction, point); } #endregion #region Vector2 extension methods /// <summary> /// Distance to a second point. /// </summary> /// <param name="v">Origin point.</param> /// <param name="u">Destination point.</param> /// <returns>The distance from origin to destination.</returns> public static float distance(this Vector2 v, Vector2 u) { return (u - v).magnitude; } /// <summary> /// Squared distance to a second point. /// </summary> /// <param name="v">Origin point.</param> /// <param name="u">Destination point.</param> /// <returns>The squared distance from origin to destination.</returns> public static float sqrDistance(this Vector2 v, Vector2 u) { return (u - v).sqrMagnitude; } /// <summary> /// Rotate a Vector2. /// </summary> /// <param name="point">Vector to rotate.</param> /// <param name="angle">Angle to rotate.</param> /// <returns>The result of rotating point.</returns> public static Vector2 Rotate(this Vector2 point, Quaternion angle) { Vector3 point3 = new Vector3( point.x, 0, point.y ); point3 = angle * point3; return new Vector2( point3.x, point3.z ); } /// <summary> /// Rotate around a given point. /// </summary> /// <param name="point">Point to rotate.</param> /// <param name="origin">Reference for rotation.</param> /// <param name="angle">Angle to rotate.</param> /// <returns>The result of rotating point around origin.</returns> public static Vector2 RotateAround(this Vector2 point, Vector2 origin, Quaternion angle) { Vector3 point3 = new Vector3( point.x, 0, point.y ); Vector3 origin3 = new Vector3( origin.x, 0, origin.y ); point3 = angle * (point3 - origin3) + origin3; return new Vector2( point3.x, point3.z ); } /// <summary> /// Calculate two vector's dot product. Sugar for <see cref="Vector2.Dot(Vector2, Vector2)"/> /// </summary> /// <param name="v"></param> /// <param name="u"></param> /// <returns>The vector's dot product.</returns> public static float Dot(this Vector2 v, Vector2 u) { return Vector2.Dot( v, u ); } #endregion } }
// // JSONNumber.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using UnityEngine; using System; using System.Text; namespace AssemblyCSharp { /// <summary> /// JSON numeric value. Note that this differs from standard JSON in that we keep track of unsigned vs signed int values. /// </summary> public class JSONNumber : JSONValue { #region Constants public enum eNumericType { Integer, UnsignedInteger, Float, Long, UnsignedLong, } #endregion #region Properties public eNumericType Type { get{ return mType; } } public int IntValue { get{ switch (Type) { case eNumericType.Float: return (int)mFloatValue; case eNumericType.Integer: return mIntValue; case eNumericType.UnsignedInteger: return (int)mUintValue; case eNumericType.Long: return (int)mLongValue; case eNumericType.UnsignedLong: return (int)mULongValue; default: Debug.LogError("Invalid JSON numeric type"); break; } return 0; } set{ mType = eNumericType.Integer; mIntValue = value; } } public uint UintValue { get{ switch (Type) { case eNumericType.Float: return (uint)mFloatValue; case eNumericType.Integer: return (uint)mIntValue; case eNumericType.UnsignedInteger: return mUintValue; case eNumericType.Long: return (uint)mLongValue; case eNumericType.UnsignedLong: return (uint)mULongValue; default: Debug.LogError("Invalid JSON numeric type"); break; } return 0; } set{ mType = eNumericType.UnsignedInteger; mUintValue = value; } } public long LongValue { get{ switch (Type) { case eNumericType.Float: return (long)mFloatValue; case eNumericType.Integer: return mIntValue; case eNumericType.UnsignedInteger: return (long)mUintValue; case eNumericType.Long: return mLongValue; case eNumericType.UnsignedLong: return (long)mULongValue; default: Debug.LogError("Invalid JSON numeric type"); break; } return 0; } set{ mType = eNumericType.Long; mLongValue = value; } } public ulong ULongValue { get{ switch (Type) { case eNumericType.Float: return (ulong)mFloatValue; case eNumericType.Integer: return (ulong)mIntValue; case eNumericType.UnsignedInteger: return mUintValue; case eNumericType.Long: return (ulong)mLongValue; case eNumericType.UnsignedLong: return mULongValue; default: Debug.LogError("Invalid JSON numeric type"); break; } return 0; } set{ mType = eNumericType.UnsignedLong; mULongValue = value; } } public float FloatValue { get{ switch (Type) { case eNumericType.Float: return mFloatValue; case eNumericType.Integer: return (float)mIntValue; case eNumericType.UnsignedInteger: return (float)mUintValue; case eNumericType.Long: return (float)mLongValue; case eNumericType.UnsignedLong: return (float)mULongValue; default: Debug.LogError("Invalid JSON numeric type"); break; } return 0; } set{ mType = eNumericType.Float; mFloatValue = value; } } #endregion #region Methods public JSONNumber () { mType = eNumericType.Integer; mIntValue = 0; mUintValue = 0; mLongValue = 0; mULongValue = 0; mFloatValue = 0; } public JSONNumber (int value) { IntValue = value; } public JSONNumber (uint value) { UintValue = value; } public JSONNumber (long value) { LongValue = value; } public JSONNumber (ulong value) { ULongValue = value; } public JSONNumber (float value) { FloatValue = value; } public JSONNumber (StringBuilder data) { Decode(data); } public void Decode(StringBuilder data) { while (Char.IsWhiteSpace(data[0])) data.Remove(0, 1); // NOTE: not allowing spaces in a number mType = eNumericType.Integer; bool isNegative = false; ulong ivalue = 0; float fvalue = 0; if (data[0] == '-') { isNegative = true; data.Remove(0, 1); } while (Char.IsDigit(data[0])) { ivalue = ivalue * 10 + (ulong)(data[0] - '0'); data.Remove(0, 1); } if (data[0] == '.') { data.Remove(0, 1); if (Char.IsDigit(data[0])) { mType = eNumericType.Float; fvalue = ivalue; float fraction = 0.1f; while (Char.IsDigit(data[0])) { fvalue += (data[0] - '0') * fraction; fraction *= .1f; data.Remove(0, 1); } mFloatValue = fvalue; } else throw new InvalidJSONException(); } float multiplier = 1.0f; if (data[0] == 'e' || data[0] == 'E') { data.Remove(0, 1); int exponential = 0; bool isExponentialNegative = false; if (data[0] == '+') data.Remove(0, 1); else if (data[0] == '-') { data.Remove(0, 1); isExponentialNegative = true; } if (!Char.IsDigit(data[0])) throw new InvalidJSONException(); while (Char.IsDigit(data[0])) { exponential = exponential * 10 + (data[0] - '0'); data.Remove(0, 1); } if (isExponentialNegative) exponential = -exponential; multiplier = (float)Math.Pow(10.0, (float)exponential); } if (mType != eNumericType.Float && multiplier >= 1) { ivalue *= (ulong)multiplier; if (!isNegative) { if (ivalue > uint.MaxValue) { mType = eNumericType.UnsignedLong; mULongValue = ivalue; } else { mType = eNumericType.UnsignedInteger; mUintValue = (uint)ivalue; } } else { if (ivalue > int.MaxValue) { mType = eNumericType.Long; mLongValue = (long)ivalue; mLongValue = -mLongValue; } else { mType = eNumericType.Integer; mIntValue = (int)ivalue; mIntValue = -mIntValue; } } } else { if (mType != eNumericType.Float) { mType = eNumericType.Float; mFloatValue = (float)ivalue; } mFloatValue *= multiplier; if (isNegative) mFloatValue = -mFloatValue; } } public void Encode(StringBuilder data) { switch (mType) { case eNumericType.Float: data.Append(mFloatValue); break; case eNumericType.Integer: data.Append(mIntValue); break; case eNumericType.UnsignedInteger: data.Append(mUintValue); break; case eNumericType.Long: data.Append(mLongValue); break; case eNumericType.UnsignedLong: data.Append(mULongValue); break; } } #endregion #region Members private eNumericType mType; private int mIntValue; private uint mUintValue; private long mLongValue; private ulong mULongValue; private float mFloatValue; #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 Microsoft.Cci; using Microsoft.Tools.Transformer.CodeModel; using System; using System.Collections.Generic; using System.Diagnostics; namespace Thinner { //public interface IApiInformationProvider //{ // bool IsFrameworkInternal(INamedTypeDefinition type); // bool IsFrameworkInternal(ITypeDefinitionMember member); //} public class ImplementationModel /*: IApiInformationProvider*/ { //TODO: remove all direct references to AssembliesClosure, MembersClosure, MethodsClosure and TypesClosure // instead we should use public methods on ClosureDepot. //TODO: combine MembersClosure and MethodsClosure if we can find an universal way to compare CCI2 objects private class ClosureDepot { private Queue<IReference> _workList; private Dictionary<String, IAssembly> _assembliesClosure; private Dictionary<uint, INamedTypeDefinition> _typesClosure; private Dictionary<String, IAliasForType> _typeForwardersClosure; private Dictionary<ITypeDefinitionMember, object> _membersClosure; private Dictionary<uint, IMethodDefinition> _methodsClosure; public Queue<IReference> WorkList { get { return _workList; } } public Dictionary<String, IAssembly> AssembliesClosure { get { return _assembliesClosure; } } public Dictionary<uint, INamedTypeDefinition> TypesClosure { get { return _typesClosure; } } public Dictionary<String, IAliasForType> TypeForwardersClosure { get { return _typeForwardersClosure; } } public Dictionary<ITypeDefinitionMember, object> MembersClosure { get { return _membersClosure; } } public Dictionary<uint, IMethodDefinition> MethodsClosure { get { return _methodsClosure; } } public ClosureDepot() { _workList = new Queue<IReference>(); _typeForwardersClosure = new Dictionary<String, IAliasForType>(); _assembliesClosure = new Dictionary<String, IAssembly>(); _typesClosure = new Dictionary<uint, INamedTypeDefinition>(); _membersClosure = new /*HashSet*/Dictionary<ITypeDefinitionMember, object>(); _methodsClosure = new Dictionary<uint, IMethodDefinition>(); } public void AddAssemblyReference(IAssemblyReference assembly) { if (null == assembly) return; IAssembly assemblyDef = assembly.ResolvedAssembly; if (!AssembliesClosure.ContainsKey(assemblyDef.Name.Value)) { AssembliesClosure.Add(assemblyDef.Name.Value, assemblyDef); _workList.Enqueue(assemblyDef); } } public bool ContainsAssembly(IAssembly assembly) { return AssembliesClosure.ContainsValue(assembly); } public bool AddTypeReference(INamedTypeReference type) { // TODO: Optionally add all members for interfaces, and add all abstract members for abstract classes INamedTypeDefinition typeDef = Util.ResolveTypeThrowing(type); IAssembly assembly = TypeHelper.GetDefiningUnit(typeDef) as IAssembly; AddAssemblyReference(assembly); if (!TypesClosure.ContainsKey(typeDef.InternedKey)) { TypesClosure.Add(typeDef.InternedKey, typeDef); _workList.Enqueue(typeDef); if (Util.IsDelegateType(typeDef)) { foreach (ITypeDefinitionMember member in typeDef.Members) { AddMemberReference(member); } } return true; } return false; } public bool AddTypeForwarder(IAliasForType alias) { String signature = Util.GetTypeForwarderSignature(alias); if (!TypeForwardersClosure.ContainsKey(signature)) { TypeForwardersClosure.Add(signature, alias); _workList.Enqueue(alias); return true; } return false; } public bool ContainsType(INamedTypeDefinition typeDef) { return TypesClosure.ContainsKey(typeDef.InternedKey); } public void AddMemberReference(ITypeMemberReference member) { if (null == member) return; ITypeDefinitionMember memberDef = Util.CanonicalizeMember(member); if (memberDef == Dummy.Method || memberDef == Dummy.Field || memberDef == Dummy.Property || memberDef == Dummy.Event || memberDef == Dummy.Type) throw new Exception("Cannot add Dummy member"); // CanonicalizeMember(ITypeDefinitionMember) ensures that member.ContainingType should always be non-null AddTypeReference(Util.ContainingTypeDefinition(memberDef)); IMethodDefinition methodDef = memberDef as IMethodDefinition; if (methodDef != null) { if (!_methodsClosure.ContainsKey(methodDef.InternedKey)) { _methodsClosure.Add(methodDef.InternedKey, methodDef); _workList.Enqueue(methodDef); } } else { // TODO: Always add accessors for events and properties? IEventDefinition eventDef = member as IEventDefinition; IPropertyDefinition propertyDef = member as IPropertyDefinition; if (eventDef != null) { foreach (IMethodReference method in eventDef.Accessors) { AddMemberReference(method); } } if (propertyDef != null) { foreach (IMethodReference method in propertyDef.Accessors) { AddMemberReference(method); } } if (!_membersClosure.ContainsKey(memberDef)) { _membersClosure.Add(memberDef, null); _workList.Enqueue(memberDef); } } } public bool ContainsMember(ITypeDefinitionMember member) { IMethodDefinition method = member as IMethodDefinition; if (method != null) return _methodsClosure.ContainsKey(method.InternedKey); else return _membersClosure.ContainsKey(member); } } private ClosureDepot _depot; private Dictionary<IAssembly, ThinAssembly> _rootAssemblies; private Dictionary<INamedTypeDefinition, ThinType> _rootTypes; private Dictionary<IAliasForType, ThinTypeForwarder> _rootTypeForwarders; private Dictionary<ITypeDefinitionMember, ThinMember> _rootMembers; private List<ThinMember> _missingMembers; private ThinModel _thinModel; //private HostEnvironment m_hostEnvironment; public ThinnerOptions Options { get { return _thinModel.Options; } } //IClosureVisitor visitor; private IncludeStatus _closureStatus; public ImplementationModel(ThinModel thinModel) { _thinModel = thinModel; _depot = new ClosureDepot(); _rootAssemblies = new Dictionary<IAssembly, ThinAssembly>(); _rootTypes = new Dictionary<INamedTypeDefinition, ThinType>(); _rootTypeForwarders = new Dictionary<IAliasForType, ThinTypeForwarder>(); _rootMembers = new Dictionary<ITypeDefinitionMember, ThinMember>(); _missingMembers = new List<ThinMember>(); } public virtual void AddAssemblyReference(IAssemblyReference assembly) { Debug.Assert(CanIncludeAssembly(assembly.AssemblyIdentity)); _depot.AddAssemblyReference(assembly); } public virtual void AddTypeReference(INamedTypeReference type) { Debug.Assert(CanInclude(type)); _depot.AddTypeReference(type); } public virtual void AddTypeForwarderReference(IAliasForType alias) { _depot.AddTypeForwarder(alias); } public virtual void AddMemberReference(ITypeDefinitionMember member) { Debug.Assert(CanInclude(Util.CanonicalizeTypeReference(member.ContainingType))); Debug.Assert(member == Util.CanonicalizeMember(member)); _depot.AddMemberReference(member); //if (!(member is IFieldDefinition && member.Name.Value.Equals("value__"))) //{ // _depot.AddMemberReference(member); //} //else //{ // // TODO: "value__" field accesses here. are those "this" pointer accesses? // // For now just ignore them. They could theoretically be used to make classic static when // // none of their instance methods are used. //} } public virtual bool HasWorkToDo() { return (_depot.WorkList.Count > 0); } public virtual IReference Dequeue() { return _depot.WorkList.Dequeue(); } public void ImportRoots(IncludeStatus rootType) { ImportWorker(rootType, AddRootAssembly, AddRootType, AddRootTypeForwarder, AddRootMember); } //@TODO: CLEAN THIS UP NOW THAT WE DON'T NEED THE DELEGATES private delegate void AddAssembly(ThinAssembly assembly); private delegate void AddType(ThinType type); private delegate void AddTypeForwarder(ThinTypeForwarder type); private delegate void AddMember(ThinMember member); private void AddRootAssembly(ThinAssembly assembly) { if (!_rootAssemblies.ContainsKey(assembly.Metadata)) _rootAssemblies.Add(assembly.Metadata, assembly); } private void AddRootType(ThinType type) { if (!_rootTypes.ContainsKey(type.Metadata)) _rootTypes.Add(type.Metadata, type); } private void AddRootTypeForwarder(ThinTypeForwarder typeForwarder) { if (!_rootTypeForwarders.ContainsKey(typeForwarder.Metadata)) _rootTypeForwarders.Add(typeForwarder.Metadata, typeForwarder); } private void AddRootMember(ThinMember member) { if (member.Metadata == null) { if (!_missingMembers.Contains(member)) _missingMembers.Add(member); } else { if (!_rootMembers.ContainsKey(member.Metadata)) _rootMembers.Add(member.Metadata, member); } } private void ImportWorker(IncludeStatus statusToImport, AddAssembly addAssembly, AddType addType, AddTypeForwarder addTypeForwarder, AddMember addMember) { foreach (ThinAssembly assembly in _thinModel.Assemblies.Values) { if (assembly.IncludeStatus == statusToImport) addAssembly(assembly); foreach (ThinTypeForwarder typeForwarder in assembly.TypeForwarders.Values) { if (typeForwarder.IncludeStatus == statusToImport) { // Assembly may not have already been added because they might not have the correct IncludedStatus. addAssembly(assembly); addTypeForwarder(typeForwarder); } } foreach (ThinType type in assembly.Types.Values) { if (type.IncludeStatus == statusToImport) { // Assembly may not have already been added because they might not have the correct IncludedStatus. addAssembly(assembly); addType(type); } foreach (ThinMember member in type.Members.Values) { if (member.IncludeStatus == statusToImport) { // Assembly and Type may not have already been added because they might not have the correct IncludedStatus. addAssembly(assembly); addType(type); addMember(member); } } } } } public void PrintStats() { Console.WriteLine("root assemblies: {0}", _rootAssemblies.Count); Console.WriteLine("root types: {0}", _rootTypes.Count); Console.WriteLine("root type forwarders: {0}", _rootTypeForwarders.Count); Console.WriteLine("root members: {0}", _rootMembers.Count); } private void Validate(IClosureVisitor visitor) { //Queue<IReference> workList = visitor.WorkList; //_assembliesClosure = visitor.AssembliesClosure; //_typesClosure = visitor.TypesClosure; //_membersClosure = visitor.MembersClosure; //_methodsClosure = visitor.MethodsClosure; // // seed the work list and closures with our roots // // NOTE: the pattern here is that whenever you add a node // to the work list, it must also be added to the appropriate // closure at the same time. Adding to the work list will // cause the node to be visited, at which time, the visitor // is supposed to find all *other* references that that node // draws into the closure and adds them to the worklist and // closure at that time. foreach (IAssembly assembly in _rootAssemblies.Keys) { AddAssemblyReference(assembly); } foreach (INamedTypeDefinition type in _rootTypes.Keys) { AddTypeReference(type); } foreach (IAliasForType typeForwarder in _rootTypeForwarders.Keys) { AddTypeForwarderReference(typeForwarder); } foreach (ITypeDefinitionMember member in _rootMembers.Keys) { AddMemberReference(member); } int loopIterations = 0; while (HasWorkToDo()) { //Console.WriteLine("iterations: {0}, queue length: {1}", loopIterations, workList.Count); loopIterations++; ProcessWorkList(visitor); GenerateWorkForVirtuals(visitor); } // TODO: we should not need this if we have authored model.xml correctly. // e.g. we should have included MulticaseDelegate..ctor(object, string) and // CodeAccessSecurityAttribute..ctor(SecurityAction) GenerateWorkForCtors(visitor); while (HasWorkToDo()) { //Console.WriteLine("iterations: {0}, queue length: {1}", loopIterations, workList.Count); loopIterations++; ProcessWorkList(visitor); GenerateWorkForCtors(visitor); } } private void GenerateWorkForVirtuals(IClosureVisitor visitor) { INamedTypeDefinition[] defs = new INamedTypeDefinition[_depot.TypesClosure.Values.Count]; _depot.TypesClosure.Values.CopyTo(defs, 0); foreach (INamedTypeDefinition type in defs) { GenerateWorkForVirtuals(type, visitor); } } private void GenerateWorkForCtors(IClosureVisitor visitor) { foreach (INamedTypeDefinition type in _depot.TypesClosure.Values) { GenerateWorkForCtors(type, visitor); } } private void GenerateWorkForVirtuals(INamedTypeDefinition type, IClosureVisitor visitor) { // TODO: can we use INamedTypeDefinition.ExplicitImplementationOverrides instead? //foreach (IMethodImplementation methodImpl in type.ExplicitImplementationOverrides) //{ // ITypeReference declType = methodImpl.ImplementedMethod.ContainingType; // if (_depot.TypesClosure.ContainsKey(declType.ResolvedType.InternedKey)) // { // AddMemberReference(methodImpl); // } //} // TODO: Events? foreach (ITypeDefinitionMember member in type.Members) { IMethodDefinition method = member as IMethodDefinition; IPropertyDefinition property = member as IPropertyDefinition; IEventDefinition eventDef = member as IEventDefinition; if (((method == null) || !method.IsVirtual) && ((property == null) || !Util.IsPropertyVirtual(property)) && ((eventDef == null) || !Util.IsEventVirtual(eventDef))) { continue; } // // If this or any related member on a base type or interface is in the closure, // we must ensure that all related members are also in the closure. // bool includeRelatedMembers = false; List<ITypeDefinitionMember> relatedMembers = Util.FindRelatedMembers(member, delegate (INamedTypeReference myType) { return _depot.TypesClosure.ContainsKey(myType.InternedKey) || !CanInclude(myType); } ); foreach (ITypeDefinitionMember m in relatedMembers) { ITypeDefinitionMember specializedMember = Util.CanonicalizeMember(m); if (_depot.ContainsMember(specializedMember) || !CanInclude(Util.CanonicalizeType(specializedMember.ContainingType))) includeRelatedMembers = true; } if (includeRelatedMembers) { foreach (ITypeDefinitionMember m in relatedMembers) { INamedTypeDefinition canonicalDeclaringType = Util.CanonicalizeType(m.ContainingType); if (CanInclude(canonicalDeclaringType)) { // TODO: Won't AddMemberReference add the type definition anyway? // Since these members could have resolved to another assembly, check whether we can include them. if (!_depot.TypesClosure.ContainsKey(canonicalDeclaringType.InternedKey)) Console.Error.WriteLine("ERROR: declaring type {0} of {1} not present in closure", canonicalDeclaringType, m); AddMemberReference(Util.CanonicalizeMember(m)); } } } } } private List<IMethodDefinition> GetCtors(INamedTypeDefinition type, bool includedCtorOnly) { List<IMethodDefinition> ctors = new List<IMethodDefinition>(); foreach (IMethodDefinition meth in type.Methods) { if (meth.IsConstructor && (_depot.MethodsClosure.ContainsKey(meth.InternedKey) || !includedCtorOnly)) { ctors.Add(meth); } } return ctors; } // // Some types may have base types with no default ctors // and no ctors themselves. In those cases, the compiler // cannot instantiate the type without an explicit ctor // that calls one of the included base type ctors. // private void GenerateWorkForCtors(INamedTypeDefinition type, IClosureVisitor visitor) { if (TypeHelper.BaseClass(type) == null) return; List<IMethodDefinition> ctors = GetCtors(type, true); if (ctors.Count != 0) return; List<IMethodDefinition> baseCtors = GetCtors(Util.CanonicalizeType(TypeHelper.BaseClass(type)), true); if (baseCtors.Count == 0) return; int nDefaultCtors = 0; foreach (IMethodDefinition ctor in baseCtors) { if (Util.ParameterCount(ctor) == 0) { nDefaultCtors++; } } if (nDefaultCtors != 0) return; // TODO: Shouldn't this be part of implclosure? ctors = GetCtors(type, false); foreach (IMethodDefinition baseCtor in baseCtors) { foreach (IMethodDefinition ctor in ctors) { if (MethodCallsMethod(ctor, baseCtor)) { AddMemberReference(ctor); return; // @TODO: we may need to add more than just the first one we find.. } } } // at this point, no included ctor in the base type is // being called by any of the ctors in the derived type // so we have to get a little more creative if (ctors.Count > 0) { IMethodDefinition fallback = FindCalledBaseCtor(ctors[0]); if (null != fallback) { AddMemberReference(ctors[0]); AddMemberReference(fallback); } } } private class CalledBaseCtorFinder : MetadataTraverser { private IMethodDefinition _baseCtor; private INamedTypeDefinition _targetType; public CalledBaseCtorFinder(IMethodDefinition ctor) { _targetType = Util.CanonicalizeType(TypeHelper.BaseClass(Util.ContainingTypeDefinition(ctor))); _baseCtor = null; } // This is never called. //public override Expression VisitMethodCall(MethodCall call) //{ // InstanceInitializer ctor = ((MemberBinding)call.Callee).BoundMember as InstanceInitializer; // if ((ctor != null) && (ctor.ContainingType == _targetType)) // { // if (_baseCtor != null) // throw new Exception("_baseCtor should be null here!"); // _baseCtor = ctor; // } // return base.VisitMethodCall(call); //} public IMethodDefinition BaseCtor { get { return _baseCtor; } } } public static IMethodDefinition FindCalledBaseCtor(IMethodDefinition ctor) { CalledBaseCtorFinder finder = new CalledBaseCtorFinder(ctor); finder.TraverseChildren(ctor); return finder.BaseCtor; } private class MethodCallFinder : MetadataTraverser { private bool _found; private IMethodDefinition _callee; public MethodCallFinder(IMethodDefinition callee) { _found = false; _callee = callee; } public bool Found { get { return _found; } } public override void TraverseChildren(IMethodDefinition method) { base.TraverseChildren(method.Body); } public override void TraverseChildren(IOperation operation) { IMethodReference methodReference = operation.Value as IMethodReference; if (methodReference != null) { IMethodDefinition method = methodReference.ResolvedMethod; if (method != null && method.InternedKey == _callee.InternedKey) { _found = true; //return; } } // TODO: Do we need this? // base.Visit(operation); } } // // if caller directly calls callee, return true // public static bool MethodCallsMethod(IMethodDefinition caller, IMethodDefinition callee) { MethodCallFinder finder = new MethodCallFinder(callee); finder.TraverseChildren(caller); return finder.Found; } private void ProcessWorkList(IClosureVisitor visitor) { // // walk the closure of each item in the list // int loopIterations = 0; while (HasWorkToDo()) { IReference node = Dequeue(); visitor.VisitNode(node); loopIterations++; } } public void CalculateImplementationClosure(bool isCSharp, FieldOptions fieldOptions) { ImplClosureVisitor visitor = new ImplClosureVisitor(this, new ImplClosureVisitorOptions(true, fieldOptions)); Validate(visitor); } public void CalculateApiClosure() { ApiClosureVisitor visitor = new ApiClosureVisitor(this); Validate(visitor); } public void CalculateClosure(ClosureVisitor visitor) { Validate(visitor); } private IncludeStatus GetIncludeStatus(IAssembly assembly) { ThinAssembly modelAssembly; if (!_rootAssemblies.TryGetValue(assembly, out modelAssembly)) { if (_depot.ContainsAssembly(assembly)) return _closureStatus; throw new Exception("could not find IncludeStatus for assembly " + assembly.ToString()); } return modelAssembly.IncludeStatus; } private IncludeStatus GetIncludeStatus(INamedTypeDefinition type) { ThinType modelType; if (!_rootTypes.TryGetValue(type, out modelType)) { if (_depot.TypesClosure.ContainsKey(type.InternedKey)) { // Special case ImplRoot // TODO: Visitor should set status instead. if (_closureStatus == IncludeStatus.ApiRoot && !Util.IsTypeExternallyVisible(type)) { return IncludeStatus.ImplRoot; } return _closureStatus; } return IncludeStatus.Exclude; } return modelType.IncludeStatus; } private IncludeStatus GetIncludeStatus(ITypeDefinitionMember member) { ThinMember modelMember; if (!_rootMembers.TryGetValue(member, out modelMember)) { if (_depot.ContainsMember(member)) { // Special case ImplRoot // TODO: Visitor should set status instead. if (_closureStatus == IncludeStatus.ApiRoot && !Util.IsMemberExternallyVisible(member)) { return IncludeStatus.ImplRoot; } return _closureStatus; } throw new Exception("could not find IncludeStatus for member " + member.ToString()); } return modelMember.IncludeStatus; } private bool IsHiddenTypeCandidate(INamedTypeDefinition type) { return !Util.IsApi(GetIncludeStatus(type)) && Util.IsTypeExternallyVisible(type); } private bool IsHiddenMemberCandidate(ITypeDefinitionMember member) { return !Util.IsApi(GetIncludeStatus(member)) && Util.IsMemberExternallyVisible(member); } private bool ShouldHideType(INamedTypeDefinition type) { return IsHiddenTypeCandidate(type); } private bool WeHidThisType(INamedTypeDefinition type) { // walk up all the declaring types to see if we hid one of them INamedTypeDefinition curType = type; while (curType != null && curType != Dummy.Type) { if (ShouldHideType(curType)) return true; INestedTypeDefinition nestedType = curType as INestedTypeDefinition; if (nestedType != null) curType = Util.CanonicalizeType(nestedType.ContainingType); else curType = null; } return false; } private bool TypeIsVisibleInApi(INamedTypeDefinition type) { // either we hid it or its already hidden // @TODO: what about private types? return !WeHidThisType(type) && Util.IsTypeExternallyVisible(type); } private bool ShouldHideMember(ITypeDefinitionMember member) { bool shouldHide = false; INamedTypeDefinition type = Util.ContainingTypeDefinition(member); if (IsHiddenMemberCandidate(member)) { if (!TypeIsVisibleInApi(type)) { // Declaring type is hidden, only modify the visibility on a // member when its corresponding member on a public base type // was hidden. INamedTypeDefinition baseType = Util.CanonicalizeType(TypeHelper.BaseClass(type)); while (baseType != null && baseType != Dummy.Type) { if (TypeIsVisibleInApi(baseType)) { ITypeDefinitionMember relatedMember = Util.FindRelatedMember(baseType, member); if (relatedMember != null) { ITypeDefinitionMember canonicalizedRelatedMember = Util.CanonicalizeMember(relatedMember); if (_depot.ContainsMember(canonicalizedRelatedMember) && ShouldHideMember(canonicalizedRelatedMember)) { shouldHide = true; break; } } } baseType = Util.CanonicalizeType(TypeHelper.BaseClass(baseType)); } } else { // declaring type is public, we must hide the member. shouldHide = true; } } return shouldHide; } // Special case: If closureStatus == ApiRoot this will automatically // convert it to ImplRoot for internal types // TODO: Visitor should set status instead of this. public ThinModel ExportModel(IncludeStatus closureStatus) { _closureStatus = closureStatus; int nApiTypes = 0; int nApiTypeForwarders = 0; int nApiMembers = 0; ThinModel thinModel = new ThinModel(_thinModel.Options); Dictionary<String, ThinAssembly> assemblies = new Dictionary<String, ThinAssembly>(_depot.AssembliesClosure.Count); Dictionary<INamedTypeDefinition, ThinType> types = new Dictionary<INamedTypeDefinition, ThinType>(_depot.TypesClosure.Count); foreach (IAssembly assembly in _depot.AssembliesClosure.Values) { ThinAssembly thinAsm = new ThinAssembly(_thinModel, assembly.Name.Value, GetIncludeStatus(assembly), assembly); thinModel.Assemblies.Add(thinAsm.Name, thinAsm); assemblies.Add(assembly.Name.Value, thinAsm); } foreach (INamedTypeDefinition type in _depot.TypesClosure.Values) { IAssembly asm = TypeHelper.GetDefiningUnit(type) as IAssembly; if (asm != null && assemblies.ContainsKey(asm.Name.Value)) { VisibilityOverride vis = VisibilityOverride.None; if (ShouldHideType(type)) vis = VisibilityOverride.Internal; if (closureStatus != IncludeStatus.ApiRoot) { if (TypeIsVisibleInApi(type)) { INamedTypeDefinition curType = type; while (curType != null && curType != Dummy.Type && // TODO: Remove dummy check? CanInclude(curType)) { if (WeHidThisType(curType)) throw new Exception("API closure error! Base type " + curType + " was hidden, but " + type + " is in the public API"); ITypeReference curTypeRef = TypeHelper.BaseClass(curType); curType = curTypeRef != null ? Util.CanonicalizeType(curTypeRef) : null; } } } ThinAssembly declaringAssembly = assemblies[asm.Name.Value]; ThinType thinType = new ThinType(declaringAssembly, Util.FullyQualifiedTypeNameFromType(type), GetIncludeStatus(type), type, vis); declaringAssembly.Types.Add(thinType.Name, thinType); types.Add(type, thinType); if (thinType.IncludeStatus == IncludeStatus.ApiClosure || thinType.IncludeStatus == IncludeStatus.ApiRoot || thinType.IncludeStatus == IncludeStatus.ApiFxInternal) { nApiTypes++; } } else { Console.Error.WriteLine("BclRewriter : warning BR5004 : couldn't find declaring module of type {0} in closure", type); } } foreach (IAliasForType typeForwarder in _depot.TypeForwardersClosure.Values) { // TODO: Why is this getting an immutable copy of the assembly? IAssembly asm = Util.GetDefiningAssembly(typeForwarder); if (asm != null && assemblies.ContainsKey(asm.Name.Value)) { ThinAssembly declaringAssembly = assemblies[asm.Name.Value]; ITypeReference aliasedType = typeForwarder.AliasedType; ThinTypeForwarder thinTypeForwarder = new ThinTypeForwarder(declaringAssembly, Util.GetDefiningAssembly(aliasedType).Name.Value, Util.GetTypeName(aliasedType), GetIncludeStatus(typeForwarder), typeForwarder); declaringAssembly.TypeForwarders.Add(thinTypeForwarder.Key, thinTypeForwarder); if (thinTypeForwarder.IncludeStatus == IncludeStatus.ApiClosure || thinTypeForwarder.IncludeStatus == IncludeStatus.ApiRoot || thinTypeForwarder.IncludeStatus == IncludeStatus.ApiFxInternal) { nApiTypeForwarders++; } } else { Console.Error.WriteLine("BclRewriter : warning BR5001 : couldn't find declaring module of type forwarder {0} in closure", typeForwarder); } } foreach (ITypeDefinitionMember member in _depot.MembersClosure.Keys) { INamedTypeDefinition type = Util.ContainingTypeDefinition(member); if (types.ContainsKey(type)) { ThinType declaringType = types[type]; IncludeStatus status = GetIncludeStatus(member); VisibilityOverride vis = VisibilityOverride.None; if (ShouldHideMember(member)) vis = VisibilityOverride.Internal; if ((type.IsInterface) && TypeIsVisibleInApi(type) && vis == VisibilityOverride.Internal) { throw new Exception(string.Format("Implementation required non-public member on public interface: {0} on {1}. This usually means you added a property to model.xml without adding the corresponding getter or setter.", member.Name, Util.FullyQualifiedTypeNameFromType(member.ContainingType))); } ThinMember thinMember = new ThinMember(declaringType, member, status, vis); declaringType.Members.Add(thinMember.Key, thinMember); if (thinMember.IncludeStatus == IncludeStatus.ApiClosure || thinMember.IncludeStatus == IncludeStatus.ApiRoot || thinMember.IncludeStatus == IncludeStatus.ApiFxInternal) { nApiMembers++; } } else { Console.Error.WriteLine("BclRewriter : warning BR5002 : couldn't find declaring type of member {0} in closure", member); } } foreach (IMethodDefinition method in _depot.MethodsClosure.Values) { INamedTypeDefinition type = Util.ContainingTypeDefinition(method); if (types.ContainsKey(type)) { ThinType declaringType = types[type]; IncludeStatus status = GetIncludeStatus(method); VisibilityOverride vis = VisibilityOverride.None; if (ShouldHideMember(method)) vis = VisibilityOverride.Internal; if ((type.IsInterface) && TypeIsVisibleInApi(type) && vis == VisibilityOverride.Internal) { //throw new Exception(string.Format("WARNING: implementation required non-public member on public interface: {0} on {1}. This usually means you added a property to model.xml without adding the corresponding getter or setter.", // method.Name, // Util.FullyQualifiedTypeNameFromType(method.ContainingType))); } ThinMember thinMember = new ThinMember(declaringType, method, status, vis); if (declaringType.Members.ContainsKey(thinMember.Key)) { throw new Exception(String.Format("Found two members with the same signature: {0}", thinMember.Key)); } declaringType.Members.Add(thinMember.Key, thinMember); if (thinMember.IncludeStatus == IncludeStatus.ApiClosure || thinMember.IncludeStatus == IncludeStatus.ApiRoot || thinMember.IncludeStatus == IncludeStatus.ApiFxInternal) { nApiMembers++; } } else { Console.Error.WriteLine("BclRewriter : warning BR5003 : couldn't find declaring type of method {0} in closure", method); } } foreach (ThinMember thinMember in _missingMembers) { ThinType typeToExtend = types[thinMember.DeclaringType.Metadata]; ThinMember newThinMember = new ThinMember(typeToExtend, thinMember); if (!typeToExtend.Members.ContainsKey(newThinMember.Key)) typeToExtend.Members.Add(newThinMember.Key, newThinMember); } return thinModel; } public IncludeStatus GetIncludeStatus(IAliasForType typeForwarder) { ThinTypeForwarder modelTypeForwarder; if (!_rootTypeForwarders.TryGetValue(typeForwarder, out modelTypeForwarder)) { if (_depot.TypeForwardersClosure.ContainsKey(Util.GetTypeForwarderSignature(typeForwarder))) { return _closureStatus; } return IncludeStatus.Exclude; } return modelTypeForwarder.IncludeStatus; } public bool /*IApiInformationProvider.*/IsFrameworkInternal(INamedTypeDefinition type) { return _rootTypes.ContainsKey(type) && _rootTypes[type].IncludeStatus == IncludeStatus.ApiFxInternal; } public bool /*IApiInformationProvider.*/IsFrameworkInternal(ITypeDefinitionMember member) { // if member is a nested type we should be looking for it in _rootTypes INamedTypeDefinition type = member as INamedTypeDefinition; if (type != null) return IsFrameworkInternal(type); else return _rootMembers.ContainsKey(member) && _rootMembers[member].IncludeStatus == IncludeStatus.ApiFxInternal; } public bool CanInclude(INamedTypeReference typeRef) { return CanIncludeUnit(TypeHelper.GetDefiningUnitReference(typeRef)); } public bool CanIncludeUnit(IUnitReference unit) { IAssemblyReference assembly = unit as IAssemblyReference; if (assembly == null) { assembly = (unit as IModuleReference).ContainingAssembly; } return CanIncludeAssembly(assembly.AssemblyIdentity); } public bool CanIncludeAssembly(AssemblyIdentity assemblyIdentity) { // If no filter set, we include all assemblies if (Options.IncludedAssemblies == null) { return true; } // Look through the list foreach (AssemblyIdentity assemblyId in Options.IncludedAssemblies) { if (assemblyId.Equals(assemblyIdentity)) { return true; } } // Assembly was not found in the list. return false; } } }
using System; using System.Collections.Generic; using System.IO; using Mono.Options; namespace CppSharp { class CLI { private static OptionSet optionSet = new OptionSet(); private static Options options = new Options(); static bool ParseCommandLineArgs(string[] args, List<string> messages, ref bool helpShown) { var showHelp = false; optionSet.Add("I=", "the {PATH} of a folder to search for include files", (i) => { AddIncludeDirs(i, messages); }); optionSet.Add("l=", "{LIBRARY} that that contains the symbols of the generated code", l => options.Libraries.Add(l) ); optionSet.Add("L=", "the {PATH} of a folder to search for additional libraries", l => options.LibraryDirs.Add(l) ); optionSet.Add("D:", "additional define with (optional) value to add to be used while parsing the given header files", (n, v) => AddDefine(n, v, messages) ); optionSet.Add("A=", "additional Clang arguments to pass to the compiler while parsing the given header files", (v) => AddArgument(v, messages) ); optionSet.Add("o=|output=", "the {PATH} for the generated bindings file (doesn't need the extension since it will depend on the generator)", v => HandleOutputArg(v, messages) ); optionSet.Add("on=|outputnamespace=", "the {NAMESPACE} that will be used for the generated code", on => options.OutputNamespace = on ); optionSet.Add("iln=|inputlibraryname=|inputlib=", "the {NAME} of the shared library that contains the symbols of the generated code", iln => options.InputLibraryName = iln ); optionSet.Add("d|debug", "enables debug mode which generates more verbose code to aid debugging", v => options.Debug = true); optionSet.Add("c|compile", "enables automatic compilation of the generated code", v => options.Compile = true); optionSet.Add("g=|gen=|generator=", "the {TYPE} of generated code: 'chsarp' or 'cli' ('cli' supported only for Windows)", g => { GetGeneratorKind(g, messages); } ); optionSet.Add("p=|platform=", "the {PLATFORM} that the generated code will target: 'win', 'osx' or 'linux'", p => { GetDestinationPlatform(p, messages); } ); optionSet.Add("a=|arch=", "the {ARCHITECTURE} that the generated code will target: 'x86' or 'x64'", a => { GetDestinationArchitecture(a, messages); } ); optionSet.Add("exceptions", "enables support for C++ exceptions in the parser", v => { options.Arguments.Add("-fcxx-exceptions"); }); optionSet.Add("c++11", "enables GCC C++ 11 compilation (valid only for Linux platform)", cpp11 => { options.Cpp11ABI = (cpp11 != null); } ); optionSet.Add("cs|checksymbols", "enable the symbol check for the generated code", cs => { options.CheckSymbols = (cs != null); } ); optionSet.Add("ub|unitybuild|unity", "enable unity build", ub => { options.UnityBuild = (ub != null); } ); optionSet.Add("v|verbose", "enables verbose mode", v => { options.Verbose = true; }); optionSet.Add("h|help", "shows the help", hl => { showHelp = (hl != null); }); List<string> additionalArguments = null; try { additionalArguments = optionSet.Parse(args); } catch (OptionException e) { Console.WriteLine(e.Message); return false; } if (showHelp || additionalArguments != null && additionalArguments.Count == 0) { helpShown = true; ShowHelp(); return false; } foreach(string s in additionalArguments) HandleAdditionalArgument(s, messages); return true; } static void ShowHelp() { string appName = Platform.IsWindows ? "CppSharp.CLI.exe" : "CppSharp.CLI"; Console.WriteLine(); Console.WriteLine("Usage: {0} [OPTIONS]+ [FILES]+", appName); Console.WriteLine("Generates target language bindings to interop with unmanaged code."); Console.WriteLine(); Console.WriteLine("Options:"); optionSet.WriteOptionDescriptions(Console.Out); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Useful informations:"); Console.WriteLine(" - to specify a file to generate bindings from you just have to add their path without any option flag, just like you"); Console.WriteLine(" would do with GCC compiler. You can specify a path to a single file (local or absolute) or a path to a folder with"); Console.WriteLine(" a search query."); Console.WriteLine(" e.g.: '{0} [OPTIONS]+ my_header.h' will generate the bindings for the file my_header.h", appName); Console.WriteLine(" e.g.: '{0} [OPTIONS]+ include/*.h' will generate the bindings for all the '.h' files inside the include folder", appName); Console.WriteLine(" - the options 'iln' (same as 'inputlibraryname') and 'l' have a similar meaning. Both of them are used to tell"); Console.WriteLine(" the generator which library has to be used to P/Invoke the functions from your native code."); Console.WriteLine(" The difference is that if you want to generate the bindings for more than one library within a single managed"); Console.WriteLine(" file you need to use the 'l' option to specify the names of all the libraries that contain the symbols to be loaded"); Console.WriteLine(" and you MUST set the 'cs' ('checksymbols') flag to let the generator automatically understand which library"); Console.WriteLine(" to use to P/Invoke. This can be also used if you plan to generate the bindings for only one library."); Console.WriteLine(" If you specify the 'iln' (or 'inputlibraryname') options, this option's value will be used for all the P/Invokes"); Console.WriteLine(" that the generator will create."); Console.WriteLine(" - If you specify the 'unitybuild' option then the generator will output a file for each given header file that will"); Console.WriteLine(" contain only the bindings for that header file."); } static void AddIncludeDirs(string dir, List<string> messages) { if (Directory.Exists(dir)) options.IncludeDirs.Add(dir); else messages.Add(string.Format("Directory '{0}' doesn't exist. Ignoring as include directory.", dir)); } static void HandleOutputArg(string arg, List<string> messages) { try { string file = Path.GetFileNameWithoutExtension(arg); options.OutputFileName = file; var dir = Path.HasExtension(arg) ? Path.GetDirectoryName(arg) : Path.GetFullPath(arg); options.OutputDir = dir; } catch(Exception e) { messages.Add(e.Message); options.OutputDir = ""; options.OutputFileName = ""; } } static void AddArgument(string value, List<string> messages) { if (value == null) messages.Add("Invalid compiler argument name for option -A."); else options.Arguments.Add(value); } static void AddDefine(string name, string value, List<string> messages) { if (name == null) messages.Add("Invalid definition name for option -D."); else options.Defines.Add(name, value); } static void HandleAdditionalArgument(string args, List<string> messages) { if (!Path.IsPathRooted(args)) args = Path.Combine(Directory.GetCurrentDirectory(), args); try { bool searchQuery = args.IndexOf('*') >= 0 || args.IndexOf('?') >= 0; if (searchQuery || Directory.Exists(args)) GetFilesFromPath(args, messages); else if (File.Exists(args)) options.HeaderFiles.Add(args); else { messages.Add(string.Format("File '{0}' could not be found.", args)); } } catch(Exception ex) { messages.Add(string.Format("Error while looking for files inside path '{0}'. Ignoring.", args)); } } static void GetFilesFromPath(string path, List<string> messages) { path = path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); string searchPattern = string.Empty; int lastSeparatorPosition = path.LastIndexOf(Path.AltDirectorySeparatorChar); if (lastSeparatorPosition >= 0) { if (path.IndexOf('*', lastSeparatorPosition) >= lastSeparatorPosition || path.IndexOf('?', lastSeparatorPosition) >= lastSeparatorPosition) { searchPattern = path.Substring(lastSeparatorPosition + 1); path = path.Substring(0, lastSeparatorPosition); } } try { if (!string.IsNullOrEmpty(searchPattern)) { string[] files = Directory.GetFiles(path, searchPattern); foreach (string s in files) options.HeaderFiles.Add(s); } else { string[] files = Directory.GetFiles(path); foreach (string s in files) options.HeaderFiles.Add(s); } } catch (Exception) { messages.Add(string.Format("Error while looking for files inside path '{0}'. Ignoring.", path)); } } static void GetGeneratorKind(string generator, List<string> messages) { switch (generator.ToLower()) { case "csharp": options.Kind = CppSharp.Generators.GeneratorKind.CSharp; return; case "cli": options.Kind = CppSharp.Generators.GeneratorKind.CLI; return; } messages.Add(string.Format("Unknown generator kind: {0}. Defaulting to {1}", generator, options.Kind.ToString())); } static void GetDestinationPlatform(string platform, List<string> messages) { switch (platform.ToLower()) { case "win": options.Platform = TargetPlatform.Windows; return; case "osx": options.Platform = TargetPlatform.MacOS; return; case "linux": options.Platform = TargetPlatform.Linux; return; } messages.Add(string.Format("Unknown target platform: {0}. Defaulting to {1}", platform, options.Platform.ToString())); } static void GetDestinationArchitecture(string architecture, List<string> messages) { switch (architecture.ToLower()) { case "x86": options.Architecture = TargetArchitecture.x86; return; case "x64": options.Architecture = TargetArchitecture.x64; return; } messages.Add(string.Format("Unknown target architecture: {0}. Defaulting to {1}", architecture, options.Architecture.ToString())); } static void PrintMessages(List<string> messages) { foreach (string m in messages) Console.WriteLine(m); } static void Main(string[] args) { List<string> messages = new List<string>(); bool helpShown = false; try { if (!ParseCommandLineArgs(args, messages, ref helpShown)) { PrintMessages(messages); // Don't need to show the help since if ParseCommandLineArgs returns false the help has already been shown return; } Generator gen = new Generator(options); bool validOptions = gen.ValidateOptions(messages); PrintMessages(messages); if (validOptions) gen.Run(); } catch (Exception ex) { PrintMessages(messages); Console.WriteLine(ex.Message); } } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.ExceptionServices; using GraphQL.Types; namespace GraphQL { /// <summary> /// Provides extension methods for objects and a method for converting a dictionary into a strongly typed object. /// </summary> public static class ObjectExtensions { private static readonly ConcurrentDictionary<Type, ConstructorInfo[]> _types = new ConcurrentDictionary<Type, ConstructorInfo[]>(); /// <summary> /// Creates a new instance of the indicated type, populating it with the dictionary. /// </summary> /// <typeparam name="T">The type to create.</typeparam> /// <param name="source">The source of values.</param> /// <returns>T.</returns> public static T ToObject<T>(this IDictionary<string, object?> source) where T : class => (T)ToObject(source, typeof(T)); private static readonly List<object> _emptyValues = new List<object>(); /// <summary> /// Creates a new instance of the indicated type, populating it with the dictionary. /// Can use any constructor of the indicated type, provided that there are keys in the /// dictionary that correspond (case sensitive) to the names of the constructor parameters. /// </summary> /// <param name="source">The source of values.</param> /// <param name="type">The type to create.</param> /// <param name="mappedType"> /// GraphType for matching dictionary keys with <paramref name="type"/> property names. /// GraphType contains information about this matching in Metadata property. /// In case of configuring field as Field(x => x.FName).Name("FirstName") source dictionary /// will have 'FirstName' key but its value should be set to 'FName' property of created object. /// </param> public static object ToObject(this IDictionary<string, object?> source, Type type, IGraphType? mappedType = null) { // Given Field(x => x.FName).Name("FirstName") and key == "FirstName" returns "FName" string GetPropertyName(string key, out FieldType? field) { var complexType = mappedType?.GetNamedType() as IComplexGraphType; // type may not contain mapping information field = complexType?.GetField(key); return field?.GetMetadata(ComplexGraphType<object>.ORIGINAL_EXPRESSION_PROPERTY_NAME, key) ?? key; } // Returns values (from source or defaults) that match constructor signature + used keys from source (List<object>?, List<string>?) GetValuesAndUsedKeys(ParameterInfo[] parameters) { // parameterless constructors are the most common use case if (parameters.Length == 0) return (_emptyValues, null); // otherwise we have to iterate over the parameters - worse performance but this is rather rare case List<object>? values = null; List<string>? keys = null; if (parameters.All(p => { // Source values take precedence if (source.Any(keyValue => { bool matched = string.Equals(GetPropertyName(keyValue.Key, out var _), p.Name, StringComparison.InvariantCultureIgnoreCase); if (matched) { (values ??= new List<object>()).Add(keyValue.Value); (keys ??= new List<string>()).Add(keyValue.Key); } return matched; })) { return true; } // Then check for default values if any if (p.HasDefaultValue) { (values ??= new List<object>()).Add(p.DefaultValue); return true; } return false; })) { return (values, keys); } return (null, null); } if (source == null) throw new ArgumentNullException(nameof(source)); // force sourceType to be IDictionary<string, object> if (ValueConverter.TryConvertTo(source, type, out object? result, typeof(IDictionary<string, object>))) return result!; // attempt to use the most specific constructor sorting in decreasing order of parameters number var ctorCandidates = _types.GetOrAdd(type, t => t.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).OrderByDescending(ctor => ctor.GetParameters().Length).ToArray()); ConstructorInfo? targetCtor = null; ParameterInfo[]? ctorParameters = null; List<object>? values = null; List<string>? usedKeys = null; foreach (var ctor in ctorCandidates) { var parameters = ctor.GetParameters(); (values, usedKeys) = GetValuesAndUsedKeys(parameters); if (values != null) { targetCtor = ctor; ctorParameters = parameters; break; } } if (targetCtor == null || ctorParameters == null || values == null) throw new ArgumentException($"Type '{type}' does not contain a constructor that could be used for current input arguments.", nameof(type)); object?[] ctorArguments = ctorParameters.Length == 0 ? Array.Empty<object>() : new object[ctorParameters.Length]; for (int i = 0; i < ctorParameters.Length; ++i) { object? arg = GetPropertyValue(values[i], ctorParameters[i].ParameterType); ctorArguments[i] = arg; } object obj; try { obj = targetCtor.Invoke(ctorArguments); } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); return ""; // never executed, necessary only for intellisense } foreach (var item in source) { // these parameters have already been used in the constructor, no need to set property if (usedKeys?.Any(k => k == item.Key) == true) continue; string propertyName = GetPropertyName(item.Key, out var field); PropertyInfo? propertyInfo = null; try { propertyInfo = type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); } catch (AmbiguousMatchException) { propertyInfo = type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); } if (propertyInfo != null && propertyInfo.CanWrite) { object? value = GetPropertyValue(item.Value, propertyInfo.PropertyType, field?.ResolvedType); propertyInfo.SetValue(obj, value, null); //issue: this works even if propertyInfo is ValueType and value is null } } return obj; } /// <summary> /// Converts the indicated value into a type that is compatible with fieldType. /// </summary> /// <param name="propertyValue">The value to be converted.</param> /// <param name="fieldType">The desired type.</param> /// <param name="mappedType"> /// GraphType for matching dictionary keys with <paramref name="fieldType"/> property names. /// GraphType contains information about this matching in Metadata property. /// In case of configuring field as Field(x => x.FName).Name("FirstName") source dictionary /// will have 'FirstName' key but its value should be set to 'FName' property of created object. /// </param> /// <remarks>There is special handling for strings, IEnumerable&lt;T&gt;, Nullable&lt;T&gt;, and Enum.</remarks> public static object? GetPropertyValue(this object? propertyValue, Type fieldType, IGraphType? mappedType = null) { // Short-circuit conversion if the property value already of the right type if (propertyValue == null || fieldType == typeof(object) || fieldType.IsInstanceOfType(propertyValue)) { return propertyValue; } if (ValueConverter.TryConvertTo(propertyValue, fieldType, out object? result)) return result; var enumerableInterface = fieldType.Name == "IEnumerable`1" ? fieldType : fieldType.GetInterface("IEnumerable`1"); if (fieldType != typeof(string) && enumerableInterface != null) { IList newCollection; var elementType = enumerableInterface.GetGenericArguments()[0]; var underlyingType = Nullable.GetUnderlyingType(elementType) ?? elementType; var fieldTypeImplementsIList = fieldType.GetInterface("IList") != null; var propertyValueAsIList = propertyValue as IList; // Custom container if (fieldTypeImplementsIList && !fieldType.IsArray) { newCollection = (IList)Activator.CreateInstance(fieldType)!; } // Array of known size is created immediately else if (fieldType.IsArray && propertyValueAsIList != null) { newCollection = Array.CreateInstance(elementType, propertyValueAsIList.Count); } // List<T> else { var genericListType = typeof(List<>).MakeGenericType(elementType); newCollection = (IList)Activator.CreateInstance(genericListType); } if (!(propertyValue is IEnumerable valueList)) return newCollection; // Array of known size is populated in-place if (fieldType.IsArray && propertyValueAsIList != null) { for (int i = 0; i < propertyValueAsIList.Count; ++i) { var listItem = propertyValueAsIList[i]; newCollection[i] = listItem == null ? null : GetPropertyValue(listItem, underlyingType, mappedType); } } // Array of unknown size is created only after populating list else { foreach (var listItem in valueList) { newCollection.Add(listItem == null ? null : GetPropertyValue(listItem, underlyingType, mappedType)); } if (fieldType.IsArray) newCollection = ((dynamic)newCollection).ToArray(); } return newCollection; } var value = propertyValue; var nullableFieldType = Nullable.GetUnderlyingType(fieldType); // if this is a nullable type and the value is null, return null if (nullableFieldType != null && value == null) { return null; } if (nullableFieldType != null) { fieldType = nullableFieldType; } if (propertyValue is IDictionary<string, object?> objects) { return ToObject(objects, fieldType, mappedType); } if (fieldType.IsEnum) { if (value == null) { var enumNames = Enum.GetNames(fieldType); value = enumNames[0]; } if (!IsDefinedEnumValue(fieldType, value)) { throw new InvalidOperationException($"Unknown value '{value}' for enum '{fieldType.Name}'."); } string str = value.ToString(); value = Enum.Parse(fieldType, str, true); } return ValueConverter.ConvertTo(value, fieldType); } /// <summary> /// Returns <see langword="true"/> if the value is <see langword="null"/>, value.ToString equals an empty string, or the value can be converted into a named enum value. /// </summary> /// <param name="type">An enum type.</param> /// <param name="value">The value being tested.</param> public static bool IsDefinedEnumValue(Type type, object? value) //TODO: rewrite, comment above seems wrong { try { var names = Enum.GetNames(type); if (names.Contains(value?.ToString() ?? "", StringComparer.OrdinalIgnoreCase)) { return true; } var underlyingType = Enum.GetUnderlyingType(type); var converted = Convert.ChangeType(value, underlyingType); var values = Enum.GetValues(type); foreach (var val in values) { var convertedVal = Convert.ChangeType(val, underlyingType); if (convertedVal.Equals(converted)) { return true; } } } catch { // TODO: refactor IsDefinedEnumValue } return false; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // namespace System.Reflection.Emit { using System.Text; using System; using CultureInfo = System.Globalization.CultureInfo; using System.Diagnostics.SymbolStore; using System.Reflection; using System.Security; using System.Collections; using System.Collections.Generic; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MethodBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public sealed class MethodBuilder : MethodInfo, _MethodBuilder { #region Private Data Members // Identity internal String m_strName; // The name of the method private MethodToken m_tkMethod; // The token of this method private ModuleBuilder m_module; internal TypeBuilder m_containingType; // IL private int[] m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups. private byte[] m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise. internal LocalSymInfo m_localSymInfo; // keep track debugging local information internal ILGenerator m_ilGenerator; // Null if not used. private byte[] m_ubBody; // The IL for the method private ExceptionHandler[] m_exceptions; // Exception handlers or null if there are none. private const int DefaultMaxStack = 16; private int m_maxStack = DefaultMaxStack; // Flags internal bool m_bIsBaked; private bool m_bIsGlobalMethod; private bool m_fInitLocals; // indicating if the method stack frame will be zero initialized or not. // Attributes private MethodAttributes m_iAttributes; private CallingConventions m_callingConvention; private MethodImplAttributes m_dwMethodImplFlags; // Parameters private SignatureHelper m_signature; internal Type[] m_parameterTypes; private ParameterBuilder m_retParam; private Type m_returnType; private Type[] m_returnTypeRequiredCustomModifiers; private Type[] m_returnTypeOptionalCustomModifiers; private Type[][] m_parameterTypeRequiredCustomModifiers; private Type[][] m_parameterTypeOptionalCustomModifiers; // Generics private GenericTypeParameterBuilder[] m_inst; private bool m_bIsGenMethDef; #endregion #region Constructor internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { Init(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, mod, type, bIsGlobalMethod); } internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { Init(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, mod, type, bIsGlobalMethod); } private void Init(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); if (name[0] == '\0') throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name"); if (mod == null) throw new ArgumentNullException("mod"); Contract.EndContractBlock(); if (parameterTypes != null) { foreach(Type t in parameterTypes) { if (t == null) throw new ArgumentNullException("parameterTypes"); } } m_strName = name; m_module = mod; m_containingType = type; // //if (returnType == null) //{ // m_returnType = typeof(void); //} //else { m_returnType = returnType; } if ((attributes & MethodAttributes.Static) == 0) { // turn on the has this calling convention callingConvention = callingConvention | CallingConventions.HasThis; } else if ((attributes & MethodAttributes.Virtual) != 0) { // A method can't be both static and virtual throw new ArgumentException(Environment.GetResourceString("Arg_NoStaticVirtual")); } if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName) { if ((type.Attributes & TypeAttributes.Interface) == TypeAttributes.Interface) { // methods on interface have to be abstract + virtual except special name methods such as type initializer if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) != (MethodAttributes.Abstract | MethodAttributes.Virtual) && (attributes & MethodAttributes.Static) == 0) throw new ArgumentException(Environment.GetResourceString("Argument_BadAttributeOnInterfaceMethod")); } } m_callingConvention = callingConvention; if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length); } else { m_parameterTypes = null; } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; // m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention, // returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, // parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); m_iAttributes = attributes; m_bIsGlobalMethod = bIsGlobalMethod; m_bIsBaked = false; m_fInitLocals = true; m_localSymInfo = new LocalSymInfo(); m_ubBody = null; m_ilGenerator = null; // Default is managed IL. Manged IL has bit flag 0x0020 set off m_dwMethodImplFlags = MethodImplAttributes.IL; } #endregion #region Internal Members internal void CheckContext(params Type[][] typess) { m_module.CheckContext(typess); } internal void CheckContext(params Type[] types) { m_module.CheckContext(types); } [System.Security.SecurityCritical] // auto-generated internal void CreateMethodBodyHelper(ILGenerator il) { // Sets the IL of the method. An ILGenerator is passed as an argument and the method // queries this instance to get all of the information which it needs. if (il == null) { throw new ArgumentNullException("il"); } Contract.EndContractBlock(); __ExceptionInfo[] excp; int counter=0; int[] filterAddrs; int[] catchAddrs; int[] catchEndAddrs; Type[] catchClass; int[] type; int numCatch; int start, end; ModuleBuilder dynMod = (ModuleBuilder) m_module; m_containingType.ThrowIfCreated(); if (m_bIsBaked) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodHasBody")); } if (il.m_methodBuilder != this && il.m_methodBuilder != null) { // you don't need to call DefineBody when you get your ILGenerator // through MethodBuilder::GetILGenerator. // throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadILGeneratorUsage")); } ThrowIfShouldNotHaveBody(); if (il.m_ScopeTree.m_iOpenScopeCount != 0) { // There are still unclosed local scope throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_OpenLocalVariableScope")); } m_ubBody = il.BakeByteArray(); m_mdMethodFixups = il.GetTokenFixups(); //Okay, now the fun part. Calculate all of the exceptions. excp = il.GetExceptions(); int numExceptions = CalculateNumberOfExceptions(excp); if (numExceptions > 0) { m_exceptions = new ExceptionHandler[numExceptions]; for (int i = 0; i < excp.Length; i++) { filterAddrs = excp[i].GetFilterAddresses(); catchAddrs = excp[i].GetCatchAddresses(); catchEndAddrs = excp[i].GetCatchEndAddresses(); catchClass = excp[i].GetCatchClass(); numCatch = excp[i].GetNumberOfCatches(); start = excp[i].GetStartAddress(); end = excp[i].GetEndAddress(); type = excp[i].GetExceptionTypes(); for (int j = 0; j < numCatch; j++) { int tkExceptionClass = 0; if (catchClass[j] != null) { tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]).Token; } switch (type[j]) { case __ExceptionInfo.None: case __ExceptionInfo.Fault: case __ExceptionInfo.Filter: m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; case __ExceptionInfo.Finally: m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; } } } } m_bIsBaked=true; if (dynMod.GetSymWriter() != null) { // set the debugging information such as scope and line number // if it is in a debug module // SymbolToken tk = new SymbolToken(MetadataTokenInternal); ISymbolWriter symWriter = dynMod.GetSymWriter(); // call OpenMethod to make this method the current method symWriter.OpenMethod(tk); // call OpenScope because OpenMethod no longer implicitly creating // the top-levelsmethod scope // symWriter.OpenScope(0); if (m_symCustomAttrs != null) { foreach(SymCustomAttr symCustomAttr in m_symCustomAttrs) dynMod.GetSymWriter().SetSymAttribute( new SymbolToken (MetadataTokenInternal), symCustomAttr.m_name, symCustomAttr.m_data); } if (m_localSymInfo != null) m_localSymInfo.EmitLocalSymInfo(symWriter); il.m_ScopeTree.EmitScopeTree(symWriter); il.m_LineNumberInfo.EmitLineNumberInfo(symWriter); symWriter.CloseScope(il.ILOffset); symWriter.CloseMethod(); } } // This is only called from TypeBuilder.CreateType after the method has been created internal void ReleaseBakedStructures() { if (!m_bIsBaked) { // We don't need to do anything here if we didn't baked the method body return; } m_ubBody = null; m_localSymInfo = null; m_mdMethodFixups = null; m_localSignature = null; m_exceptions = null; } internal override Type[] GetParameterTypes() { if (m_parameterTypes == null) m_parameterTypes = EmptyArray<Type>.Value; return m_parameterTypes; } internal static Type GetMethodBaseReturnType(MethodBase method) { MethodInfo mi = null; ConstructorInfo ci = null; if ( (mi = method as MethodInfo) != null ) { return mi.ReturnType; } else if ( (ci = method as ConstructorInfo) != null) { return ci.GetReturnType(); } else { Contract.Assert(false, "We should never get here!"); return null; } } internal void SetToken(MethodToken token) { m_tkMethod = token; } internal byte[] GetBody() { // Returns the il bytes of this method. // This il is not valid until somebody has called BakeByteArray return m_ubBody; } internal int[] GetTokenFixups() { return m_mdMethodFixups; } [System.Security.SecurityCritical] // auto-generated internal SignatureHelper GetMethodSignature() { if (m_parameterTypes == null) m_parameterTypes = EmptyArray<Type>.Value; m_signature = SignatureHelper.GetMethodSigHelper (m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0, m_returnType == null ? typeof(void) : m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers, m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers); return m_signature; } // Returns a buffer whose initial signatureLength bytes contain encoded local signature. internal byte[] GetLocalSignature(out int signatureLength) { if (m_localSignature != null) { signatureLength = m_localSignature.Length; return m_localSignature; } if (m_ilGenerator != null) { if (m_ilGenerator.m_localCount != 0) { // If user is using ILGenerator::DeclareLocal, then get local signaturefrom there. return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength); } } return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength); } internal int GetMaxStack() { if (m_ilGenerator != null) { return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount; } else { // this is the case when client provide an array of IL byte stream rather than going through ILGenerator. return m_maxStack; } } internal ExceptionHandler[] GetExceptionHandlers() { return m_exceptions; } internal int ExceptionHandlerCount { get { return m_exceptions != null ? m_exceptions.Length : 0; } } internal int CalculateNumberOfExceptions(__ExceptionInfo[] excp) { int num=0; if (excp==null) { return 0; } for (int i=0; i<excp.Length; i++) { num+=excp[i].GetNumberOfCatches(); } return num; } internal bool IsTypeCreated() { return (m_containingType != null && m_containingType.IsCreated()); } internal TypeBuilder GetTypeBuilder() { return m_containingType; } internal ModuleBuilder GetModuleBuilder() { return m_module; } #endregion #region Object Overrides [System.Security.SecuritySafeCritical] // auto-generated public override bool Equals(Object obj) { if (!(obj is MethodBuilder)) { return false; } if (!(this.m_strName.Equals(((MethodBuilder)obj).m_strName))) { return false; } if (m_iAttributes!=(((MethodBuilder)obj).m_iAttributes)) { return false; } SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature(); if (thatSig.Equals(GetMethodSignature())) { return true; } return false; } public override int GetHashCode() { return this.m_strName.GetHashCode(); } [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { StringBuilder sb = new StringBuilder(1000); sb.Append("Name: " + m_strName + " " + Environment.NewLine); sb.Append("Attributes: " + (int)m_iAttributes + Environment.NewLine); sb.Append("Method Signature: " + GetMethodSignature() + Environment.NewLine); sb.Append(Environment.NewLine); return sb.ToString(); } #endregion #region MemberInfo Overrides public override String Name { get { return m_strName; } } internal int MetadataTokenInternal { get { return GetToken().Token; } } public override Module Module { get { return m_containingType.Module; } } public override Type DeclaringType { get { if (m_containingType.m_isHiddenGlobalType == true) return null; return m_containingType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return null; } } public override Type ReflectedType { get { return DeclaringType; } } #endregion #region MethodBase Overrides public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_dwMethodImplFlags; } public override MethodAttributes Attributes { get { return m_iAttributes; } } public override CallingConventions CallingConvention { get {return m_callingConvention;} } public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } } public override bool IsSecurityCritical { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } } public override bool IsSecuritySafeCritical { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } } public override bool IsSecurityTransparent { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } } #endregion #region MethodInfo Overrides public override MethodInfo GetBaseDefinition() { return this; } public override Type ReturnType { get { return m_returnType; } } [Pure] public override ParameterInfo[] GetParameters() { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_TypeNotCreated")); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes); return rmi.GetParameters(); } public override ParameterInfo ReturnParameter { get { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeNotCreated")); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes); return rmi.ReturnParameter; } } #endregion #region ICustomAttributeProvider Implementation public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } #endregion #region Generic Members public override bool IsGenericMethodDefinition { get { return m_bIsGenMethDef; } } public override bool ContainsGenericParameters { get { throw new NotSupportedException(); } } public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; } public override bool IsGenericMethod { get { return m_inst != null; } } public override Type[] GetGenericArguments() { return m_inst; } public override MethodInfo MakeGenericMethod(params Type[] typeArguments) { return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments); } public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names) { if (names == null) throw new ArgumentNullException("names"); if (names.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "names"); Contract.EndContractBlock(); if (m_inst != null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GenericParametersAlreadySet")); for (int i = 0; i < names.Length; i ++) if (names[i] == null) throw new ArgumentNullException("names"); if (m_tkMethod.Token != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBuilderBaked")); m_bIsGenMethDef = true; m_inst = new GenericTypeParameterBuilder[names.Length]; for (int i = 0; i < names.Length; i ++) m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this)); return m_inst; } internal void ThrowIfGeneric () { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException (); } #endregion #region Public Members [System.Security.SecuritySafeCritical] // auto-generated public MethodToken GetToken() { // We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498 // we only "tokenize" a method when requested. But the order in which the methods are tokenized // didn't change: the same order the MethodBuilders are constructed. The recursion introduced // will overflow the stack when there are many methods on the same type (10000 in my experiment). // The change also introduced race conditions. Before the code change GetToken is called from // the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it // could be called more than once on the the same method introducing duplicate (invalid) tokens. // I don't fully understand this change. So I will keep the logic and only fix the recursion and // the race condition. if (m_tkMethod.Token != 0) { return m_tkMethod; } MethodBuilder currentMethod = null; MethodToken currentToken = new MethodToken(0); int i; // We need to lock here to prevent a method from being "tokenized" twice. // We don't need to synchronize this with Type.DefineMethod because it only appends newly // constructed MethodBuilders to the end of m_listMethods lock (m_containingType.m_listMethods) { if (m_tkMethod.Token != 0) { return m_tkMethod; } // If m_tkMethod is still 0 when we obtain the lock, m_lastTokenizedMethod must be smaller // than the index of the current method. for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; ++i) { currentMethod = m_containingType.m_listMethods[i]; currentToken = currentMethod.GetTokenNoLock(); if (currentMethod == this) break; } m_containingType.m_lastTokenizedMethod = i; } Contract.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods"); Contract.Assert(currentToken.Token != 0, "The token should not be 0"); return currentToken; } [System.Security.SecurityCritical] // auto-generated private MethodToken GetTokenNoLock() { Contract.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized"); int sigLength; byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength); int token = TypeBuilder.DefineMethod(m_module.GetNativeHandle(), m_containingType.MetadataTokenInternal, m_strName, sigBytes, sigLength, Attributes); m_tkMethod = new MethodToken(token); if (m_inst != null) foreach (GenericTypeParameterBuilder tb in m_inst) if (!tb.m_type.IsCreated()) tb.m_type.CreateType(); TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), token, m_dwMethodImplFlags); return m_tkMethod; } public void SetParameters (params Type[] parameterTypes) { CheckContext(parameterTypes); SetSignature (null, null, null, parameterTypes, null, null); } public void SetReturnType (Type returnType) { CheckContext(returnType); SetSignature (returnType, null, null, null, null, null); } public void SetSignature( Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) { // We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked. // But we cannot because that would be a breaking change from V2. if (m_tkMethod.Token != 0) return; CheckContext(returnType); CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); CheckContext(parameterTypeRequiredCustomModifiers); CheckContext(parameterTypeOptionalCustomModifiers); ThrowIfGeneric(); if (returnType != null) { m_returnType = returnType; } if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy (parameterTypes, m_parameterTypes, parameterTypes.Length); } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; } [System.Security.SecuritySafeCritical] // auto-generated public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName) { if (position < 0) throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence")); Contract.EndContractBlock(); ThrowIfGeneric(); m_containingType.ThrowIfCreated (); if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length)) throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence")); attributes = attributes & ~ParameterAttributes.ReservedMask; return new ParameterBuilder(this, position, attributes, strParamName); } [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")] public void SetMarshal(UnmanagedMarshal unmanagedMarshal) { ThrowIfGeneric (); // set Marshal info for the return type m_containingType.ThrowIfCreated(); if (m_retParam == null) { m_retParam = new ParameterBuilder(this, 0, 0, null); } m_retParam.SetMarshal(unmanagedMarshal); } private List<SymCustomAttr> m_symCustomAttrs; private struct SymCustomAttr { public SymCustomAttr(String name, byte[] data) { m_name = name; m_data = data; } public String m_name; public byte[] m_data; } public void SetSymCustomAttribute(String name, byte[] data) { // Note that this API is rarely used. Support for custom attributes in PDB files was added in // Whidbey and as of 8/2007 the only known user is the C# compiler. There seems to be little // value to this for Reflection.Emit users since they can always use metadata custom attributes. // Some versions of the symbol writer used in the CLR will ignore these entirely. This API has // been removed from the Silverlight API surface area, but we should also consider removing it // from future desktop product versions as well. ThrowIfGeneric (); // This is different from CustomAttribute. This is stored into the SymWriter. m_containingType.ThrowIfCreated(); ModuleBuilder dynMod = (ModuleBuilder) m_module; if ( dynMod.GetSymWriter() == null) { // Cannot SetSymCustomAttribute when it is not a debug module throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule")); } if (m_symCustomAttrs == null) m_symCustomAttrs = new List<SymCustomAttr>(); m_symCustomAttrs.Add(new SymCustomAttr(name, data)); } #if FEATURE_CAS_POLICY [System.Security.SecuritySafeCritical] // auto-generated public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset) { if (pset == null) throw new ArgumentNullException("pset"); Contract.EndContractBlock(); ThrowIfGeneric (); #pragma warning disable 618 if (!Enum.IsDefined(typeof(SecurityAction), action) || action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) { throw new ArgumentOutOfRangeException("action"); } #pragma warning restore 618 // cannot declarative security after type is created m_containingType.ThrowIfCreated(); // Translate permission set into serialized format (uses standard binary serialization format). byte[] blob = null; int length = 0; if (!pset.IsEmpty()) { blob = pset.EncodeXml(); length = blob.Length; } // Write the blob into the metadata. TypeBuilder.AddDeclarativeSecurity(m_module.GetNativeHandle(), MetadataTokenInternal, action, blob, length); } #endif // FEATURE_CAS_POLICY #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups) { if (il == null) { throw new ArgumentNullException("il", Environment.GetResourceString("ArgumentNull_Array")); } if (maxStack < 0) { throw new ArgumentOutOfRangeException("maxStack", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (m_bIsBaked) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked")); } m_containingType.ThrowIfCreated(); ThrowIfGeneric(); byte[] newLocalSignature = null; ExceptionHandler[] newHandlers = null; int[] newTokenFixups = null; byte[] newIL = (byte[])il.Clone(); if (localSignature != null) { newLocalSignature = (byte[])localSignature.Clone(); } if (exceptionHandlers != null) { newHandlers = ToArray(exceptionHandlers); CheckExceptionHandlerRanges(newHandlers, newIL.Length); // Note: Fixup entries for type tokens stored in ExceptionHandlers are added by the method body emitter. } if (tokenFixups != null) { newTokenFixups = ToArray(tokenFixups); int maxTokenOffset = newIL.Length - 4; for (int i = 0; i < newTokenFixups.Length; i++) { // Check that fixups are within the range of this method's IL, otherwise some random memory might get "fixed up". if (newTokenFixups[i] < 0 || newTokenFixups[i] > maxTokenOffset) { throw new ArgumentOutOfRangeException("tokenFixups[" + i + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, maxTokenOffset)); } } } m_ubBody = newIL; m_localSignature = newLocalSignature; m_exceptions = newHandlers; m_mdMethodFixups = newTokenFixups; m_maxStack = maxStack; // discard IL generator, all information stored in it is now irrelevant m_ilGenerator = null; m_bIsBaked = true; } private static T[] ToArray<T>(IEnumerable<T> sequence) { T[] array = sequence as T[]; if (array != null) { return (T[])array.Clone(); } return new List<T>(sequence).ToArray(); } private static void CheckExceptionHandlerRanges(ExceptionHandler[] exceptionHandlers, int maxOffset) { // Basic checks that the handler ranges are within the method body (ranges are end-exclusive). // Doesn't verify that the ranges are otherwise correct - it is very well possible to emit invalid IL. for (int i = 0; i < exceptionHandlers.Length; i++) { var handler = exceptionHandlers[i]; if (handler.m_filterOffset > maxOffset || handler.m_tryEndOffset > maxOffset || handler.m_handlerEndOffset > maxOffset) { throw new ArgumentOutOfRangeException("exceptionHandlers[" + i + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, maxOffset)); } // Type token might be 0 if the ExceptionHandler was created via a default constructor. // Other tokens migth also be invalid. We only check nil tokens as the implementation (SectEH_Emit in corhlpr.cpp) requires it, // and we can't check for valid tokens until the module is baked. if (handler.Kind == ExceptionHandlingClauseOptions.Clause && handler.ExceptionTypeToken == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", handler.ExceptionTypeToken), "exceptionHandlers[" + i + "]"); } } } /// <summary> /// Obsolete. /// </summary> #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public void CreateMethodBody(byte[] il, int count) { ThrowIfGeneric(); // Note that when user calls this function, there are a few information that client is // not able to supply: local signature, exception handlers, max stack size, a list of Token fixup, a list of RVA fixup if (m_bIsBaked) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked")); } m_containingType.ThrowIfCreated(); if (il != null && (count < 0 || count > il.Length)) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (il == null) { m_ubBody = null; return; } m_ubBody = new byte[count]; Array.Copy(il,m_ubBody,count); m_localSignature = null; m_exceptions = null; m_mdMethodFixups = null; m_maxStack = DefaultMaxStack; m_bIsBaked = true; } [System.Security.SecuritySafeCritical] // auto-generated public void SetImplementationFlags(MethodImplAttributes attributes) { ThrowIfGeneric (); m_containingType.ThrowIfCreated (); m_dwMethodImplFlags = attributes; m_canBeRuntimeImpl = true; TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), MetadataTokenInternal, attributes); } public ILGenerator GetILGenerator() { Contract.Ensures(Contract.Result<ILGenerator>() != null); ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); if (m_ilGenerator == null) m_ilGenerator = new ILGenerator(this); return m_ilGenerator; } public ILGenerator GetILGenerator(int size) { Contract.Ensures(Contract.Result<ILGenerator>() != null); ThrowIfGeneric (); ThrowIfShouldNotHaveBody(); if (m_ilGenerator == null) m_ilGenerator = new ILGenerator(this, size); return m_ilGenerator; } private void ThrowIfShouldNotHaveBody() { if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL || (m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 || (m_iAttributes & MethodAttributes.PinvokeImpl) != 0 || m_isDllImport) { // cannot attach method body if methodimpl is marked not marked as managed IL // throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ShouldNotHaveMethodBody")); } } public bool InitLocals { // Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false. get { ThrowIfGeneric (); return m_fInitLocals; } set { ThrowIfGeneric (); m_fInitLocals = value; } } public Module GetModule() { return GetModuleBuilder(); } public String Signature { [System.Security.SecuritySafeCritical] // auto-generated get { return GetMethodSignature().ToString(); } } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) throw new ArgumentNullException("con"); if (binaryAttribute == null) throw new ArgumentNullException("binaryAttribute"); Contract.EndContractBlock(); ThrowIfGeneric(); TypeBuilder.DefineCustomAttribute(m_module, MetadataTokenInternal, ((ModuleBuilder)m_module).GetConstructorToken(con).Token, binaryAttribute, false, false); if (IsKnownCA(con)) ParseCA(con, binaryAttribute); } [System.Security.SecuritySafeCritical] // auto-generated public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) throw new ArgumentNullException("customBuilder"); Contract.EndContractBlock(); ThrowIfGeneric(); customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataTokenInternal); if (IsKnownCA(customBuilder.m_con)) ParseCA(customBuilder.m_con, customBuilder.m_blob); } // this method should return true for any and every ca that requires more work // than just setting the ca private bool IsKnownCA(ConstructorInfo con) { Type caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) return true; else if (caType == typeof(DllImportAttribute)) return true; else return false; } private void ParseCA(ConstructorInfo con, byte[] blob) { Type caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) { // dig through the blob looking for the MethodImplAttributes flag // that must be in the MethodCodeType field // for now we simply set a flag that relaxes the check when saving and // allows this method to have no body when any kind of MethodImplAttribute is present m_canBeRuntimeImpl = true; } else if (caType == typeof(DllImportAttribute)) { m_canBeRuntimeImpl = true; m_isDllImport = true; } } internal bool m_canBeRuntimeImpl = false; internal bool m_isDllImport = false; #endregion void _MethodBuilder.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _MethodBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _MethodBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } } internal class LocalSymInfo { // This class tracks the local variable's debugging information // and namespace information with a given active lexical scope. #region Internal Data Members internal String[] m_strName; internal byte[][] m_ubSignature; internal int[] m_iLocalSlot; internal int[] m_iStartOffset; internal int[] m_iEndOffset; internal int m_iLocalSymCount; // how many entries in the arrays are occupied internal String[] m_namespace; internal int m_iNameSpaceCount; internal const int InitialSize = 16; #endregion #region Constructor internal LocalSymInfo() { // initialize data variables m_iLocalSymCount = 0; m_iNameSpaceCount = 0; } #endregion #region Private Members private void EnsureCapacityNamespace() { if (m_iNameSpaceCount == 0) { m_namespace = new String[InitialSize]; } else if (m_iNameSpaceCount == m_namespace.Length) { String [] strTemp = new String [checked(m_iNameSpaceCount * 2)]; Array.Copy(m_namespace, strTemp, m_iNameSpaceCount); m_namespace = strTemp; } } private void EnsureCapacity() { if (m_iLocalSymCount == 0) { // First time. Allocate the arrays. m_strName = new String[InitialSize]; m_ubSignature = new byte[InitialSize][]; m_iLocalSlot = new int[InitialSize]; m_iStartOffset = new int[InitialSize]; m_iEndOffset = new int[InitialSize]; } else if (m_iLocalSymCount == m_strName.Length) { // the arrays are full. Enlarge the arrays // why aren't we just using lists here? int newSize = checked(m_iLocalSymCount * 2); int[] temp = new int [newSize]; Array.Copy(m_iLocalSlot, temp, m_iLocalSymCount); m_iLocalSlot = temp; temp = new int [newSize]; Array.Copy(m_iStartOffset, temp, m_iLocalSymCount); m_iStartOffset = temp; temp = new int [newSize]; Array.Copy(m_iEndOffset, temp, m_iLocalSymCount); m_iEndOffset = temp; String [] strTemp = new String [newSize]; Array.Copy(m_strName, strTemp, m_iLocalSymCount); m_strName = strTemp; byte[][] ubTemp = new byte[newSize][]; Array.Copy(m_ubSignature, ubTemp, m_iLocalSymCount); m_ubSignature = ubTemp; } } #endregion #region Internal Members internal void AddLocalSymInfo(String strName,byte[] signature,int slot,int startOffset,int endOffset) { // make sure that arrays are large enough to hold addition info EnsureCapacity(); m_iStartOffset[m_iLocalSymCount] = startOffset; m_iEndOffset[m_iLocalSymCount] = endOffset; m_iLocalSlot[m_iLocalSymCount] = slot; m_strName[m_iLocalSymCount] = strName; m_ubSignature[m_iLocalSymCount] = signature; checked {m_iLocalSymCount++; } } internal void AddUsingNamespace(String strNamespace) { EnsureCapacityNamespace(); m_namespace[m_iNameSpaceCount] = strNamespace; checked { m_iNameSpaceCount++; } } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter) { int i; for (i = 0; i < m_iLocalSymCount; i ++) { symWriter.DefineLocalVariable( m_strName[i], FieldAttributes.PrivateScope, m_ubSignature[i], SymAddressKind.ILOffset, m_iLocalSlot[i], 0, // addr2 is not used yet 0, // addr3 is not used m_iStartOffset[i], m_iEndOffset[i]); } for (i = 0; i < m_iNameSpaceCount; i ++) { symWriter.UsingNamespace(m_namespace[i]); } } #endregion } /// <summary> /// Describes exception handler in a method body. /// </summary> [StructLayout(LayoutKind.Sequential)] [ComVisible(false)] public struct ExceptionHandler : IEquatable<ExceptionHandler> { // Keep in [....] with unmanged structure. internal readonly int m_exceptionClass; internal readonly int m_tryStartOffset; internal readonly int m_tryEndOffset; internal readonly int m_filterOffset; internal readonly int m_handlerStartOffset; internal readonly int m_handlerEndOffset; internal readonly ExceptionHandlingClauseOptions m_kind; public int ExceptionTypeToken { get { return m_exceptionClass; } } public int TryOffset { get { return m_tryStartOffset; } } public int TryLength { get { return m_tryEndOffset - m_tryStartOffset; } } public int FilterOffset { get { return m_filterOffset; } } public int HandlerOffset { get { return m_handlerStartOffset; } } public int HandlerLength { get { return m_handlerEndOffset - m_handlerStartOffset; } } public ExceptionHandlingClauseOptions Kind { get { return m_kind; } } #region Constructors /// <summary> /// Creates a description of an exception handler. /// </summary> /// <param name="tryOffset">The offset of the first instruction protected by this handler.</param> /// <param name="tryLength">The number of bytes protected by this handler.</param> /// <param name="filterOffset">The filter code begins at the specified offset and ends at the first instruction of the handler block. Specify 0 if not applicable (this is not a filter handler).</param> /// <param name="handlerOffset">The offset of the first instruction of this handler.</param> /// <param name="handlerLength">The number of bytes of the handler.</param> /// <param name="kind">The kind of handler, the handler might be a catch handler, filter handler, fault handler, or finally handler.</param> /// <param name="exceptionTypeToken">The token of the exception type handled by this handler. Specify 0 if not applicable (this is finally handler).</param> /// <exception cref="ArgumentOutOfRangeException"> /// Some of the instruction offset is negative, /// the end offset of specified range is less than its start offset, /// or <paramref name="kind"/> has an invalid value. /// </exception> public ExceptionHandler(int tryOffset, int tryLength, int filterOffset, int handlerOffset, int handlerLength, ExceptionHandlingClauseOptions kind, int exceptionTypeToken) { if (tryOffset < 0) { throw new ArgumentOutOfRangeException("tryOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (tryLength < 0) { throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (filterOffset < 0) { throw new ArgumentOutOfRangeException("filterOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (handlerOffset < 0) { throw new ArgumentOutOfRangeException("handlerOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (handlerLength < 0) { throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if ((long)tryOffset + tryLength > Int32.MaxValue) { throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - tryOffset)); } if ((long)handlerOffset + handlerLength > Int32.MaxValue) { throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - handlerOffset)); } // Other tokens migth also be invalid. We only check nil tokens as the implementation (SectEH_Emit in corhlpr.cpp) requires it, // and we can't check for valid tokens until the module is baked. if (kind == ExceptionHandlingClauseOptions.Clause && (exceptionTypeToken & 0x00FFFFFF) == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", exceptionTypeToken), "exceptionTypeToken"); } Contract.EndContractBlock(); if (!IsValidKind(kind)) { throw new ArgumentOutOfRangeException("kind", Environment.GetResourceString("ArgumentOutOfRange_Enum")); } m_tryStartOffset = tryOffset; m_tryEndOffset = tryOffset + tryLength; m_filterOffset = filterOffset; m_handlerStartOffset = handlerOffset; m_handlerEndOffset = handlerOffset + handlerLength; m_kind = kind; m_exceptionClass = exceptionTypeToken; } internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset, int kind, int exceptionTypeToken) { Contract.Assert(tryStartOffset >= 0); Contract.Assert(tryEndOffset >= 0); Contract.Assert(filterOffset >= 0); Contract.Assert(handlerStartOffset >= 0); Contract.Assert(handlerEndOffset >= 0); Contract.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind)); Contract.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0); m_tryStartOffset = tryStartOffset; m_tryEndOffset = tryEndOffset; m_filterOffset = filterOffset; m_handlerStartOffset = handlerStartOffset; m_handlerEndOffset = handlerEndOffset; m_kind = (ExceptionHandlingClauseOptions)kind; m_exceptionClass = exceptionTypeToken; } private static bool IsValidKind(ExceptionHandlingClauseOptions kind) { switch (kind) { case ExceptionHandlingClauseOptions.Clause: case ExceptionHandlingClauseOptions.Filter: case ExceptionHandlingClauseOptions.Finally: case ExceptionHandlingClauseOptions.Fault: return true; default: return false; } } #endregion #region Equality public override int GetHashCode() { return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind; } public override bool Equals(Object obj) { return obj is ExceptionHandler && Equals((ExceptionHandler)obj); } public bool Equals(ExceptionHandler other) { return other.m_exceptionClass == m_exceptionClass && other.m_tryStartOffset == m_tryStartOffset && other.m_tryEndOffset == m_tryEndOffset && other.m_filterOffset == m_filterOffset && other.m_handlerStartOffset == m_handlerStartOffset && other.m_handlerEndOffset == m_handlerEndOffset && other.m_kind == m_kind; } public static bool operator ==(ExceptionHandler left, ExceptionHandler right) { return left.Equals(right); } public static bool operator !=(ExceptionHandler left, ExceptionHandler right) { return !left.Equals(right); } #endregion } }
// // This file is part of the game Voxalia, created by FreneticXYZ. // This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license. // See README.md or LICENSE.txt for contents of the MIT license. // If these are not available, see https://opensource.org/licenses/MIT // using System.Collections.Generic; using BEPUutilities; using BEPUphysics.CollisionShapes; using BEPUphysics.CollisionShapes.ConvexShapes; namespace Voxalia.Shared.BlockShapes { public class BSD64_68: BlockShapeDetails { public MaterialSide[] Mats; public BSD64_68(params MaterialSide[] mats) { Mats = mats; BlockShapeCache = new BoxShape(1f, 1f, 1f); OffsetCache = new Location(0.5); ShrunkBlockShapeCache = new BoxShape(SHRINK_CONSTANT, SHRINK_CONSTANT, SHRINK_CONSTANT); ShrunkOffsetCache = new Location(SHRINK_CONSTANT * 0.5); } public override List<Vector3> GetVertices(Vector3 pos, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM) { List<Vector3> Vertices = new List<Vector3>(); if (!TOP) { Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z + 1)); } if (!BOTTOM) { Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z)); } if (!XP) { Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z)); } if (!XM) { Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z + 1)); } if (!YP) { Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z)); Vertices.Add(new Vector3(pos.X + 1, pos.Y + 1, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y + 1, pos.Z + 1)); } if (!YM) { Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z)); Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z + 1)); Vertices.Add(new Vector3(pos.X + 1, pos.Y, pos.Z + 1)); Vertices.Add(new Vector3(pos.X, pos.Y, pos.Z)); } return Vertices; } public override List<Vector3> GetNormals(Vector3 blockPos, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM) { List<Vector3> Norms = new List<Vector3>(); if (!TOP) { for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(0, 0, 1)); } } if (!BOTTOM) { for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(0, 0, -1)); } } if (!XP) { for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(1, 0, 0)); } } if (!XM) { for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(-1, 0, 0)); } } if (!YP) { for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(0, 1, 0)); } } if (!YM) { for (int i = 0; i < 6; i++) { Norms.Add(new Vector3(0, -1, 0)); } } return Norms; } public override List<Vector3> GetTCoords(Vector3 blockPos, Material mat, bool XP, bool XM, bool YP, bool YM, bool TOP, bool BOTTOM) { List<Vector3> TCoords = new List<Vector3>(); if (!TOP) { int tID_TOP = mat.TextureID(Mats[0]); TCoords.Add(new Vector3(0, 1, tID_TOP)); TCoords.Add(new Vector3(1, 1, tID_TOP)); TCoords.Add(new Vector3(0, 0, tID_TOP)); TCoords.Add(new Vector3(1, 1, tID_TOP)); TCoords.Add(new Vector3(1, 0, tID_TOP)); TCoords.Add(new Vector3(0, 0, tID_TOP)); } if (!BOTTOM) { int tID_BOTTOM = mat.TextureID(Mats[1]); TCoords.Add(new Vector3(0, 0, tID_BOTTOM)); TCoords.Add(new Vector3(1, 1, tID_BOTTOM)); TCoords.Add(new Vector3(0, 1, tID_BOTTOM)); TCoords.Add(new Vector3(0, 0, tID_BOTTOM)); TCoords.Add(new Vector3(1, 0, tID_BOTTOM)); TCoords.Add(new Vector3(1, 1, tID_BOTTOM)); } if (!XP) { int tID_XP = mat.TextureID(Mats[2]); TCoords.Add(new Vector3(1, 0, tID_XP)); TCoords.Add(new Vector3(1, 1, tID_XP)); TCoords.Add(new Vector3(0, 1, tID_XP)); TCoords.Add(new Vector3(0, 0, tID_XP)); TCoords.Add(new Vector3(1, 0, tID_XP)); TCoords.Add(new Vector3(0, 1, tID_XP)); } if (!XM) { int tID_XM = mat.TextureID(Mats[3]); TCoords.Add(new Vector3(1, 1, tID_XM)); TCoords.Add(new Vector3(0, 1, tID_XM)); TCoords.Add(new Vector3(0, 0, tID_XM)); TCoords.Add(new Vector3(1, 1, tID_XM)); TCoords.Add(new Vector3(0, 0, tID_XM)); TCoords.Add(new Vector3(1, 0, tID_XM)); } if (!YP) { int tID_YP = mat.TextureID(Mats[4]); TCoords.Add(new Vector3(1, 1, tID_YP)); TCoords.Add(new Vector3(0, 1, tID_YP)); TCoords.Add(new Vector3(0, 0, tID_YP)); TCoords.Add(new Vector3(1, 1, tID_YP)); TCoords.Add(new Vector3(0, 0, tID_YP)); TCoords.Add(new Vector3(1, 0, tID_YP)); } if (!YM) { int tID_YM = mat.TextureID(Mats[5]); TCoords.Add(new Vector3(1, 0, tID_YM)); TCoords.Add(new Vector3(1, 1, tID_YM)); TCoords.Add(new Vector3(0, 1, tID_YM)); TCoords.Add(new Vector3(0, 0, tID_YM)); TCoords.Add(new Vector3(1, 0, tID_YM)); TCoords.Add(new Vector3(0, 1, tID_YM)); } return TCoords; } public override bool OccupiesXP() { return true; } public override bool OccupiesYP() { return true; } public override bool OccupiesXM() { return true; } public override bool OccupiesYM() { return true; } public override bool OccupiesTOP() { return true; } public override bool OccupiesBOTTOM() { return true; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Platform; using Gdk; using Action = System.Action; using WindowEdge = Avalonia.Controls.WindowEdge; using GLib; using Avalonia.Rendering; namespace Avalonia.Gtk { using Gtk = global::Gtk; public abstract class TopLevelImpl : ITopLevelImpl { private IInputRoot _inputRoot; private Gtk.Widget _widget; private FramebufferManager _framebuffer; private Gtk.IMContext _imContext; private uint _lastKeyEventTimestamp; private static readonly Gdk.Cursor DefaultCursor = new Gdk.Cursor(CursorType.LeftPtr); protected TopLevelImpl(Gtk.Widget window) { _widget = window; _framebuffer = new FramebufferManager(this); Init(); } void Init() { Handle = _widget as IPlatformHandle; _widget.Events = EventMask.AllEventsMask; _imContext = new Gtk.IMMulticontext(); _imContext.Commit += ImContext_Commit; _widget.Realized += OnRealized; _widget.Realize(); _widget.ButtonPressEvent += OnButtonPressEvent; _widget.ButtonReleaseEvent += OnButtonReleaseEvent; _widget.ScrollEvent += OnScrollEvent; _widget.Destroyed += OnDestroyed; _widget.KeyPressEvent += OnKeyPressEvent; _widget.KeyReleaseEvent += OnKeyReleaseEvent; _widget.ExposeEvent += OnExposeEvent; _widget.MotionNotifyEvent += OnMotionNotifyEvent; } public IPlatformHandle Handle { get; private set; } public Gtk.Widget Widget => _widget; public Gdk.Drawable CurrentDrawable { get; private set; } void OnRealized (object sender, EventArgs eventArgs) { _imContext.ClientWindow = _widget.GdkWindow; } public abstract Size ClientSize { get; } public Size MaxClientSize { get { // TODO: This should take into account things such as taskbar and window border // thickness etc. return new Size(_widget.Screen.Width, _widget.Screen.Height); } } public IMouseDevice MouseDevice => GtkMouseDevice.Instance; public Avalonia.Controls.WindowState WindowState { get { switch (_widget.GdkWindow.State) { case Gdk.WindowState.Iconified: return Controls.WindowState.Minimized; case Gdk.WindowState.Maximized: return Controls.WindowState.Maximized; default: return Controls.WindowState.Normal; } } set { switch (value) { case Controls.WindowState.Minimized: _widget.GdkWindow.Iconify(); break; case Controls.WindowState.Maximized: _widget.GdkWindow.Maximize(); break; case Controls.WindowState.Normal: _widget.GdkWindow.Deiconify(); _widget.GdkWindow.Unmaximize(); break; } } } public double Scaling => 1; public Action Activated { get; set; } public Action Closed { get; set; } public Action Deactivated { get; set; } public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size> Resized { get; set; } public Action<Point> PositionChanged { get; set; } public Action<double> ScalingChanged { get; set; } public IEnumerable<object> Surfaces => new object[] { Handle, new Func<Gdk.Drawable>(() => CurrentDrawable), _framebuffer }; public IPopupImpl CreatePopup() { return new PopupImpl(); } public IRenderer CreateRenderer(IRenderRoot root) { return new ImmediateRenderer(root); } public void Invalidate(Rect rect) { if (_widget?.GdkWindow != null) _widget.GdkWindow.InvalidateRect( new Rectangle((int) rect.X, (int) rect.Y, (int) rect.Width, (int) rect.Height), true); } public Point PointToClient(Point point) { int x, y; _widget.GdkWindow.GetDeskrelativeOrigin(out x, out y); return new Point(point.X - x, point.Y - y); } public Point PointToScreen(Point point) { int x, y; _widget.GdkWindow.GetDeskrelativeOrigin(out x, out y); return new Point(point.X + x, point.Y + y); } public void SetInputRoot(IInputRoot inputRoot) { _inputRoot = inputRoot; } public void SetCursor(IPlatformHandle cursor) { _widget.GdkWindow.Cursor = cursor != null ? new Gdk.Cursor(cursor.Handle) : DefaultCursor; } public void Show() => _widget.Show(); public void Hide() => _widget.Hide(); private static InputModifiers GetModifierKeys(ModifierType state) { var rv = InputModifiers.None; if (state.HasFlag(ModifierType.ControlMask)) rv |= InputModifiers.Control; if (state.HasFlag(ModifierType.ShiftMask)) rv |= InputModifiers.Shift; if (state.HasFlag(ModifierType.Mod1Mask)) rv |= InputModifiers.Control; if(state.HasFlag(ModifierType.Button1Mask)) rv |= InputModifiers.LeftMouseButton; if (state.HasFlag(ModifierType.Button2Mask)) rv |= InputModifiers.RightMouseButton; if (state.HasFlag(ModifierType.Button3Mask)) rv |= InputModifiers.MiddleMouseButton; return rv; } void OnButtonPressEvent(object o, Gtk.ButtonPressEventArgs args) { var evnt = args.Event; var e = new RawMouseEventArgs( GtkMouseDevice.Instance, evnt.Time, _inputRoot, evnt.Button == 1 ? RawMouseEventType.LeftButtonDown : evnt.Button == 3 ? RawMouseEventType.RightButtonDown : RawMouseEventType.MiddleButtonDown, new Point(evnt.X, evnt.Y), GetModifierKeys(evnt.State)); Input(e); } void OnScrollEvent(object o, Gtk.ScrollEventArgs args) { var evnt = args.Event; double step = 1; var delta = new Vector(); if (evnt.Direction == ScrollDirection.Down) delta = new Vector(0, -step); else if (evnt.Direction == ScrollDirection.Up) delta = new Vector(0, step); else if (evnt.Direction == ScrollDirection.Right) delta = new Vector(-step, 0); if (evnt.Direction == ScrollDirection.Left) delta = new Vector(step, 0); var e = new RawMouseWheelEventArgs(GtkMouseDevice.Instance, evnt.Time, _inputRoot, new Point(evnt.X, evnt.Y), delta, GetModifierKeys(evnt.State)); Input(e); } protected void OnButtonReleaseEvent(object o, Gtk.ButtonReleaseEventArgs args) { var evnt = args.Event; var e = new RawMouseEventArgs( GtkMouseDevice.Instance, evnt.Time, _inputRoot, evnt.Button == 1 ? RawMouseEventType.LeftButtonUp : evnt.Button == 3 ? RawMouseEventType.RightButtonUp : RawMouseEventType.MiddleButtonUp, new Point(evnt.X, evnt.Y), GetModifierKeys(evnt.State)); Input(e); } void OnDestroyed(object sender, EventArgs eventArgs) { Closed(); } private void ProcessKeyEvent(EventKey evnt) { _lastKeyEventTimestamp = evnt.Time; if (_imContext.FilterKeypress(evnt)) return; var e = new RawKeyEventArgs( GtkKeyboardDevice.Instance, evnt.Time, evnt.Type == EventType.KeyPress ? RawKeyEventType.KeyDown : RawKeyEventType.KeyUp, Common.KeyTransform.ConvertKey(evnt.Key), GetModifierKeys(evnt.State)); Input(e); } [ConnectBefore] void OnKeyPressEvent(object o, Gtk.KeyPressEventArgs args) { args.RetVal = true; ProcessKeyEvent(args.Event); } void OnKeyReleaseEvent(object o, Gtk.KeyReleaseEventArgs args) { args.RetVal = true; ProcessKeyEvent(args.Event); } private void ImContext_Commit(object o, Gtk.CommitArgs args) { Input(new RawTextInputEventArgs(GtkKeyboardDevice.Instance, _lastKeyEventTimestamp, args.Str)); } void OnExposeEvent(object o, Gtk.ExposeEventArgs args) { CurrentDrawable = args.Event.Window; Paint(args.Event.Area.ToAvalonia()); CurrentDrawable = null; args.RetVal = true; } void OnMotionNotifyEvent(object o, Gtk.MotionNotifyEventArgs args) { var evnt = args.Event; var position = new Point(evnt.X, evnt.Y); GtkMouseDevice.Instance.SetClientPosition(position); var e = new RawMouseEventArgs( GtkMouseDevice.Instance, evnt.Time, _inputRoot, RawMouseEventType.Move, position, GetModifierKeys(evnt.State)); Input(e); args.RetVal = true; } public void Dispose() { _framebuffer.Dispose(); _widget.Hide(); _widget.Dispose(); _widget = null; } } }
using System; using System.ComponentModel; using System.Linq; using Umbraco.Core; using Umbraco.Core.Sync; using umbraco.interfaces; namespace Umbraco.Web.Cache { /// <summary> /// Represents the entry point into Umbraco's distributed cache infrastructure. /// </summary> /// <remarks> /// <para> /// The distributed cache infrastructure ensures that distributed caches are /// invalidated properly in load balancing environments. /// </para> /// <para> /// Distribute caches include static (in-memory) cache, runtime cache, front-end content cache, Examine/Lucene indexes /// </para> /// </remarks> public sealed class DistributedCache { #region Public constants/Ids public const string ApplicationTreeCacheRefresherId = "0AC6C028-9860-4EA4-958D-14D39F45886E"; public const string ApplicationCacheRefresherId = "B15F34A1-BC1D-4F8B-8369-3222728AB4C8"; public const string TemplateRefresherId = "DD12B6A0-14B9-46e8-8800-C154F74047C8"; public const string PageCacheRefresherId = "27AB3022-3DFA-47b6-9119-5945BC88FD66"; public const string UnpublishedPageCacheRefresherId = "55698352-DFC5-4DBE-96BD-A4A0F6F77145"; public const string MemberCacheRefresherId = "E285DF34-ACDC-4226-AE32-C0CB5CF388DA"; public const string MemberGroupCacheRefresherId = "187F236B-BD21-4C85-8A7C-29FBA3D6C00C"; public const string MediaCacheRefresherId = "B29286DD-2D40-4DDB-B325-681226589FEC"; public const string MacroCacheRefresherId = "7B1E683C-5F34-43dd-803D-9699EA1E98CA"; public const string UserCacheRefresherId = "E057AF6D-2EE6-41F4-8045-3694010F0AA6"; public const string UserGroupCacheRefresherId = "45178038-B232-4FE8-AA1A-F2B949C44762"; public const string UserGroupPermissionsCacheRefresherId = "840AB9C5-5C0B-48DB-A77E-29FE4B80CD3A"; public const string ContentTypeCacheRefresherId = "6902E22C-9C10-483C-91F3-66B7CAE9E2F5"; public const string LanguageCacheRefresherId = "3E0F95D8-0BE5-44B8-8394-2B8750B62654"; public const string DomainCacheRefresherId = "11290A79-4B57-4C99-AD72-7748A3CF38AF"; public const string RelationTypeCacheRefresherId = "D8375ABA-4FB3-4F86-B505-92FBA1B6F7C9"; [Obsolete("This is no longer used and will be removed in future versions")] [EditorBrowsable(EditorBrowsableState.Never)] public const string StylesheetCacheRefresherId = "E0633648-0DEB-44AE-9A48-75C3A55CB670"; public const string StylesheetPropertyCacheRefresherId = "2BC7A3A4-6EB1-4FBC-BAA3-C9E7B6D36D38"; public const string DataTypeCacheRefresherId = "35B16C25-A17E-45D7-BC8F-EDAB1DCC28D2"; public const string DictionaryCacheRefresherId = "D1D7E227-F817-4816-BFE9-6C39B6152884"; public const string PublicAccessCacheRefresherId = "1DB08769-B104-4F8B-850E-169CAC1DF2EC"; public static readonly Guid ApplicationTreeCacheRefresherGuid = new Guid(ApplicationTreeCacheRefresherId); public static readonly Guid ApplicationCacheRefresherGuid = new Guid(ApplicationCacheRefresherId); public static readonly Guid TemplateRefresherGuid = new Guid(TemplateRefresherId); public static readonly Guid PageCacheRefresherGuid = new Guid(PageCacheRefresherId); public static readonly Guid UnpublishedPageCacheRefresherGuid = new Guid(UnpublishedPageCacheRefresherId); public static readonly Guid MemberCacheRefresherGuid = new Guid(MemberCacheRefresherId); public static readonly Guid MemberGroupCacheRefresherGuid = new Guid(MemberGroupCacheRefresherId); public static readonly Guid MediaCacheRefresherGuid = new Guid(MediaCacheRefresherId); public static readonly Guid MacroCacheRefresherGuid = new Guid(MacroCacheRefresherId); public static readonly Guid UserCacheRefresherGuid = new Guid(UserCacheRefresherId); public static readonly Guid UserGroupCacheRefresherGuid = new Guid(UserGroupCacheRefresherId); public static readonly Guid UserGroupPermissionsCacheRefresherGuid = new Guid(UserGroupPermissionsCacheRefresherId); public static readonly Guid ContentTypeCacheRefresherGuid = new Guid(ContentTypeCacheRefresherId); public static readonly Guid LanguageCacheRefresherGuid = new Guid(LanguageCacheRefresherId); public static readonly Guid DomainCacheRefresherGuid = new Guid(DomainCacheRefresherId); public static readonly Guid StylesheetCacheRefresherGuid = new Guid(StylesheetCacheRefresherId); public static readonly Guid StylesheetPropertyCacheRefresherGuid = new Guid(StylesheetPropertyCacheRefresherId); public static readonly Guid DataTypeCacheRefresherGuid = new Guid(DataTypeCacheRefresherId); public static readonly Guid DictionaryCacheRefresherGuid = new Guid(DictionaryCacheRefresherId); public static readonly Guid PublicAccessCacheRefresherGuid = new Guid(PublicAccessCacheRefresherId); public static readonly Guid RelationTypeCacheRefresherGuid = new Guid(RelationTypeCacheRefresherId); #endregion #region Constructor & Singleton // note - should inject into the application instead of using a singleton private static readonly DistributedCache InstanceObject = new DistributedCache(); /// <summary> /// Initializes a new instance of the <see cref="DistributedCache"/> class. /// </summary> private DistributedCache() { } /// <summary> /// Gets the static unique instance of the <see cref="DistributedCache"/> class. /// </summary> /// <returns>The static unique instance of the <see cref="DistributedCache"/> class.</returns> /// <remarks>Exists so that extension methods can be added to the distributed cache.</remarks> public static DistributedCache Instance { get { return InstanceObject; } } #endregion #region Core notification methods /// <summary> /// Notifies the distributed cache of specifieds item invalidation, for a specified <see cref="ICacheRefresher"/>. /// </summary> /// <typeparam name="T">The type of the invalidated items.</typeparam> /// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param> /// <param name="getNumericId">A function returning the unique identifier of items.</param> /// <param name="instances">The invalidated items.</param> /// <remarks> /// This method is much better for performance because it does not need to re-lookup object instances. /// </remarks> public void Refresh<T>(Guid factoryGuid, Func<T, int> getNumericId, params T[] instances) { if (factoryGuid == Guid.Empty || instances.Length == 0 || getNumericId == null) return; ServerMessengerResolver.Current.Messenger.PerformRefresh( ServerRegistrarResolver.Current.Registrar.Registrations, GetRefresherById(factoryGuid), getNumericId, instances); } /// <summary> /// Notifies the distributed cache of a specified item invalidation, for a specified <see cref="ICacheRefresher"/>. /// </summary> /// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param> /// <param name="id">The unique identifier of the invalidated item.</param> public void Refresh(Guid factoryGuid, int id) { if (factoryGuid == Guid.Empty || id == default(int)) return; ServerMessengerResolver.Current.Messenger.PerformRefresh( ServerRegistrarResolver.Current.Registrar.Registrations, GetRefresherById(factoryGuid), id); } /// <summary> /// Notifies the distributed cache of a specified item invalidation, for a specified <see cref="ICacheRefresher"/>. /// </summary> /// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param> /// <param name="id">The unique identifier of the invalidated item.</param> public void Refresh(Guid factoryGuid, Guid id) { if (factoryGuid == Guid.Empty || id == Guid.Empty) return; ServerMessengerResolver.Current.Messenger.PerformRefresh( ServerRegistrarResolver.Current.Registrar.Registrations, GetRefresherById(factoryGuid), id); } public void RefreshByPayload(Guid factoryGuid, object payload) { if (factoryGuid == Guid.Empty || payload == null) return; ServerMessengerResolver.Current.Messenger.PerformRefresh( ServerRegistrarResolver.Current.Registrar.Registrations, GetRefresherById(factoryGuid), payload); } /// <summary> /// Notifies the distributed cache, for a specified <see cref="ICacheRefresher"/>. /// </summary> /// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param> /// <param name="jsonPayload">The notification content.</param> public void RefreshByJson(Guid factoryGuid, string jsonPayload) { if (factoryGuid == Guid.Empty || jsonPayload.IsNullOrWhiteSpace()) return; ServerMessengerResolver.Current.Messenger.PerformRefresh( ServerRegistrarResolver.Current.Registrar.Registrations, GetRefresherById(factoryGuid), jsonPayload); } ///// <summary> ///// Notifies the distributed cache, for a specified <see cref="ICacheRefresher"/>. ///// </summary> ///// <param name="refresherId">The unique identifier of the ICacheRefresher.</param> ///// <param name="payload">The notification content.</param> //internal void Notify(Guid refresherId, object payload) //{ // if (refresherId == Guid.Empty || payload == null) return; // ServerMessengerResolver.Current.Messenger.Notify( // ServerRegistrarResolver.Current.Registrar.Registrations, // GetRefresherById(refresherId), // json); //} /// <summary> /// Notifies the distributed cache of a global invalidation for a specified <see cref="ICacheRefresher"/>. /// </summary> /// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param> public void RefreshAll(Guid factoryGuid) { if (factoryGuid == Guid.Empty) return; ServerMessengerResolver.Current.Messenger.PerformRefreshAll( ServerRegistrarResolver.Current.Registrar.Registrations, GetRefresherById(factoryGuid)); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is no longer in use and does not work as advertised, the allServers parameter doesnt have any affect for database server messengers, do not use!")] public void RefreshAll(Guid factoryGuid, bool allServers) { if (factoryGuid == Guid.Empty) return; if (allServers) { RefreshAll(factoryGuid); } else { ServerMessengerResolver.Current.Messenger.PerformRefreshAll( Enumerable.Empty<IServerAddress>(), GetRefresherById(factoryGuid)); } } /// <summary> /// Notifies the distributed cache of a specified item removal, for a specified <see cref="ICacheRefresher"/>. /// </summary> /// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param> /// <param name="id">The unique identifier of the removed item.</param> public void Remove(Guid factoryGuid, int id) { if (factoryGuid == Guid.Empty || id == default(int)) return; ServerMessengerResolver.Current.Messenger.PerformRemove( ServerRegistrarResolver.Current.Registrar.Registrations, GetRefresherById(factoryGuid), id); } /// <summary> /// Notifies the distributed cache of specifieds item removal, for a specified <see cref="ICacheRefresher"/>. /// </summary> /// <typeparam name="T">The type of the removed items.</typeparam> /// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param> /// <param name="getNumericId">A function returning the unique identifier of items.</param> /// <param name="instances">The removed items.</param> /// <remarks> /// This method is much better for performance because it does not need to re-lookup object instances. /// </remarks> public void Remove<T>(Guid factoryGuid, Func<T, int> getNumericId, params T[] instances) { ServerMessengerResolver.Current.Messenger.PerformRemove( ServerRegistrarResolver.Current.Registrar.Registrations, GetRefresherById(factoryGuid), getNumericId, instances); } #endregion // helper method to get an ICacheRefresher by its unique identifier private static ICacheRefresher GetRefresherById(Guid uniqueIdentifier) { return CacheRefreshersResolver.Current.GetById(uniqueIdentifier); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.IO; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; using UnityEngine.Networking; namespace HoloToolkit.Unity { /// <summary> /// Renders the UI and handles update logic for HoloToolkit/Configure/Apply HoloLens Project Settings. /// </summary> public class ProjectSettingsWindow : AutoConfigureWindow<ProjectSettingsWindow.ProjectSetting> { private const string SharingServiceURL = "https://raw.githubusercontent.com/Microsoft/MixedRealityToolkit-Unity/master/External/HoloToolkit/Sharing/Server/SharingService.exe"; private const string InputManagerAssetURL = "https://raw.githubusercontent.com/Microsoft/MixedRealityToolkit-Unity/master/ProjectSettings/InputManager.asset"; #region Nested Types public enum ProjectSetting { BuildWsaUwp, WsaEnableXR, WsaUwpBuildToD3D, TargetOccludedDevices, SharingServices, XboxControllerSupport, DotNetScriptingBackend, } #endregion // Nested Types #region Overrides / Event Handlers protected override void ApplySettings() { // Apply individual settings if (Values[ProjectSetting.BuildWsaUwp]) { if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.WSAPlayer) { #if UNITY_2017_1_OR_NEWER EditorUserBuildSettings.SwitchActiveBuildTargetAsync(BuildTargetGroup.WSA, BuildTarget.WSAPlayer); #else EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.WSA, BuildTarget.WSAPlayer); #endif } else { UpdateSettings(EditorUserBuildSettings.activeBuildTarget); } } else { EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows64); } } protected override void LoadSettings() { for (int i = (int)ProjectSetting.BuildWsaUwp; i <= (int)ProjectSetting.DotNetScriptingBackend; i++) { switch ((ProjectSetting)i) { case ProjectSetting.BuildWsaUwp: case ProjectSetting.WsaEnableXR: case ProjectSetting.WsaUwpBuildToD3D: case ProjectSetting.DotNetScriptingBackend: Values[(ProjectSetting)i] = true; break; case ProjectSetting.TargetOccludedDevices: Values[(ProjectSetting)i] = EditorPrefsUtility.GetEditorPref(Names[(ProjectSetting)i], false); break; case ProjectSetting.SharingServices: Values[(ProjectSetting)i] = EditorPrefsUtility.GetEditorPref(Names[(ProjectSetting)i], false); break; case ProjectSetting.XboxControllerSupport: Values[(ProjectSetting)i] = EditorPrefsUtility.GetEditorPref(Names[(ProjectSetting)i], false); break; default: throw new ArgumentOutOfRangeException(); } } } private void UpdateSettings(BuildTarget currentBuildTarget) { EditorPrefsUtility.SetEditorPref(Names[ProjectSetting.SharingServices], Values[ProjectSetting.SharingServices]); if (Values[ProjectSetting.SharingServices]) { string sharingServiceDirectory = Directory.GetParent(Path.GetFullPath(Application.dataPath)).FullName + "\\External\\HoloToolkit\\Sharing\\Server"; string sharingServicePath = sharingServiceDirectory + "\\SharingService.exe"; if (!File.Exists(sharingServicePath) && EditorUtility.DisplayDialog("Attention!", "You're missing the Sharing Service Executable in your project.\n\n" + "Would you like to download the missing files from GitHub?\n\n" + "Alternatively, you can download it yourself or specify a target IP to connect to at runtime on the Sharing Stage.", "Yes", "Cancel")) { using (var webRequest = UnityWebRequest.Get(SharingServiceURL)) { #if UNITY_2017_2_OR_NEWER webRequest.SendWebRequest(); #else webRequest.Send(); #endif while (!webRequest.isDone) { if (webRequest.downloadProgress != -1) { EditorUtility.DisplayProgressBar( "Downloading the SharingService executable from GitHub", "Progress...", webRequest.downloadProgress); } } EditorUtility.ClearProgressBar(); #if UNITY_2017_1_OR_NEWER if (webRequest.isNetworkError || webRequest.isHttpError) #else if (webRequest.isError) #endif { Debug.LogError("Network Error: " + webRequest.error); } else { byte[] sharingServiceData = webRequest.downloadHandler.data; Directory.CreateDirectory(sharingServiceDirectory); File.WriteAllBytes(sharingServicePath, sharingServiceData); } } } else { Debug.LogFormat("Alternatively, you can download from this link: {0}", SharingServiceURL); } PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.InternetClientServer, true); PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.PrivateNetworkClientServer, true); } else { PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.InternetClient, false); PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.InternetClientServer, false); PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.PrivateNetworkClientServer, false); } var inputManagerPath = Directory.GetParent(Path.GetFullPath(Application.dataPath)).FullName + "\\ProjectSettings\\InputManager.asset"; bool userPermission = Values[ProjectSetting.XboxControllerSupport]; if (userPermission) { userPermission = EditorUtility.DisplayDialog("Attention!", "Hi there, we noticed that you've enabled the Xbox Controller support.\n\n" + "Do you give us permission to download the latest input mapping definitions from " + "the Mixed Reality Toolkit's GitHub page and replace your project's InputManager.asset?\n\n", "OK", "Cancel"); if (userPermission) { using (var webRequest = UnityWebRequest.Get(InputManagerAssetURL)) { #if UNITY_2017_2_OR_NEWER webRequest.SendWebRequest(); #else webRequest.Send(); #endif while (!webRequest.isDone) { if (webRequest.downloadProgress != -1) { EditorUtility.DisplayProgressBar("Downloading InputManager.asset from GitHub", "Progress...", webRequest.downloadProgress); } } EditorUtility.ClearProgressBar(); #if UNITY_2017_1_OR_NEWER if (webRequest.isNetworkError || webRequest.isHttpError) #else if (webRequest.isError) #endif { Debug.LogError("Network Error: " + webRequest.error); userPermission = false; } else { File.Copy(inputManagerPath, inputManagerPath + ".old", true); File.WriteAllText(inputManagerPath, webRequest.downloadHandler.text); } } } } if (!userPermission) { Values[ProjectSetting.XboxControllerSupport] = false; if (File.Exists(inputManagerPath + ".old")) { File.Copy(inputManagerPath + ".old", inputManagerPath, true); File.Delete(inputManagerPath + ".old"); Debug.Log("Previous Input Mapping Restored."); } else { Debug.LogWarning("No old Input Mapping found!"); } } EditorPrefsUtility.SetEditorPref(Names[ProjectSetting.XboxControllerSupport], Values[ProjectSetting.XboxControllerSupport]); if (currentBuildTarget != BuildTarget.WSAPlayer) { AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); Close(); return; } EditorUserBuildSettings.wsaUWPBuildType = Values[ProjectSetting.WsaUwpBuildToD3D] ? WSAUWPBuildType.D3D : WSAUWPBuildType.XAML; UnityEditorInternal.VR.VREditor.SetVREnabledOnTargetGroup(BuildTargetGroup.WSA, Values[ProjectSetting.WsaEnableXR]); if (!Values[ProjectSetting.WsaEnableXR]) { EditorUserBuildSettings.wsaSubtarget = WSASubtarget.AnyDevice; UnityEditorInternal.VR.VREditor.SetVREnabledDevicesOnTargetGroup(BuildTargetGroup.WSA, new[] { "None" }); PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.HumanInterfaceDevice, false); BuildDeployPrefs.BuildPlatform = "Any CPU"; } else { #if !UNITY_2017_2_OR_NEWER Values[ProjectSetting.TargetOccludedDevices] = false; #endif if (!Values[ProjectSetting.TargetOccludedDevices]) { EditorUserBuildSettings.wsaSubtarget = WSASubtarget.HoloLens; UnityEditorInternal.VR.VREditor.SetVREnabledDevicesOnTargetGroup(BuildTargetGroup.WSA, new[] { "HoloLens" }); PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.HumanInterfaceDevice, Values[ProjectSetting.XboxControllerSupport]); BuildDeployPrefs.BuildPlatform = "x86"; for (var i = 0; i < QualitySettings.names.Length; i++) { QualitySettings.DecreaseLevel(true); } } else { EditorUserBuildSettings.wsaSubtarget = WSASubtarget.PC; UnityEditorInternal.VR.VREditor.SetVREnabledDevicesOnTargetGroup(BuildTargetGroup.WSA, new[] { "stereo" }); PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.HumanInterfaceDevice, false); BuildDeployPrefs.BuildPlatform = "x64"; for (var i = 0; i < QualitySettings.names.Length; i++) { QualitySettings.IncreaseLevel(true); } } int currentQualityLevel = QualitySettings.GetQualityLevel(); // HACK: Edits QualitySettings.asset Directly // TODO: replace with friendlier version that uses built in APIs when Unity fixes or makes available. // See: http://answers.unity3d.com/questions/886160/how-do-i-change-qualitysetting-for-my-platform-fro.html try { // Find the WSA element under the platform quality list and replace it's value with the current level. string settingsPath = "ProjectSettings/QualitySettings.asset"; string matchPattern = @"(m_PerPlatformDefaultQuality.*Windows Store Apps:) (\d+)"; string replacePattern = @"$1 " + currentQualityLevel; string settings = File.ReadAllText(settingsPath); settings = Regex.Replace(settings, matchPattern, replacePattern, RegexOptions.Singleline); File.WriteAllText(settingsPath, settings); } catch (Exception e) { Debug.LogException(e); } } EditorPrefsUtility.SetEditorPref(Names[ProjectSetting.TargetOccludedDevices], Values[ProjectSetting.TargetOccludedDevices]); PlayerSettings.SetScriptingBackend(BuildTargetGroup.WSA, Values[ProjectSetting.DotNetScriptingBackend] ? ScriptingImplementation.WinRTDotNET : ScriptingImplementation.IL2CPP); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); Close(); } protected override void OnGuiChanged() { } protected override void LoadStrings() { Names[ProjectSetting.BuildWsaUwp] = "Target Windows Universal UWP"; Descriptions[ProjectSetting.BuildWsaUwp] = "<b>Required</b>\n\n" + "Switches the currently active target to produce a Store app targeting the Universal Windows Platform.\n\n" + "<color=#ffff00ff><b>Note:</b></color> Cross platform development can be done with this toolkit, but many features and" + "tools will not work if the build target is not Windows Universal."; Names[ProjectSetting.WsaEnableXR] = "Enable XR"; Descriptions[ProjectSetting.WsaEnableXR] = "<b>Required</b>\n\n" + "Enables 'Windows Holographic' for Windows Store apps.\n\n" + "If disabled, your application will run as a normal UWP app on PC, and will launch as a 2D app on HoloLens.\n\n" + "<color=#ff0000ff><b>Warning!</b></color> HoloLens and tools like 'Holographic Remoting' will not function without this enabled."; Names[ProjectSetting.WsaUwpBuildToD3D] = "Build for Direct3D"; Descriptions[ProjectSetting.WsaUwpBuildToD3D] = "Recommended\n\n" + "Produces an app that targets Direct3D instead of Xaml.\n\n" + "Pure Direct3D apps run faster than applications that include Xaml. This option should remain checked unless you plan to " + "overlay Unity content with Xaml content or you plan to switch between Unity views and Xaml views at runtime."; Names[ProjectSetting.TargetOccludedDevices] = "Target Occluded Devices"; Descriptions[ProjectSetting.TargetOccludedDevices] = "Changes the target Device and updates the default quality settings, if needed. Occluded devices are generally VR hardware (like the Acer HMD) " + "that do not have a 'see through' display, while transparent devices (like the HoloLens) are generally AR hardware where users can see " + "and interact with digital elements in the physical world around them.\n\n" + #if !UNITY_2017_2_OR_NEWER "<color=#ff0000ff><b>Warning!</b></color> Occluded Devices are only supported in Unity 2017.2 and newer and cannot be enabled.\n\n" + #endif "<color=#ffff00ff><b>Note:</b></color> If you're not targeting Occluded devices, It's generally recommended that Transparent devices use " + "the lowest default quality setting, and is set automatically for you. This can be manually changed in your the Project's Quality Settings."; Names[ProjectSetting.SharingServices] = "Enable Sharing Services"; Descriptions[ProjectSetting.SharingServices] = "Enables the use of the Sharing Services in your project for all apps on any platform.\n\n" + "<color=#ffff00ff><b>Note:</b></color> Start the Sharing Server via 'HoloToolkit/Sharing Service/Launch Sharing Service'.\n\n" + "<color=#ffff00ff><b>Note:</b></color> The InternetClientServer and PrivateNetworkClientServer capabilities will be enabled in the " + "appx manifest for you."; Names[ProjectSetting.XboxControllerSupport] = "Enable Xbox Controller Support"; Descriptions[ProjectSetting.XboxControllerSupport] = "Enables the use of Xbox Controller support for all apps on any platform.\n\n" + "<color=#ff0000ff><b>Warning!</b></color> Enabling this feature will copy your old InputManager.asset and append it with \".old\". " + "To revert simply disable Xbox Controller Support.\n\n" + "<color=#ffff00ff><b>Note:</b></color> ONLY the HoloLens platform target requires the HID capabilities be defined in the appx manifest. " + "This capability is automatically enabled for you if you enable Xbox Controller Support and enable VR and target the HoloLens device."; Names[ProjectSetting.DotNetScriptingBackend] = "Enable .NET scripting backend"; Descriptions[ProjectSetting.DotNetScriptingBackend] = "Recommended\n\n" + "If you have the .NET unity module installed this will update the backend scripting profile, otherwise the scripting backend will be IL2CPP."; } protected override void OnEnable() { base.OnEnable(); #if UNITY_2017_1_OR_NEWER AutoConfigureMenu.ActiveBuildTargetChanged += UpdateSettings; #endif minSize = new Vector2(350, 350); maxSize = minSize; } #endregion // Overrides / Event Handlers } }
using System; using System.Runtime.InteropServices; using System.Security; using BulletSharp.Math; namespace BulletSharp { public abstract class DiscreteCollisionDetectorInterface : IDisposable { public class ClosestPointInput : IDisposable { internal IntPtr _native; public ClosestPointInput() { _native = btDiscreteCollisionDetectorInterface_ClosestPointInput_new(); } public float MaximumDistanceSquared { get { return btDiscreteCollisionDetectorInterface_ClosestPointInput_getMaximumDistanceSquared(_native); } set { btDiscreteCollisionDetectorInterface_ClosestPointInput_setMaximumDistanceSquared(_native, value); } } public Matrix TransformA { get { Matrix value; btDiscreteCollisionDetectorInterface_ClosestPointInput_getTransformA(_native, out value); return value; } set { btDiscreteCollisionDetectorInterface_ClosestPointInput_setTransformA(_native, ref value); } } public Matrix TransformB { get { Matrix value; btDiscreteCollisionDetectorInterface_ClosestPointInput_getTransformB(_native, out value); return value; } set { btDiscreteCollisionDetectorInterface_ClosestPointInput_setTransformB(_native, ref value); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btDiscreteCollisionDetectorInterface_ClosestPointInput_delete(_native); _native = IntPtr.Zero; } } ~ClosestPointInput() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btDiscreteCollisionDetectorInterface_ClosestPointInput_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btDiscreteCollisionDetectorInterface_ClosestPointInput_getMaximumDistanceSquared(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_ClosestPointInput_getTransformA(IntPtr obj, [Out] out Matrix value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_ClosestPointInput_getTransformB(IntPtr obj, [Out] out Matrix value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_ClosestPointInput_setMaximumDistanceSquared(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_ClosestPointInput_setTransformA(IntPtr obj, [In] ref Matrix value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_ClosestPointInput_setTransformB(IntPtr obj, [In] ref Matrix value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_ClosestPointInput_delete(IntPtr obj); } public abstract class Result : IDisposable { internal IntPtr _native; internal Result(IntPtr native) { _native = native; } public void AddContactPoint(Vector3 normalOnBInWorld, Vector3 pointInWorld, float depth) { btDiscreteCollisionDetectorInterface_Result_addContactPoint(_native, ref normalOnBInWorld, ref pointInWorld, depth); } public void SetShapeIdentifiersA(int partId0, int index0) { btDiscreteCollisionDetectorInterface_Result_setShapeIdentifiersA(_native, partId0, index0); } public void SetShapeIdentifiersB(int partId1, int index1) { btDiscreteCollisionDetectorInterface_Result_setShapeIdentifiersB(_native, partId1, index1); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btDiscreteCollisionDetectorInterface_Result_delete(_native); _native = IntPtr.Zero; } } ~Result() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_Result_addContactPoint(IntPtr obj, [In] ref Vector3 normalOnBInWorld, [In] ref Vector3 pointInWorld, float depth); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_Result_setShapeIdentifiersA(IntPtr obj, int partId0, int index0); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_Result_setShapeIdentifiersB(IntPtr obj, int partId1, int index1); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_Result_delete(IntPtr obj); } internal IntPtr _native; internal DiscreteCollisionDetectorInterface(IntPtr native) { _native = native; } public void GetClosestPoints(ClosestPointInput input, Result output, IDebugDraw debugDraw) { btDiscreteCollisionDetectorInterface_getClosestPoints(_native, input._native, output._native, DebugDraw.GetUnmanaged(debugDraw)); } public void GetClosestPoints(ClosestPointInput input, Result output, IDebugDraw debugDraw, bool swapResults) { btDiscreteCollisionDetectorInterface_getClosestPoints2(_native, input._native, output._native, DebugDraw.GetUnmanaged(debugDraw), swapResults); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btDiscreteCollisionDetectorInterface_delete(_native); _native = IntPtr.Zero; } } ~DiscreteCollisionDetectorInterface() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_getClosestPoints(IntPtr obj, IntPtr input, IntPtr output, IntPtr debugDraw); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_getClosestPoints2(IntPtr obj, IntPtr input, IntPtr output, IntPtr debugDraw, bool swapResults); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btDiscreteCollisionDetectorInterface_delete(IntPtr obj); } public abstract class StorageResult : DiscreteCollisionDetectorInterface.Result { internal StorageResult(IntPtr native) : base(native) { } /* public StorageResult() : base(btStorageResultWrapper_new()) { } */ public Vector3 ClosestPointInB { get { Vector3 value; btStorageResult_getClosestPointInB(_native, out value); return value; } set { btStorageResult_setClosestPointInB(_native, ref value); } } public float Distance { get { return btStorageResult_getDistance(_native); } set { btStorageResult_setDistance(_native, value); } } public Vector3 NormalOnSurfaceB { get { Vector3 value; btStorageResult_getNormalOnSurfaceB(_native, out value); return value; } set { btStorageResult_setNormalOnSurfaceB(_native, ref value); } } //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern IntPtr btStorageResultWrapper_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStorageResult_getClosestPointInB(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btStorageResult_getDistance(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStorageResult_getNormalOnSurfaceB(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStorageResult_setClosestPointInB(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStorageResult_setDistance(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btStorageResult_setNormalOnSurfaceB(IntPtr obj, [In] ref Vector3 value); } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Game.Rulesets.UI; using System; using System.Collections.Generic; using JetBrains.Annotations; using ManagedBass.Fx; using osu.Framework.Allocation; using osu.Framework.Audio.Sample; using osu.Framework.Audio.Track; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Utils; using osu.Game.Audio.Effects; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Rulesets.Objects.Drawables; using osuTK; using osuTK.Graphics; namespace osu.Game.Screens.Play { /// <summary> /// Manage the animation to be applied when a player fails. /// Single use and automatically disposed after use. /// </summary> public class FailAnimation : Container { public Action OnComplete; private readonly DrawableRuleset drawableRuleset; private readonly BindableDouble trackFreq = new BindableDouble(1); private readonly BindableDouble volumeAdjustment = new BindableDouble(0.5); private Container filters; private Box redFlashLayer; private Track track; private AudioFilter failLowPassFilter; private AudioFilter failHighPassFilter; private const float duration = 2500; private Sample failSample; [Resolved] private OsuConfigManager config { get; set; } protected override Container<Drawable> Content { get; } = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, }; /// <summary> /// The player screen background, used to adjust appearance on failing. /// </summary> [CanBeNull] public BackgroundScreen Background { private get; set; } public FailAnimation(DrawableRuleset drawableRuleset) { this.drawableRuleset = drawableRuleset; RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(AudioManager audio, IBindable<WorkingBeatmap> beatmap) { track = beatmap.Value.Track; failSample = audio.Samples.Get(@"Gameplay/failsound"); AddRangeInternal(new Drawable[] { filters = new Container { Children = new Drawable[] { failLowPassFilter = new AudioFilter(audio.TrackMixer), failHighPassFilter = new AudioFilter(audio.TrackMixer, BQFType.HighPass), }, }, Content, redFlashLayer = new Box { Colour = Color4.Red.Opacity(0.6f), RelativeSizeAxes = Axes.Both, Blending = BlendingParameters.Additive, Depth = float.MinValue, Alpha = 0 }, }); } private bool started; /// <summary> /// Start the fail animation playing. /// </summary> /// <exception cref="InvalidOperationException">Thrown if started more than once.</exception> public void Start() { if (started) throw new InvalidOperationException("Animation cannot be started more than once."); started = true; this.TransformBindableTo(trackFreq, 0, duration).OnComplete(_ => { // Don't reset frequency as the pause screen may appear post transform, causing a second frequency sweep. RemoveFilters(false); OnComplete?.Invoke(); }); failHighPassFilter.CutoffTo(300); failLowPassFilter.CutoffTo(300, duration, Easing.OutCubic); failSample.Play(); track.AddAdjustment(AdjustableProperty.Frequency, trackFreq); track.AddAdjustment(AdjustableProperty.Volume, volumeAdjustment); applyToPlayfield(drawableRuleset.Playfield); drawableRuleset.Playfield.HitObjectContainer.FadeOut(duration / 2); if (config.Get<bool>(OsuSetting.FadePlayfieldWhenHealthLow)) redFlashLayer.FadeOutFromOne(1000); Content.Masking = true; Content.Add(new Box { Colour = Color4.Black, RelativeSizeAxes = Axes.Both, Depth = float.MaxValue }); Content.ScaleTo(0.85f, duration, Easing.OutQuart); Content.RotateTo(1, duration, Easing.OutQuart); Content.FadeColour(Color4.Gray, duration); // Will be restored by `ApplyToBackground` logic in `SongSelect`. Background?.FadeColour(OsuColour.Gray(0.3f), 60); } public void RemoveFilters(bool resetTrackFrequency = true) { if (resetTrackFrequency) track?.RemoveAdjustment(AdjustableProperty.Frequency, trackFreq); track?.RemoveAdjustment(AdjustableProperty.Volume, volumeAdjustment); if (filters.Parent == null) return; RemoveInternal(filters); filters.Dispose(); } protected override void Update() { base.Update(); if (!started) return; applyToPlayfield(drawableRuleset.Playfield); } private readonly List<DrawableHitObject> appliedObjects = new List<DrawableHitObject>(); private void applyToPlayfield(Playfield playfield) { double failTime = playfield.Time.Current; foreach (var nested in playfield.NestedPlayfields) applyToPlayfield(nested); foreach (DrawableHitObject obj in playfield.HitObjectContainer.AliveObjects) { if (appliedObjects.Contains(obj)) continue; float rotation = RNG.NextSingle(-90, 90); Vector2 originalPosition = obj.Position; Vector2 originalScale = obj.Scale; dropOffScreen(obj, failTime, rotation, originalScale, originalPosition); // need to reapply the fail drop after judgement state changes obj.ApplyCustomUpdateState += (o, _) => dropOffScreen(obj, failTime, rotation, originalScale, originalPosition); appliedObjects.Add(obj); } } private void dropOffScreen(DrawableHitObject obj, double failTime, float randomRotation, Vector2 originalScale, Vector2 originalPosition) { using (obj.BeginAbsoluteSequence(failTime)) { obj.RotateTo(randomRotation, duration); obj.ScaleTo(originalScale * 0.5f, duration); obj.MoveTo(originalPosition + new Vector2(0, 400), duration); } } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * 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.Threading; using MindTouch.Tasking; using NUnit.Framework; namespace MindTouch.Dream.Test { public class ResultTestException : Exception { public ResultTestException() { } public ResultTestException(string message) : base(message) { } } [TestFixture] public class ResultTest { #region --- Valid Transitions --- [Test] public void Return_Wait() { Test<int>( false, result => { result.Return(1); }, result => { /* do nothing */ }); } [Test] public void Wait_Return() { Test<int>( true, result => { result.Return(1); }, result => { /* do nothing */ }); } [Test] public void Throw_Wait() { Test<int, ResultTestException>( false, result => { result.Throw(new ResultTestException()); }, result => { /* do nothing */ }, false, false, null, null ); } [Test] public void Wait_Throw() { Test<int, ResultTestException>( true, result => { result.Throw(new ResultTestException()); }, result => { /* do nothing */ }, false, false, null, null ); } [Test] public void Wait_Timeout() { Test<int, TimeoutException>( false, result => { /* do nothing */ }, result => { /* do nothing */ }, false, false, null, null ); } [Test] public void Wait_Timeout_Return() { Test<int, TimeoutException>( false, result => { /* do nothing */ }, result => { result.Return(1); }, false, true, 1, null ); } [Test] public void Wait_Timeout_Throw() { Test<int, TimeoutException>( false, result => { /* do nothing */ }, result => { result.Throw(new ResultTestException()); }, false, true, typeof(ResultTestException), null ); } [Test] public void Wait_Timeout_Cancel() { Test<int, TimeoutException>( false, result => { /* do nothing */ }, result => { result.Cancel(); }, false, false, null, null ); } [Test] public void Wait_Timeout_ConfirmCancel() { Test<int, TimeoutException>( false, result => { /* do nothing */ }, result => { result.ConfirmCancel(); }, false,true, null, null ); } [Test] public void Wait_Timeout_Cancel_Return() { Test<int, TimeoutException>( false, result => { /* do nothing */ }, result => { result.Cancel(); result.Return(1); }, false, true, 1, null ); } [Test] public void Wait_Timeout_Cancel_Throw() { Test<int, TimeoutException>( false, result => { /* do nothing */ }, result => { result.Cancel(); result.Throw(new ResultTestException()); }, false, true, typeof(ResultTestException), null ); } [Test] public void Wait_Timeout_Cancel_ConfirmCancel() { Test<int, TimeoutException>( false, result => { /* do nothing */ }, result => { result.Cancel(); result.ConfirmCancel(); }, false, true, null, null ); } [Test] public void Cancel_Return_Wait() { Test<int>( false, result => { result.Cancel(); result.Return(1); }, result => { /* do nothing */ }); } [Test] public void Cancel_Cancel_Return_Wait() { Test<int>( false, result => { result.Cancel(); result.Cancel(); result.Return(1); }, result => { /* do nothing */ }); } [Test] public void Cancel_HasFinished_Return_Wait() { Test<int, CanceledException>( false, result => { result.Cancel(); bool finished = result.HasFinished; result.Return(1); }, result => { /* do nothing */ }, false, true, 1, null ); } [Test] public void Cancel_HasFinished_Confirm_Wait() { Test<int, CanceledException>( false, result => { result.Cancel(); bool finished = result.HasFinished; result.ConfirmCancel(); }, result => { /* do nothing */ }, false, true, null, null ); } [Test] public void Wait_Cancel_Return() { Test<int, CanceledException>( true, result => { result.Cancel(); result.Return(1); }, result => { /* do nothing */ }, false, true, 1, null ); } [Test] public void Wait_Cancel_Cancel_Return() { Test<int, CanceledException>( true, result => { result.Cancel(); result.Cancel(); result.Return(1); }, result => { /* do nothing */ }, false, true, 1, null ); } [Test] public void Cancel_Throw_Wait() { Test<int, ResultTestException>( false, result => { result.Cancel(); result.Throw(new ResultTestException()); }, result => { /* do nothing */ }, false, false, null, null ); } [Test] public void Cancel_Cancel_Throw_Wait() { Test<int, ResultTestException>( false, result => { result.Cancel(); result.Cancel(); result.Throw(new ResultTestException()); }, result => { /* do nothing */ }, false, false, null, null ); } [Test] public void Cancel_HasFinished_Throw_Wait() { Test<int, CanceledException>( false, result => { result.Cancel(); bool finished = result.HasFinished; result.Throw(new ResultTestException()); }, result => { /* do nothing */ }, false, true, typeof(ResultTestException), null ); } [Test] public void Wait_Cancel_Throw() { Test<int, CanceledException>( true, result => { result.Cancel(); result.Throw(new ResultTestException()); }, result => { /* do nothing */ }, false, true, typeof(ResultTestException), null ); } [Test] public void Wait_Cancel_Cancel_Throw() { Test<int, CanceledException>( true, result => { result.Cancel(); result.Cancel(); result.Throw(new ResultTestException()); }, result => { /* do nothing */ }, false, true, typeof(ResultTestException), null ); } [Test] public void Return_Cancel_Wait() { Test<int>( false, result => { result.Return(1); result.Cancel(); }, result => { /* do nothing */ }); } [Test] public void Wait_Return_Cancel() { Test<int>( true, result => { result.Return(1); result.Cancel(); }, result => { /* do nothing */ }); } [Test] public void Throw_Cancel_Wait() { Test<int, ResultTestException>( false, result => { result.Throw(new ResultTestException()); result.Cancel(); }, result => { /* do nothing */ }, false, false, null, null ); } [Test] public void Wait_Throw_Cancel() { Test<int, ResultTestException>( true, result => { result.Throw(new ResultTestException()); result.Cancel(); }, result => { /* do nothing */ }, false, false, null, null ); } [Test] public void Cancel_ConfirmCancel_Wait() { Test<int, CanceledException>( false, result => { result.Cancel(); result.ConfirmCancel(); }, result => { /* do nothing */ }, false, true, null, null ); } [Test] public void Cancel_ConfirmCancel_Cancel_Wait() { Test<int, CanceledException>( false, result => { result.Cancel(); result.ConfirmCancel(); result.Cancel(); }, result => { /* do nothing */ }, false, true, null, null ); } [Test] public void Wait_Cancel_ConfirmCancel() { Test<int, CanceledException>( true, result => { result.Cancel(); result.ConfirmCancel(); }, result => { /* do nothing */ }, false, true, null, null ); } [Test] public void Wait_Cancel_ConfirmCancel_Cancel() { Test<int, CanceledException>( true, result => { result.Cancel(); result.ConfirmCancel(); result.Cancel(); }, result => { /* do nothing */ }, false, true, null, null ); } #endregion #region --- TryReturn --- [Test] public void TryReturn() { var result = new Result<int>(); var test = result.TryReturn(2); Assert.IsTrue(test, "TryReturn failed"); Assert.IsTrue(result.HasValue, "result value is missing"); Assert.AreEqual(2, result.Value, "result value does not match"); } [Test] public void Return_TryReturn() { var result = new Result<int>(); result.Return(1); var test = result.TryReturn(2); Assert.IsFalse(test, "TryReturn succeeded"); Assert.IsTrue(result.HasValue, "result value is missing"); Assert.AreEqual(1, result.Value, "result value does not match"); } [Test] public void Throw_TryReturn() { var result = new Result<int>(); result.Throw(new ResultTestException()); var test = result.TryReturn(2); Assert.IsFalse(test, "TryReturn succeeded"); Assert.IsTrue(result.HasException, "result exception is missing"); Assert.IsInstanceOf<ResultTestException>(result.Exception, "result exception has wrong type"); } [Ignore("Not fully baked yet")] [Test] public void Cancel_TryReturn() { var result = new Result<int>(); result.Cancel(); var test = result.TryReturn(2); Assert.IsFalse(test, "TryReturn succeeded"); Assert.IsTrue(result.IsCanceled, "result is not canceled"); Assert.IsTrue(result.HasException, "result exception is missing"); Assert.IsInstanceOf<CanceledException>(result.Exception, "result exception has wrong type"); } #endregion #region --- Invalid Transitions --- [Test] public void Return_Return() { TestFail<int, InvalidOperationException>( result => { result.Return(1); result.Return(2); }, null, result => result.HasValue && (result.Value == 1) ); } [Test] public void Return_Throw() { TestFail<int, InvalidOperationException>( result => { result.Return(1); result.Throw(new ResultTestException()); }, null, result => result.HasValue && (result.Value == 1) ); } [Test] public void Throw_Return() { TestFail<int, InvalidOperationException>( result => { result.Throw(new ResultTestException()); result.Return(1); }, null, result => result.HasException && (result.Exception is ResultTestException) ); } [Test] public void Throw_Throw() { TestFail<int, InvalidOperationException>( result => { result.Throw(new ResultTestException("first")); result.Throw(new ResultTestException("second")); }, null, result => result.HasException && (result.Exception is ResultTestException) ); } [Test] public void ConfirmCancel() { TestFail<int, InvalidOperationException>( result => { result.ConfirmCancel(); }, null, result => result.HasException && (result.Exception is InvalidOperationException) ); } [Test] public void Return_ConfirmCancel() { TestFail<int, InvalidOperationException>( result => { result.Return(1); result.ConfirmCancel(); }, null, result => result.HasValue && (result.Value == 1) ); } [Test] public void Throw_ConfirmCancel() { TestFail<int, InvalidOperationException>( result => { result.Throw(new ResultTestException()); result.ConfirmCancel(); }, null, result => result.HasException && (result.Exception is ResultTestException) ); } #endregion #region --- Helpers --- private static void Test<T>(bool waitFirst, Action<Result<T>> before, Action<Result<T>> after) { int success = 0; int error = 0; int canceled = 0; Result<T> canceldResult = null; AutoResetEvent wait = new AutoResetEvent(false); Result<T> result = new Result<T>(TimeSpan.FromSeconds(0.1), TaskEnv.Instantaneous); if(!waitFirst) { if(before != null) { before(result); } } result.WithCleanup(r => { ++canceled; canceldResult = r; wait.Set(); }); result.WhenDone( v => { ++success; wait.Set(); }, e => { ++error; wait.Set(); } ); if(waitFirst) { if(before != null) { before(result); } } bool waited = wait.WaitOne(TimeSpan.FromSeconds(1), false); Assert.IsTrue(waited, "result failed to time out"); if(after != null) { after(result); } int expected_success = 1; int expected_error = 0; Assert.AreEqual(expected_success, success, string.Format("success was {1}, but expected {0}", expected_success, success)); Assert.AreEqual(expected_error, error, string.Format("error was {1}, but expected {0}", expected_error, error)); Assert.IsNull(result.Exception, "exception is set"); } private static void Test<T, TException>(bool waitFirst, Action<Result<T>> before, Action<Result<T>> after, bool isSuccess, bool isCancel, object cancelOutcome, Action<Result<T>> check) where TException : Exception { int success = 0; int error = 0; int canceled = 0; Result<T> canceldResult = null; AutoResetEvent wait = new AutoResetEvent(false); Result<T> result = new Result<T>(TimeSpan.FromSeconds(0.1), TaskEnv.Instantaneous); if(!waitFirst) { if(before != null) { before(result); } } result.WithCleanup(r => { ++canceled; canceldResult = r; wait.Set(); }); result.WhenDone( v => { ++success; wait.Set(); }, e => { ++error; wait.Set(); } ); if(waitFirst) { if(before != null) { before(result); } } bool waited = wait.WaitOne(TimeSpan.FromSeconds(1), false); Assert.IsTrue(waited, "result failed to time out"); if(after != null) { after(result); } int expected_success = isSuccess ? 1 : 0; int expected_error = 1; int expected_cancel = isCancel ? 1 : 0; Assert.AreEqual(expected_success, success, string.Format("success was {1}, but expected {0}", expected_success, success)); Assert.AreEqual(expected_error, error, string.Format("error was {1}, but expected {0}", expected_error, error)); Assert.AreEqual(expected_cancel, canceled, string.Format("canceled was {1}, but expected {0}", expected_cancel, canceled)); Assert.IsInstanceOf<TException>(result.Exception, "exception has wrong type"); if(isCancel) { if(cancelOutcome == null) { Assert.IsNull(canceldResult, "canceled result was not null"); } else if(cancelOutcome is Type) { #pragma warning disable 612 Assert.IsInstanceOfType((Type)cancelOutcome, canceldResult.Exception, "canceled result exception did not match"); #pragma warning restore 612 } else { Assert.AreEqual(cancelOutcome, canceldResult.Value, "canceled result value did not match"); } } if(check != null) { check(result); } } private static void TestFail<T, TException>(Action<Result<T>> callback, string exceptionMessage, Predicate<Result<T>> validate) where TException : Exception { Exception ex = null; var result = new Result<T>(); try { callback(result); } catch(Exception e) { ex = e; } Assert.IsInstanceOf<TException>(ex, "unexpected exception on failed operation"); if(exceptionMessage != null) { Assert.AreEqual(exceptionMessage, ex.Message); } if(validate != null) { Assert.IsTrue(validate(result), "result validation failed"); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace Draft.Responses { /// <summary> /// Etcd error codes /// </summary> public enum EtcdErrorCode { /// <summary> /// Unable to determine errorcode from response /// </summary> Unknown, #region Command related /// <summary> /// Key not found /// </summary> KeyNotFound, /// <summary> /// Compare failed /// </summary> TestFailed, /// <summary> /// Not a file /// </summary> NotFile, /// <summary> /// Reached the max number of peers in the cluster /// </summary> NoMorePeer, /// <summary> /// Not a directory /// </summary> NotDirectory, /// <summary> /// Key already exists /// </summary> NodeExists, /// <summary> /// The prefix of given key is a keyword in etcd /// </summary> KeyIsPreserved, /// <summary> /// Root is read only /// </summary> RootReadOnly, /// <summary> /// Directory not empty /// </summary> DirectoryNotEmpty, /// <summary> /// Peer address has "existed" /// </summary> ExistingPeerAddress, #endregion #region Post form related /// <summary> /// Value is required in POST form /// </summary> ValueRequired, /// <summary> /// PrevValue is required in POST form /// </summary> PreviousValueRequired, /// <summary> /// The given TTL in POST form is not a number /// </summary> TtlNotANumber, /// <summary> /// The given index in POST form is not a number /// </summary> IndexNotANumber, /// <summary> /// Value or TTL is required in POST form /// </summary> ValueOrTtlRequired, /// <summary> /// The given timeout in POST form is not a number /// </summary> TimeoutNotANumber, /// <summary> /// Name is required in POST form /// </summary> NameRequired, /// <summary> /// Index or value is required /// </summary> IndexOrValueRequired, /// <summary> /// Index and value cannot both be specified /// </summary> IndexValueMutex, /// <summary> /// Field is not valid /// </summary> InvalidField, /// <summary> /// Invalid POST form /// </summary> InvalidForm, #endregion #region Raft related /// <summary> /// Internal RAFT error /// </summary> RaftInternal, /// <summary> /// During leader election /// </summary> LeaderElect, #endregion #region Etcd related /// <summary> /// Watcher is cleared due to etcd recovery /// </summary> WatcherCleared, /// <summary> /// The event in requested index is outdated and cleared /// </summary> EventIndexCleared, /// <summary> /// Standby Internal Error /// </summary> StandbyInternal, /// <summary> /// Invalid active size /// </summary> InvalidActiveSize, /// <summary> /// Standby remove delay /// </summary> InvalidRemoveDelay, #endregion /// <summary> /// Client internal error /// </summary> ClientInternal } internal static class EtcdErrorCodeMapping { private static readonly Dictionary<int, EtcdErrorCode> Mapping = new Dictionary<int, EtcdErrorCode>(Enum.GetValues(typeof (EtcdErrorCode)).Length) { // Command related {Constants.Etcd.ErrorCode_KeyNotFound, EtcdErrorCode.KeyNotFound}, {Constants.Etcd.ErrorCode_TestFailed, EtcdErrorCode.TestFailed}, {Constants.Etcd.ErrorCode_NotFile, EtcdErrorCode.NotFile}, {Constants.Etcd.ErrorCode_NoMorePeer, EtcdErrorCode.NoMorePeer}, {Constants.Etcd.ErrorCode_NotDirectory, EtcdErrorCode.NotDirectory}, {Constants.Etcd.ErrorCode_NodeExists, EtcdErrorCode.NodeExists}, {Constants.Etcd.ErrorCode_KeyIsPreserved, EtcdErrorCode.KeyIsPreserved}, {Constants.Etcd.ErrorCode_RootReadOnly, EtcdErrorCode.RootReadOnly}, {Constants.Etcd.ErrorCode_DirectoryNotEmpty, EtcdErrorCode.DirectoryNotEmpty}, {Constants.Etcd.ErrorCode_ExistingPeerAddress, EtcdErrorCode.ExistingPeerAddress}, // Post form related {Constants.Etcd.ErrorCode_ValueRequired, EtcdErrorCode.ValueRequired}, {Constants.Etcd.ErrorCode_PreviousValueRequired, EtcdErrorCode.PreviousValueRequired}, {Constants.Etcd.ErrorCode_TtlNotANumber, EtcdErrorCode.TtlNotANumber}, {Constants.Etcd.ErrorCode_IndexNotANumber, EtcdErrorCode.IndexNotANumber}, {Constants.Etcd.ErrorCode_ValueOrTtlRequired, EtcdErrorCode.ValueOrTtlRequired}, {Constants.Etcd.ErrorCode_TimeoutNotANumber, EtcdErrorCode.TimeoutNotANumber}, {Constants.Etcd.ErrorCode_NameRequired, EtcdErrorCode.NameRequired}, {Constants.Etcd.ErrorCode_IndexOrValueRequired, EtcdErrorCode.IndexOrValueRequired}, {Constants.Etcd.ErrorCode_IndexValueMutex, EtcdErrorCode.IndexValueMutex}, {Constants.Etcd.ErrorCode_InvalidField, EtcdErrorCode.InvalidField}, {Constants.Etcd.ErrorCode_InvalidForm, EtcdErrorCode.InvalidForm}, // Raft related {Constants.Etcd.ErrorCode_RaftInternal, EtcdErrorCode.RaftInternal}, {Constants.Etcd.ErrorCode_LeaderElect, EtcdErrorCode.LeaderElect}, // Etcd related {Constants.Etcd.ErrorCode_WatcherCleared, EtcdErrorCode.WatcherCleared}, {Constants.Etcd.ErrorCode_EventIndexCleared, EtcdErrorCode.EventIndexCleared}, {Constants.Etcd.ErrorCode_StandbyInternal, EtcdErrorCode.StandbyInternal}, {Constants.Etcd.ErrorCode_InvalidActiveSize, EtcdErrorCode.InvalidActiveSize}, {Constants.Etcd.ErrorCode_InvalidRemoveDelay, EtcdErrorCode.InvalidRemoveDelay}, // Other {Constants.Etcd.ErrorCode_ClientInternal, EtcdErrorCode.ClientInternal}, {Constants.Etcd.ErrorCode_Unknown, EtcdErrorCode.Unknown} }; public static EtcdErrorCode? Map(this HttpStatusCode This) { var code = (int) This; if (This == HttpStatusCode.Conflict) { code = Constants.Etcd.ErrorCode_ExistingPeerAddress; } return code.Map(); } public static EtcdErrorCode? Map(this int? This) { return This.HasValue ? This.Value.Map() : null; } public static EtcdErrorCode? Map(this int This) { EtcdErrorCode result; if (Mapping.TryGetValue(This, out result)) { return result; } return null; } public static int? RawValue(this EtcdErrorCode? This) { return This.HasValue ? This.Value.RawValue() : null; } public static int? RawValue(this EtcdErrorCode This) { return Mapping .Where(x => x.Value == This) .Select(x => x.Key) .FirstOrDefault(); } } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows; using System.Windows.Media; using Caliburn.Micro; using csPresenterPlugin.Controls; namespace nl.tno.cs.presenter { public class Folder: PropertyChangedBase { private string _name; public string Name { get { return _name; } set { _name = value; NotifyOfPropertyChange(()=>Name); NotifyOfPropertyChange(()=>Title); } } private bool _seeThru; public bool SeeThru { get { return _seeThru; } set { _seeThru = value; } } public string Title { get { return Name.CleanName(); } } private MetroExplorer _explorer; public MetroExplorer Explorer { get { return _explorer; } set { _explorer = value; } } private Brush textBrush; public Brush TextBrush { get { return textBrush; } set { textBrush = value; NotifyOfPropertyChange(()=>TextBrush); } } private BindableCollection<MetroItemViewModel> _items; public BindableCollection<MetroItemViewModel> Items { get { return _items; } set { _items = value; NotifyOfPropertyChange(()=>Items); } } public List<FolderTemplate> Templates { get; set; } private DirectoryInfo _directory; public DirectoryInfo Directory { get { return _directory; } set { _directory = value; NotifyOfPropertyChange(()=>Directory); } } private Visibility _titleVisibility; public Visibility TitleVibility { get { return _titleVisibility; } set { _titleVisibility = value; NotifyOfPropertyChange(()=>TitleVibility); } } private bool _templated = true; public bool Templated { get { return _templated; } set { _templated = value; NotifyOfPropertyChange(()=>Templated); } } public Folder(ItemClass item, MetroExplorer explorer) { Directory = new DirectoryInfo(item.Path); Name = Directory.Name; InitTemplates(); Explorer = explorer; } public void InitTemplates() { Templates = new List<FolderTemplate>() { new FolderTemplate() { Items = new List<ItemTemplate>() { new ItemTemplate() { Col = 0, Row = 0, Colspan = 12, Rowspan= 12} }, }, new FolderTemplate() { Items = new List<ItemTemplate>() { new ItemTemplate() { Col = 0, Row = 0, Colspan = 12, Rowspan= 6}, new ItemTemplate() { Col = 0, Row = 6, Colspan = 12, Rowspan= 6}, }, }, new FolderTemplate() { Items = new List<ItemTemplate>() { new ItemTemplate() { Col = 0, Row = 0, Colspan = 4, Rowspan= 12}, new ItemTemplate() { Col = 4, Row = 0, Colspan = 4, Rowspan= 12}, new ItemTemplate() { Col = 8, Row = 0, Colspan = 4, Rowspan= 12}, }, }, new FolderTemplate() { Items = new List<ItemTemplate>() { new ItemTemplate() { Col = 0, Row = 0, Colspan = 6, Rowspan= 6}, new ItemTemplate() { Col = 6, Row = 0, Colspan = 6, Rowspan = 6}, new ItemTemplate() { Col = 0, Row = 6, Colspan = 6, Rowspan = 6}, new ItemTemplate() { Col = 6, Row = 6, Colspan = 6, Rowspan = 6}, }, }, new FolderTemplate() { Items = new List<ItemTemplate>() { new ItemTemplate() { Col = 0, Row = 0, Colspan = 8, Rowspan= 8}, new ItemTemplate() { Col = 8, Row = 0, Colspan = 4, Rowspan = 4}, new ItemTemplate() { Col = 8, Row = 4, Colspan = 4, Rowspan = 8}, new ItemTemplate() { Col = 0, Row = 8, Colspan = 4, Rowspan = 4}, new ItemTemplate() { Col = 4, Row = 8, Colspan = 4, Rowspan = 4} }, } }; } //protected override void OnViewLoaded(object view) //{ // base.OnViewLoaded(view); // _view = (FolderView) view; // _view.SetBinding(FrameworkElement.WidthProperty, new Binding("SegWidth") {Source = Explorer}); // _view.SetBinding(FrameworkElement.HeightProperty, new Binding("SegHeight") { Source = Explorer }); // _view.gScaleGrid.SetBinding(Grid.WidthProperty, new Binding("ScaleWidth") { Source = Explorer }); // _view.gScaleGrid.SetBinding(Grid.HeightProperty, new Binding("ScaleHeight") { Source = Explorer }); // GetFiles(); //} public void GetFiles() { var l = new List<ItemClass>(); Items = new BindableCollection<MetroItemViewModel>(); if (Directory.Exists) { List<DirectoryInfo> di = Directory.GetDirectories().ToList().OrderBy(k => k.Name).ToList(); List<FileInfo> fi = Directory.GetFiles().ToList().OrderBy(k => k.Name).ToList(); foreach (var d in di) { if (!d.Name.StartsWith("_")) { var ic = new ItemClass() {Path = d.FullName, ImagePath = d.FullName, Type = ItemType.folder}; l.Add(ic); } } foreach (var d in fi) { if (!d.Name.StartsWith("_")) { string[] dd = d.Name.ToLower().Split('.'); if (dd[0] != Directory.Name.ToLower()) { if (d.Extension.ToLower() == ".pdf") { } if (Explorer.images.Contains(d.Extension.ToLower())) { var ic = new ItemClass() {Path = d.FullName, Type = ItemType.image, Name = dd[0]}; l.Add(ic); } if (Explorer.videos.Contains(d.Extension.ToLower())) { var ic = new ItemClass() { Path = d.FullName, ImagePath = d.FullName, Type = ItemType.video, Name = dd[0] }; l.Add(ic); } if (Explorer.scripts.Contains(d.Extension.ToLower())) { var ic = new ItemClass() { Path = d.FullName, Type = ItemType.script, Name = dd[0] }; } } if (Explorer.Extensions.ContainsKey(d.Extension.ToLower())) { var ic = new ItemClass() {Path = d.FullName, ImagePath = "", Type = ItemType.unknown, Name = dd[0]}; l.Add(ic); } } } List<ItemClass> tbr = new List<ItemClass>(); foreach (var ic in l.Where(k => k.Type != ItemType.image)) { if (ic != null && ic.Name!=null) { var i = l.FirstOrDefault(k => k.Name!=null && k.Name.ToLower() == ic.Name.ToLower() && k.Type == ItemType.image); if (i != null) { tbr.Add(i); ic.ImagePath = i.Path; } } } foreach (var i in tbr) l.Remove(i); //var view = Caliburn.Micro.ViewModelLocator.(new MetroItemViewModel(fi[0], 0, 0, 2, 2)); if (Templated) { FolderTemplate ft = Templates.FirstOrDefault(k => k.Items.Count == l.Count); int c = 0; if (ft != null) { foreach (var i in ft.Items) { Items.Add(new MetroItemViewModel(l[c], i.Col, i.Row, i.Colspan, i.Rowspan, Explorer)); c += 1; } } } } } } }
// // TimeAdaptor.cs // // Author: // Ruben Vermeersch <[email protected]> // Gabriel Burt <[email protected]> // Larry Ewing <[email protected]> // Stephane Delcroix <[email protected]> // // Copyright (C) 2004-2010 Novell, Inc. // Copyright (C) 2010 Ruben Vermeersch // Copyright (C) 2005-2006 Gabriel Burt // Copyright (C) 2004-2005 Larry Ewing // Copyright (C) 2006, 2008 Stephane Delcroix // // 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.Threading; using System.Collections.Generic; using FSpot.Core; using FSpot.Query; using Hyena; namespace FSpot { public class TimeAdaptor : GroupAdaptor, FSpot.ILimitable { Dictionary <int, int[]> years = new Dictionary<int, int[]> (); public override event GlassSetHandler GlassSet; public override void SetGlass (int min) { DateTime date = DateFromIndex (min); if (GlassSet != null) GlassSet (this, query.LookupItem (date)); } public void SetLimits (int min, int max) { DateTime start = DateFromIndex (min); DateTime end = DateFromIndex(max); end = order_ascending ? end.AddMonths (1) : end.AddMonths(-1); SetLimits (start, end); } public void SetLimits (DateTime start, DateTime end) { query.Range = (start > end) ? new DateRange (end, start) : new DateRange (start, end); } public override int Count () { return years.Count * 12; } public override string GlassLabel (int item) { return String.Format ("{0} ({1})", DateFromIndex (item).ToString ("MMMM yyyy"), Value (item)); } public override string TickLabel (int item) { DateTime start = DateFromIndex (item); if ((start.Month == 12 && !order_ascending) || (start.Month == 1 && order_ascending)) return start.Year.ToString (); return null; } public override int Value (int item) { if (order_ascending) return years [startyear + item/12][item % 12]; return years [endyear - item/12][11 - item % 12]; } public DateTime DateFromIndex (int item) { item = Math.Max (item, 0); item = Math.Min (years.Count * 12 - 1, item); if (order_ascending) return DateFromIndexAscending (item); return DateFromIndexDescending (item); } private DateTime DateFromIndexAscending (int item) { int year = startyear + item/12; int month = 1 + (item % 12); return new DateTime(year, month, 1); } private DateTime DateFromIndexDescending (int item) { int year = endyear - item/12; int month = 12 - (item % 12); year = Math.Max(1, year); year = Math.Min(year, 9999); month = Math.Max(1, month); month = Math.Min(month, 12); int daysInMonth = DateTime.DaysInMonth(year, month); return new DateTime (year, month, daysInMonth).AddDays (1.0).AddMilliseconds (-.1); } public override int IndexFromPhoto (IPhoto photo) { if (order_ascending) return IndexFromDateAscending (photo.Time); return IndexFromDateDescending (photo.Time); } public int IndexFromDate (DateTime date) { if (order_ascending) return IndexFromDateAscending(date); return IndexFromDateDescending(date); } private int IndexFromDateAscending(DateTime date) { int year = date.Year; int min_year = startyear; int max_year = endyear; if (year < min_year || year > max_year) { Log.DebugFormat ("TimeAdaptor.IndexFromDate year out of range[{1},{2}]: {0}", year, min_year, max_year); return 0; } return (year - startyear) * 12 + date.Month - 1 ; } private int IndexFromDateDescending(DateTime date) { int year = date.Year; int min_year = startyear; int max_year = endyear; if (year < min_year || year > max_year) { Log.DebugFormat ("TimeAdaptor.IndexFromPhoto year out of range[{1},{2}]: {0}", year, min_year, max_year); return 0; } return 12 * (endyear - year) + 12 - date.Month; } public override IPhoto PhotoFromIndex (int item) { DateTime start = DateFromIndex (item); return query [query.LookupItem (start)]; } public override event ChangedHandler Changed; uint timer; protected override void Reload () { timer = Log.DebugTimerStart (); Thread reload = new Thread (new ThreadStart (DoReload)); reload.IsBackground = true; reload.Priority = ThreadPriority.Lowest; reload.Start (); } int startyear = Int32.MaxValue, endyear = Int32.MinValue; void DoReload () { Thread.Sleep (200); Dictionary <int, int[]> years_tmp = query.Store.PhotosPerMonth (); int startyear_tmp = Int32.MaxValue; int endyear_tmp = Int32.MinValue; foreach (int year in years_tmp.Keys) { startyear_tmp = Math.Min (year, startyear_tmp); endyear_tmp = Math.Max (year, endyear_tmp); } ThreadAssist.ProxyToMain (() => { years = years_tmp; startyear = startyear_tmp; endyear = endyear_tmp; if (Changed != null) Changed (this); }); Log.DebugTimerPrint (timer, "TimeAdaptor REAL Reload took {0}"); } public TimeAdaptor (PhotoQuery query, bool order_ascending) : base (query, order_ascending) { } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate; using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.Resources.Core; using Windows.Globalization; using Windows.Media.SpeechRecognition; using Windows.Storage; using Windows.UI; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.Foundation; namespace SpeechAndTTS { public sealed partial class SRGSConstraintScenario : Page { /// <summary> /// This HResult represents the scenario where a user is prompted to allow in-app speech, but /// declines. This should only happen on a Phone device, where speech is enabled for the entire device, /// not per-app. /// </summary> private static uint HResultPrivacyStatementDeclined = 0x80045509; /// <summary> /// the HResult 0x8004503a typically represents the case where a recognizer for a particular language cannot /// be found. This may occur if the language is installed, but the speech pack for that language is not. /// See Settings -> Time & Language -> Region & Language -> *Language* -> Options -> Speech Language Options. /// </summary> private static uint HResultRecognizerNotFound = 0x8004503a; private SpeechRecognizer speechRecognizer; private IAsyncOperation<SpeechRecognitionResult> recognitionOperation; private CoreDispatcher dispatcher; private ResourceContext speechContext; private ResourceMap speechResourceMap; private Dictionary<string, Color> colorLookup = new Dictionary<string, Color> { { "COLOR_RED", Colors.Red }, {"COLOR_BLUE", Colors.Blue }, {"COLOR_BLACK", Colors.Black}, { "COLOR_BROWN", Colors.Brown}, {"COLOR_PURPLE",Colors.Purple}, {"COLOR_GREEN", Colors.Green}, { "COLOR_YELLOW",Colors.Yellow}, {"COLOR_CYAN", Colors.Cyan}, {"COLOR_MAGENTA",Colors.Magenta}, { "COLOR_ORANGE",Colors.Orange}, {"COLOR_GRAY", Colors.Gray}, {"COLOR_WHITE", Colors.White} }; public SRGSConstraintScenario() { InitializeComponent(); } /// <summary> /// When activating the scenario, ensure we have permission from the user to access their microphone, and /// provide an appropriate path for the user to enable access to the microphone if they haven't /// given explicit permission for it. /// </summary> /// <param name="e">The navigation event details</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { // Save the UI thread dispatcher to allow speech status messages to be shown on the UI. dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission(); if (permissionGained) { // Enable the recognition buttons. btnRecognizeWithUI.IsEnabled = true; btnRecognizeWithoutUI.IsEnabled = true; } else { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone."; } Language speechLanguage = SpeechRecognizer.SystemSpeechLanguage; string langTag = speechLanguage.LanguageTag; speechContext = ResourceContext.GetForCurrentView(); speechContext.Languages = new string[] { langTag }; speechResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("LocalizationSpeechResources"); PopulateLanguageDropdown(); await InitializeRecognizer(SpeechRecognizer.SystemSpeechLanguage); } /// <summary> /// Look up the supported languages for this speech recognition scenario, /// that are installed on this machine, and populate a dropdown with a list. /// </summary> private void PopulateLanguageDropdown() { // disable the callback so we don't accidentally trigger initialization of the recognizer // while initialization is already in progress. cbLanguageSelection.SelectionChanged -= cbLanguageSelection_SelectionChanged; Language defaultLanguage = SpeechRecognizer.SystemSpeechLanguage; IEnumerable<Language> supportedLanguages = SpeechRecognizer.SupportedGrammarLanguages; foreach (Language lang in supportedLanguages) { ComboBoxItem item = new ComboBoxItem(); item.Tag = lang; item.Content = lang.DisplayName; cbLanguageSelection.Items.Add(item); if (lang.LanguageTag == defaultLanguage.LanguageTag) { item.IsSelected = true; cbLanguageSelection.SelectedItem = item; } } cbLanguageSelection.SelectionChanged += cbLanguageSelection_SelectionChanged; } /// <summary> /// When a user changes the speech recognition language, trigger re-initialization of the /// speech engine with that language, and change any speech-specific UI assets. /// </summary> /// <param name="sender">Ignored</param> /// <param name="e">Ignored</param> private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBoxItem item = (ComboBoxItem)(cbLanguageSelection.SelectedItem); Language newLanguage = (Language)item.Tag; if (speechRecognizer != null) { if (speechRecognizer.CurrentLanguage == newLanguage) { return; } } // trigger cleanup and re-initialization of speech. try { speechContext.Languages = new string[] { newLanguage.LanguageTag }; await InitializeRecognizer(newLanguage); } catch (Exception exception) { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } /// <summary> /// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks. /// </summary> /// <param name="e">Details about the navigation event</param> protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); if (speechRecognizer != null) { if (speechRecognizer.State != SpeechRecognizerState.Idle) { if (recognitionOperation != null) { recognitionOperation.Cancel(); recognitionOperation = null; } } speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged; this.speechRecognizer.Dispose(); this.speechRecognizer = null; } } /// <summary> /// Initialize Speech Recognizer and compile constraints. /// </summary> /// <param name="recognizerLanguage">Language to use for the speech recognizer</param> /// <returns>Awaitable task.</returns> private async Task InitializeRecognizer(Language recognizerLanguage) { if (speechRecognizer != null) { // cleanup prior to re-initializing this scenario. speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged; this.speechRecognizer.Dispose(); this.speechRecognizer = null; } try { // Initialize the SRGS-compliant XML file. // For more information about grammars for Windows apps and how to // define and use SRGS-compliant grammars in your app, see // https://msdn.microsoft.com/en-us/library/dn596121.aspx // determine the language code being used. string languageTag = recognizerLanguage.LanguageTag; string fileName = String.Format("SRGS\\{0}\\SRGSColors.xml", languageTag); StorageFile grammarContentFile = await Package.Current.InstalledLocation.GetFileAsync(fileName); // Initialize the SpeechRecognizer and add the grammar. speechRecognizer = new SpeechRecognizer(recognizerLanguage); // Provide feedback to the user about the state of the recognizer. speechRecognizer.StateChanged += SpeechRecognizer_StateChanged; // RecognizeWithUIAsync allows developers to customize the prompts. speechRecognizer.UIOptions.ExampleText = speechResourceMap.GetValue("SRGSUIOptionsExampleText", speechContext).ValueAsString; SpeechRecognitionGrammarFileConstraint grammarConstraint = new SpeechRecognitionGrammarFileConstraint(grammarContentFile); speechRecognizer.Constraints.Add(grammarConstraint); SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync(); // Check to make sure that the constraints were in a proper format and the recognizer was able to compile it. if (compilationResult.Status != SpeechRecognitionResultStatus.Success) { // Disable the recognition buttons. btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; // Let the user know that the grammar didn't compile properly. resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "Unable to compile grammar."; } else { btnRecognizeWithUI.IsEnabled = true; btnRecognizeWithoutUI.IsEnabled = true; resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = speechResourceMap.GetValue("SRGSListeningPromptText", speechContext).ValueAsString; // Set EndSilenceTimeout to give users more time to complete speaking a phrase. speechRecognizer.Timeouts.EndSilenceTimeout = TimeSpan.FromSeconds(1.2); } } catch (Exception ex) { if ((uint)ex.HResult == HResultRecognizerNotFound) { btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "Speech Language pack for selected language not installed."; } else { var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, "Exception"); await messageDialog.ShowAsync(); } } } /// <summary> /// Handle SpeechRecognizer state changed events by updating a UI component. /// </summary> /// <param name="sender">Speech recognizer that generated this status event</param> /// <param name="args">The recognizer's status</param> private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args) { await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { MainPage.Current.NotifyUser("Speech recognizer state: " + args.State.ToString(), NotifyType.StatusMessage); }); } /// <summary> /// Uses the recognizer constructed earlier to listen for speech from the user before displaying /// it back on the screen. Uses the built-in speech recognition UI. /// </summary> /// <param name="sender">Button that triggered this event</param> /// <param name="e">State information about the routed event</param> private async void RecognizeWithUI_Click(object sender, RoutedEventArgs e) { // Reset the text to prompt the user. resultTextBlock.Text = speechResourceMap.GetValue("SRGSListeningPromptText", speechContext).ValueAsString; // Start recognition. try { recognitionOperation = speechRecognizer.RecognizeWithUIAsync(); SpeechRecognitionResult speechRecognitionResult = await recognitionOperation; if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success) { HandleRecognitionResult(speechRecognitionResult); } else { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString()); } } catch (TaskCanceledException exception) { // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively // processing speech. Since this happens here when we navigate out of the scenario, don't try to // show a message dialog for this exception. System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):"); System.Diagnostics.Debug.WriteLine(exception.ToString()); } catch (Exception exception) { // Handle the speech privacy policy error. if ((uint)exception.HResult == HResultPrivacyStatementDeclined) { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "The privacy statement was declined."; } else { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } } /// <summary> /// Uses the recognizer constructed earlier to listen for speech from the user before displaying /// it back on the screen. Uses developer-provided UI for user feedback. /// </summary> /// <param name="sender">Button that triggered this event</param> /// <param name="e">State information about the routed event</param> private async void RecognizeWithoutUI_Click(object sender, RoutedEventArgs e) { // Reset the text to prompt the user. resultTextBlock.Text = speechResourceMap.GetValue("SRGSListeningPromptText", speechContext).ValueAsString; // Disable the UI while recognition is occurring, and provide feedback to the user about current state. btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; cbLanguageSelection.IsEnabled = false; listenWithoutUIButtonText.Text = " listening for speech..."; // Start recognition. try { recognitionOperation = speechRecognizer.RecognizeAsync(); SpeechRecognitionResult speechRecognitionResult = await recognitionOperation; if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success) { HandleRecognitionResult(speechRecognitionResult); } else { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = string.Format("Speech Recognition Failed, Status: {0}", speechRecognitionResult.Status.ToString()); } } catch (TaskCanceledException exception) { // TaskCanceledException will be thrown if you exit the scenario while the recognizer is actively // processing speech. Since this happens here when we navigate out of the scenario, don't try to // show a message dialog for this exception. System.Diagnostics.Debug.WriteLine("TaskCanceledException caught while recognition in progress (can be ignored):"); System.Diagnostics.Debug.WriteLine(exception.ToString()); } catch (Exception exception) { // Handle the speech privacy policy error. if ((uint)exception.HResult == HResultPrivacyStatementDeclined) { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "The privacy statement was declined."; } else { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } // Reset UI state. listenWithoutUIButtonText.Text = " without UI"; cbLanguageSelection.IsEnabled = true; btnRecognizeWithUI.IsEnabled = true; btnRecognizeWithoutUI.IsEnabled = true; } /// <summary> /// Uses the result from the speech recognizer to change the colors of the shapes. /// </summary> /// <param name="recoResult">The result from the recognition event</param> private void HandleRecognitionResult(SpeechRecognitionResult recoResult) { // Check the confidence level of the recognition result. if (recoResult.Confidence == SpeechRecognitionConfidence.High || recoResult.Confidence == SpeechRecognitionConfidence.Medium) { // Declare a string that will contain messages when the color rule matches GARBAGE. string garbagePrompt = ""; // BACKGROUND: Check to see if the recognition result contains the semantic key for the background color, // and not a match for the GARBAGE rule, and change the color. if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BACKGROUND") && recoResult.SemanticInterpretation.Properties["KEY_BACKGROUND"][0].ToString() != "...") { string backgroundColor = recoResult.SemanticInterpretation.Properties["KEY_BACKGROUND"][0].ToString(); colorRectangle.Fill = new SolidColorBrush(getColor(backgroundColor)); } // If "background" was matched, but the color rule matched GARBAGE, prompt the user. else if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BACKGROUND") && recoResult.SemanticInterpretation.Properties["KEY_BACKGROUND"][0].ToString() == "...") { garbagePrompt += speechResourceMap.GetValue("SRGSBackgroundGarbagePromptText", speechContext).ValueAsString; resultTextBlock.Text = garbagePrompt; } // BORDER: Check to see if the recognition result contains the semantic key for the border color, // and not a match for the GARBAGE rule, and change the color. if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BORDER") && recoResult.SemanticInterpretation.Properties["KEY_BORDER"][0].ToString() != "...") { string borderColor = recoResult.SemanticInterpretation.Properties["KEY_BORDER"][0].ToString(); colorRectangle.Stroke = new SolidColorBrush(getColor(borderColor)); } // If "border" was matched, but the color rule matched GARBAGE, prompt the user. else if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_BORDER") && recoResult.SemanticInterpretation.Properties["KEY_BORDER"][0].ToString() == "...") { garbagePrompt += speechResourceMap.GetValue("SRGSBorderGarbagePromptText", speechContext).ValueAsString; resultTextBlock.Text = garbagePrompt; } // CIRCLE: Check to see if the recognition result contains the semantic key for the circle color, // and not a match for the GARBAGE rule, and change the color. if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_CIRCLE") && recoResult.SemanticInterpretation.Properties["KEY_CIRCLE"][0].ToString() != "...") { string circleColor = recoResult.SemanticInterpretation.Properties["KEY_CIRCLE"][0].ToString(); colorCircle.Fill = new SolidColorBrush(getColor(circleColor)); } // If "circle" was matched, but the color rule matched GARBAGE, prompt the user. else if (recoResult.SemanticInterpretation.Properties.ContainsKey("KEY_CIRCLE") && recoResult.SemanticInterpretation.Properties["KEY_CIRCLE"][0].ToString() == "...") { garbagePrompt += speechResourceMap.GetValue("SRGSCircleGarbagePromptText", speechContext).ValueAsString; resultTextBlock.Text = garbagePrompt; } // Initialize a string that will describe the user's color choices. string textBoxColors = "You selected (Semantic Interpretation)-> \n"; // Write the color choices contained in the semantics of the recognition result to the text box. foreach (KeyValuePair<String, IReadOnlyList<string>> child in recoResult.SemanticInterpretation.Properties) { // Check to see if any of the semantic values in recognition result contains a match for the GARBAGE rule. if (!child.Value.Equals("...")) { // Cycle through the semantic keys and values and write them to the text box. textBoxColors += (string.Format(" {0} {1}\n", child.Value[0], child.Key ?? "null")); resultTextBlock.Text = textBoxColors; } // If there was no match to the colors rule or if it matched GARBAGE, prompt the user. else { resultTextBlock.Text = garbagePrompt; } } } // Prompt the user if recognition failed or recognition confidence is low. else if (recoResult.Confidence == SpeechRecognitionConfidence.Rejected || recoResult.Confidence == SpeechRecognitionConfidence.Low) { resultTextBlock.Text = speechResourceMap.GetValue("SRGSGarbagePromptText", speechContext).ValueAsString; } } /// <summary> /// Creates a color object from the passed in string. /// </summary> /// <param name="colorString">The name of the color</param> private Color getColor(string colorString) { Color newColor = Colors.Transparent; if (colorLookup.ContainsKey(colorString)) { newColor = colorLookup[colorString]; } return newColor; } } }
using System; using NUnit.Framework; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.Oiw; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.TeleTrust; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Tests { [TestFixture] public class RsaTest : SimpleTest { /** * a fake random number generator - we just want to make sure the random numbers * aren't random so that we get the same output, while still getting to test the * key generation facilities. */ // TODO Use FixedSecureRandom instead? private class MyFixedSecureRandom : SecureRandom { byte[] seed = { (byte)0xaa, (byte)0xfd, (byte)0x12, (byte)0xf6, (byte)0x59, (byte)0xca, (byte)0xe6, (byte)0x34, (byte)0x89, (byte)0xb4, (byte)0x79, (byte)0xe5, (byte)0x07, (byte)0x6d, (byte)0xde, (byte)0xc2, (byte)0xf0, (byte)0x6c, (byte)0xb5, (byte)0x8f }; public override void NextBytes( byte[] bytes) { int offset = 0; while ((offset + seed.Length) < bytes.Length) { seed.CopyTo(bytes, offset); offset += seed.Length; } Array.Copy(seed, 0, bytes, offset, bytes.Length - offset); } } private static readonly byte[] seed = { (byte)0xaa, (byte)0xfd, (byte)0x12, (byte)0xf6, (byte)0x59, (byte)0xca, (byte)0xe6, (byte)0x34, (byte)0x89, (byte)0xb4, (byte)0x79, (byte)0xe5, (byte)0x07, (byte)0x6d, (byte)0xde, (byte)0xc2, (byte)0xf0, (byte)0x6c, (byte)0xb5, (byte)0x8f }; private RsaKeyParameters pubKeySpec = new RsaKeyParameters( false, new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); private RsaPrivateCrtKeyParameters privKeySpec = new RsaPrivateCrtKeyParameters( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); private RsaKeyParameters isoPubKeySpec = new RsaKeyParameters( false, new BigInteger("0100000000000000000000000000000000bba2d15dbb303c8a21c5ebbcbae52b7125087920dd7cdf358ea119fd66fb064012ec8ce692f0a0b8e8321b041acd40b7", 16), new BigInteger("03", 16)); private RsaKeyParameters isoPrivKeySpec = new RsaKeyParameters( true, new BigInteger("0100000000000000000000000000000000bba2d15dbb303c8a21c5ebbcbae52b7125087920dd7cdf358ea119fd66fb064012ec8ce692f0a0b8e8321b041acd40b7", 16), new BigInteger("2aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac9f0783a49dd5f6c5af651f4c9d0dc9281c96a3f16a85f9572d7cc3f2d0f25a9dbf1149e4cdc32273faadd3fda5dcda7", 16)); internal static RsaKeyParameters pub2048KeySpec = new RsaKeyParameters( false, new BigInteger("a7295693155b1813bb84877fb45343556e0568043de5910872a3a518cc11e23e2db74eaf4545068c4e3d258a2718fbacdcc3eafa457695b957e88fbf110aed049a992d9c430232d02f3529c67a3419935ea9b569f85b1bcd37de6b899cd62697e843130ff0529d09c97d813cb15f293751ff56f943fbdabb63971cc7f4f6d5bff1594416b1f5907bde5a84a44f9802ef29b43bda1960f948f8afb8766c1ab80d32eec88ed66d0b65aebe44a6d0b3c5e0ab051aaa1b912fbcc17b8e751ddecc5365b6db6dab0020c3057db4013a51213a5798a3aab67985b0f4d88627a54a0f3f0285fbcb4afdfeb65cb153af66825656d43238b75503231500753f4e421e3c57", 16), new BigInteger("10001", 16)); internal static RsaPrivateCrtKeyParameters priv2048KeySpec = new RsaPrivateCrtKeyParameters( new BigInteger("a7295693155b1813bb84877fb45343556e0568043de5910872a3a518cc11e23e2db74eaf4545068c4e3d258a2718fbacdcc3eafa457695b957e88fbf110aed049a992d9c430232d02f3529c67a3419935ea9b569f85b1bcd37de6b899cd62697e843130ff0529d09c97d813cb15f293751ff56f943fbdabb63971cc7f4f6d5bff1594416b1f5907bde5a84a44f9802ef29b43bda1960f948f8afb8766c1ab80d32eec88ed66d0b65aebe44a6d0b3c5e0ab051aaa1b912fbcc17b8e751ddecc5365b6db6dab0020c3057db4013a51213a5798a3aab67985b0f4d88627a54a0f3f0285fbcb4afdfeb65cb153af66825656d43238b75503231500753f4e421e3c57", 16), new BigInteger("10001", 16), new BigInteger("65dad56ac7df7abb434e4cb5eeadb16093aa6da7f0033aad3815289b04757d32bfee6ade7749c8e4a323b5050a2fb9e2a99e23469e1ed4ba5bab54336af20a5bfccb8b3424cc6923db2ffca5787ed87aa87aa614cd04cedaebc8f623a2d2063017910f436dff18bb06f01758610787f8b258f0a8efd8bd7de30007c47b2a1031696c7d6523bc191d4d918927a7e0b09584ed205bd2ff4fc4382678df82353f7532b3bbb81d69e3f39070aed3fb64fce032a089e8e64955afa5213a6eb241231bd98d702fba725a9b205952fda186412d9e0d9344d2998c455ad8c2bae85ee672751466d5288304032b5b7e02f7e558c7af82c7fbf58eea0bb4ef0f001e6cd0a9", 16), new BigInteger("d4fd9ac3474fb83aaf832470643609659e511b322632b239b688f3cd2aad87527d6cf652fb9c9ca67940e84789444f2e99b0cb0cfabbd4de95396106c865f38e2fb7b82b231260a94df0e01756bf73ce0386868d9c41645560a81af2f53c18e4f7cdf3d51d80267372e6e0216afbf67f655c9450769cca494e4f6631b239ce1b", 16), new BigInteger("c8eaa0e2a1b3a4412a702bccda93f4d150da60d736c99c7c566fdea4dd1b401cbc0d8c063daaf0b579953d36343aa18b33dbf8b9eae94452490cc905245f8f7b9e29b1a288bc66731a29e1dd1a45c9fd7f8238ff727adc49fff73991d0dc096206b9d3a08f61e7462e2b804d78cb8c5eccdb9b7fbd2ad6a8fea46c1053e1be75", 16), new BigInteger("10edcb544421c0f9e123624d1099feeb35c72a8b34e008ac6fa6b90210a7543f293af4e5299c8c12eb464e70092805c7256e18e5823455ba0f504d36f5ccacac1b7cd5c58ff710f9c3f92646949d88fdd1e7ea5fed1081820bb9b0d2a8cd4b093fecfdb96dabd6e28c3a6f8c186dc86cddc89afd3e403e0fcf8a9e0bcb27af0b", 16), new BigInteger("97fc25484b5a415eaa63c03e6efa8dafe9a1c8b004d9ee6e80548fefd6f2ce44ee5cb117e77e70285798f57d137566ce8ea4503b13e0f1b5ed5ca6942537c4aa96b2a395782a4cb5b58d0936e0b0fa63b1192954d39ced176d71ef32c6f42c84e2e19f9d4dd999c2151b032b97bd22aa73fd8c5bcd15a2dca4046d5acc997021", 16), new BigInteger("4bb8064e1eff7e9efc3c4578fcedb59ca4aef0993a8312dfdcb1b3decf458aa6650d3d0866f143cbf0d3825e9381181170a0a1651eefcd7def786b8eb356555d9fa07c85b5f5cbdd74382f1129b5e36b4166b6cc9157923699708648212c484958351fdc9cf14f218dbe7fbf7cbd93a209a4681fe23ceb44bab67d66f45d1c9d", 16)); public override void PerformTest() { byte[] input = new byte[] { (byte)0x54, (byte)0x85, (byte)0x9b, (byte)0x34, (byte)0x2c, (byte)0x49, (byte)0xea, (byte)0x2a }; byte[][] output = new byte[][] { Hex.Decode("8b427f781a2e59dd9def386f1956b996ee07f48c96880e65a368055ed8c0a8831669ef7250b40918b2b1d488547e72c84540e42bd07b03f14e226f04fbc2d929"), Hex.Decode("2ec6e1a1711b6c7b8cd3f6a25db21ab8bb0a5f1d6df2ef375fa708a43997730ffc7c98856dbbe36edddcdd1b2d2a53867d8355af94fea3aeec128da908e08f4c"), Hex.Decode("0850ac4e5a8118323200c8ed1e5aaa3d5e635172553ccac66a8e4153d35c79305c4440f11034ab147fccce21f18a50cf1c0099c08a577eb68237a91042278965"), Hex.Decode("1c9649bdccb51056751fe43837f4eb43bada472accf26f65231666d5de7d11950d8379b3596dfdf75c6234274896fa8d18ad0865d3be2ac4d6687151abdf01e93941dcef18fa63186c9351d1506c89d09733c5ff4304208c812bdd21a50f56fde115e629e0e973721c9fcc87e89295a79853dee613962a0b2f2fc57163fd99057a3c776f13c20c26407eb8863998d7e53b543ba8d0a295a9a68d1a149833078c9809ad6a6dad7fc22a95ad615a73138c54c018f40d99bf8eeecd45f5be526f2d6b01aeb56381991c1ab31a2e756f15e052b9cd5638b2eff799795c5bae493307d5eb9f8c21d438de131fe505a4e7432547ab19224094f9e4be1968bd0793b79d"), Hex.Decode("4c4afc0c24dddaedd4f9a3b23be30d35d8e005ffd36b3defc5d18acc830c3ed388ce20f43a00e614fd087c814197bc9fc2eff9ad4cc474a7a2ef3ed9c0f0a55eb23371e41ee8f2e2ed93ea3a06ca482589ab87e0d61dcffda5eea1241408e43ea1108726cdb87cc3aa5e9eaaa9f72507ca1352ac54a53920c94dccc768147933d8c50aefd9d1da10522a40133cd33dbc0524669e70f771a88d65c4716d471cd22b08b9f01f24e4e9fc7ffbcfa0e0a7aed47b345826399b26a73be112eb9c5e06fc6742fc3d0ef53d43896403c5105109cfc12e6deeaf4a48ba308e039774b9bdb31a9b9e133c81c321630cf0b4b2d1f90717b24c3268e1fea681ea9cdc709342"), Hex.Decode("06b5b26bd13515f799e5e37ca43cace15cd82fd4bf36b25d285a6f0998d97c8cb0755a28f0ae66618b1cd03e27ac95eaaa4882bc6dc0078cd457d4f7de4154173a9c7a838cfc2ac2f74875df462aae0cfd341645dc51d9a01da9bdb01507f140fa8a016534379d838cc3b2a53ac33150af1b242fc88013cb8d914e66c8182864ee6de88ce2879d4c05dd125409620a96797c55c832fb2fb31d4310c190b8ed2c95fdfda2ed87f785002faaec3f35ec05cf70a3774ce185e4882df35719d582dd55ac31257344a9cba95189dcbea16e8c6cb7a235a0384bc83b6183ca8547e670fe33b1b91725ae0c250c9eca7b5ba78bd77145b70270bf8ac31653006c02ca9c"), Hex.Decode("135f1be3d045526235bf9d5e43499d4ee1bfdf93370769ae56e85dbc339bc5b7ea3bee49717497ee8ac3f7cd6adb6fc0f17812390dcd65ac7b87fef7970d9ff9"), Hex.Decode("03c05add1e030178c352face07cafc9447c8f369b8f95125c0d311c16b6da48ca2067104cce6cd21ae7b163cd18ffc13001aecebdc2eb02b9e92681f84033a98"), Hex.Decode("00319bb9becb49f3ed1bca26d0fcf09b0b0a508e4d0bd43b350f959b72cd25b3af47d608fdcd248eada74fbe19990dbeb9bf0da4b4e1200243a14e5cab3f7e610c") }; SecureRandom rand = new MyFixedSecureRandom(); // KeyFactory fact = KeyFactory.GetInstance("RSA"); // // PrivateKey privKey = fact.generatePrivate(privKeySpec); // PublicKey pubKey = fact.generatePublic(pubKeySpec); IAsymmetricKeyParameter privKey = privKeySpec; IAsymmetricKeyParameter pubKey = pubKeySpec; // PrivateKey priv2048Key = fact.generatePrivate(priv2048KeySpec); // PublicKey pub2048Key = fact.generatePublic(pub2048KeySpec); IAsymmetricKeyParameter priv2048Key = priv2048KeySpec; IAsymmetricKeyParameter pub2048Key = pub2048KeySpec; // // No Padding // // Cipher c = Cipher.GetInstance("RSA"); IBufferedCipher c = CipherUtilities.GetCipher("RSA"); // c.init(Cipher.ENCRYPT_MODE, pubKey, rand); c.Init(true, pubKey);// new ParametersWithRandom(pubKey, rand)); byte[] outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[0])) { Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes)); } // c.init(Cipher.DECRYPT_MODE, privKey); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // No Padding - incremental // // c = Cipher.GetInstance("RSA"); c = CipherUtilities.GetCipher("RSA"); // c.init(Cipher.ENCRYPT_MODE, pubKey, rand); c.Init(true, pubKey);// new ParametersWithRandom(pubKey, rand)); c.ProcessBytes(input); outBytes = c.DoFinal(); if (!AreEqual(outBytes, output[0])) { Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes)); } // c.init(Cipher.DECRYPT_MODE, privKey); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // No Padding - incremental - explicit use of NONE in mode. // c = CipherUtilities.GetCipher("RSA/NONE/NoPadding"); // c.init(Cipher.ENCRYPT_MODE, pubKey, rand); c.Init(true, pubKey);// new ParametersWithRandom(pubKey, rand)); c.ProcessBytes(input); outBytes = c.DoFinal(); if (!AreEqual(outBytes, output[0])) { Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes)); } // c.init(Cipher.DECRYPT_MODE, privKey); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // No Padding - maximum.Length // c = CipherUtilities.GetCipher("RSA"); byte[] modBytes = ((RsaKeyParameters) pubKey).Modulus.ToByteArray(); byte[] maxInput = new byte[modBytes.Length - 1]; maxInput[0] |= 0x7f; c.Init(true, pubKey);// new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(maxInput); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, maxInput)) { Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(maxInput) + " got " + Hex.ToHexString(outBytes)); } // // PKCS1 V 1.5 // c = CipherUtilities.GetCipher("RSA//PKCS1Padding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[1])) { Fail("PKCS1 test failed on encrypt expected " + Hex.ToHexString(output[1]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("PKCS1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // PKCS1 V 1.5 - NONE // c = CipherUtilities.GetCipher("RSA/NONE/PKCS1Padding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[1])) { Fail("PKCS1 test failed on encrypt expected " + Hex.ToHexString(output[1]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("PKCS1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // OAEP - SHA1 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[2])) { Fail("OAEP test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding"); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // TODO // AlgorithmParameters oaepP = c.getParameters(); byte[] rop = new RsaesOaepParameters( new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded())) // { // Fail("OAEP test failed default sha-1 parameters"); // } // // OAEP - SHA224 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA224AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pub2048Key, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[3])) { Fail("OAEP SHA-224 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, priv2048Key); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP SHA-224 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default sha-224 parameters"); // } // // OAEP - SHA 256 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA256AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pub2048Key, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[4])) { Fail("OAEP SHA-256 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, priv2048Key); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP SHA-256 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default sha-256 parameters"); // } // // OAEP - SHA 384 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA384AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pub2048Key, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[5])) { Fail("OAEP SHA-384 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, priv2048Key); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP SHA-384 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default sha-384 parameters"); // } // // OAEP - MD5 // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithMD5AndMGF1Padding"); c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); if (!AreEqual(outBytes, output[6])) { Fail("OAEP MD5 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("OAEP MD5 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()) // { // Fail("OAEP test failed default md5 parameters"); // } // // OAEP - SHA1 with default parameters // c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding"); // TODO // c.init(Cipher.ENCRYPT_MODE, pubKey, OAEPParameterSpec.DEFAULT, rand); // // outBytes = c.DoFinal(input); // // if (!AreEqual(outBytes, output[2])) // { // Fail("OAEP test failed on encrypt expected " + Encoding.ASCII.GetString(Hex.Encode(output[2])) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } // // c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding"); // // c.Init(false, privKey); // // outBytes = c.DoFinal(outBytes); // // if (!AreEqual(outBytes, input)) // { // Fail("OAEP test failed on decrypt expected " + Encoding.ASCII.GetString(Hex.Encode(input)) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } // // oaepP = c.getParameters(); // // if (!AreEqual(oaepP.getEncoded(), new byte[] { 0x30, 0x00 })) // { // Fail("OAEP test failed default parameters"); // } // // OAEP - SHA1 with specified string // c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding"); // TODO // c.init(Cipher.ENCRYPT_MODE, pubKey, new OAEPParameterSpec("SHA1", "MGF1", new MGF1ParameterSpec("SHA1"), new PSource.PSpecified(new byte[] { 1, 2, 3, 4, 5 })), rand); // // outBytes = c.DoFinal(input); // // oaepP = c.getParameters(); rop = new RsaesOaepParameters( new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance)), new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[] { 1, 2, 3, 4, 5 }))).GetEncoded(); // if (!AreEqual(oaepP.getEncoded()) // { // Fail("OAEP test failed changed sha-1 parameters"); // } // // if (!AreEqual(outBytes, output[7])) // { // Fail("OAEP test failed on encrypt expected " + Encoding.ASCII.GetString(Hex.Encode(output[2])) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding"); // TODO // c.init(Cipher.DECRYPT_MODE, privKey, oaepP); // // outBytes = c.DoFinal(outBytes); // // if (!AreEqual(outBytes, input)) // { // Fail("OAEP test failed on decrypt expected " + Encoding.ASCII.GetString(Hex.Encode(input)) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes))); // } // // iso9796-1 // byte[] isoInput = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"); // PrivateKey isoPrivKey = fact.generatePrivate(isoPrivKeySpec); // PublicKey isoPubKey = fact.generatePublic(isoPubKeySpec); IAsymmetricKeyParameter isoPrivKey = isoPrivKeySpec; IAsymmetricKeyParameter isoPubKey = isoPubKeySpec; c = CipherUtilities.GetCipher("RSA/NONE/ISO9796-1Padding"); c.Init(true, isoPrivKey); outBytes = c.DoFinal(isoInput); if (!AreEqual(outBytes, output[8])) { Fail("ISO9796-1 test failed on encrypt expected " + Hex.ToHexString(output[3]) + " got " + Hex.ToHexString(outBytes)); } c.Init(false, isoPubKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, isoInput)) { Fail("ISO9796-1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // // generation with parameters test. // IAsymmetricCipherKeyPairGenerator keyPairGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); // // 768 bit RSA with e = 2^16-1 // keyPairGen.Init( new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 768, 25)); IAsymmetricCipherKeyPair kp = keyPairGen.GenerateKeyPair(); pubKey = kp.Public; privKey = kp.Private; c.Init(true, new ParametersWithRandom(pubKey, rand)); outBytes = c.DoFinal(input); c.Init(false, privKey); outBytes = c.DoFinal(outBytes); if (!AreEqual(outBytes, input)) { Fail("key generation test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes)); } // // comparison check // // KeyFactory keyFact = KeyFactory.GetInstance("RSA"); // // RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey)keyFact.translateKey(privKey); RsaPrivateCrtKeyParameters crtKey = (RsaPrivateCrtKeyParameters) privKey; if (!privKey.Equals(crtKey)) { Fail("private key equality check failed"); } // RSAPublicKey copyKey = (RSAPublicKey)keyFact.translateKey(pubKey); RsaKeyParameters copyKey = (RsaKeyParameters) pubKey; if (!pubKey.Equals(copyKey)) { Fail("public key equality check failed"); } SecureRandom random = new SecureRandom(); rawModeTest("SHA1withRSA", X509ObjectIdentifiers.IdSha1, priv2048Key, pub2048Key, random); rawModeTest("MD5withRSA", PkcsObjectIdentifiers.MD5, priv2048Key, pub2048Key, random); rawModeTest("RIPEMD128withRSA", TeleTrusTObjectIdentifiers.RipeMD128, priv2048Key, pub2048Key, random); } private void rawModeTest(string sigName, DerObjectIdentifier digestOID, IAsymmetricKeyParameter privKey, IAsymmetricKeyParameter pubKey, SecureRandom random) { byte[] sampleMessage = new byte[1000 + random.Next() % 100]; random.NextBytes(sampleMessage); ISigner normalSig = SignerUtilities.GetSigner(sigName); normalSig.Init(true, privKey); normalSig.BlockUpdate(sampleMessage, 0, sampleMessage.Length); byte[] normalResult = normalSig.GenerateSignature(); byte[] hash = DigestUtilities.CalculateDigest(digestOID.Id, sampleMessage); byte[] digInfo = derEncode(digestOID, hash); ISigner rawSig = SignerUtilities.GetSigner("RSA"); rawSig.Init(true, privKey); rawSig.BlockUpdate(digInfo, 0, digInfo.Length); byte[] rawResult = rawSig.GenerateSignature(); if (!Arrays.AreEqual(normalResult, rawResult)) { Fail("raw mode signature differs from normal one"); } rawSig.Init(false, pubKey); rawSig.BlockUpdate(digInfo, 0, digInfo.Length); if (!rawSig.VerifySignature(rawResult)) { Fail("raw mode signature verification failed"); } } private byte[] derEncode(DerObjectIdentifier oid, byte[] hash) { AlgorithmIdentifier algId = new AlgorithmIdentifier(oid, DerNull.Instance); DigestInfo dInfo = new DigestInfo(algId, hash); return dInfo.GetEncoded(Asn1Encodable.Der); } public override string Name { get { return "RSATest"; } } public static void Main( string[] args) { ITest test = new RsaTest(); ITestResult result = test.Perform(); Console.WriteLine(result); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Reactive.Linq; using System.Threading.Tasks; using Avalonia.Controls.Platform; using Avalonia.Input; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Platform; using Avalonia.Styling; using System.Collections.Generic; namespace Avalonia.Controls { /// <summary> /// Determines how a <see cref="Window"/> will size itself to fit its content. /// </summary> public enum SizeToContent { /// <summary> /// The window will not automatically size itself to fit its content. /// </summary> Manual, /// <summary> /// The window will size itself horizontally to fit its content. /// </summary> Width, /// <summary> /// The window will size itself vertically to fit its content. /// </summary> Height, /// <summary> /// The window will size itself horizontally and vertically to fit its content. /// </summary> WidthAndHeight, } /// <summary> /// A top-level window. /// </summary> public class Window : TopLevel, IStyleable, IFocusScope, ILayoutRoot, INameScope { private static IList<Window> s_windows = new List<Window>(); /// <summary> /// Retrieves an enumeration of all Windows in the currently running application. /// </summary> public static IList<Window> OpenWindows => s_windows; /// <summary> /// Defines the <see cref="SizeToContent"/> property. /// </summary> public static readonly StyledProperty<SizeToContent> SizeToContentProperty = AvaloniaProperty.Register<Window, SizeToContent>(nameof(SizeToContent)); /// <summary> /// Enables of disables system window decorations (title bar, buttons, etc) /// </summary> public static readonly StyledProperty<bool> HasSystemDecorationsProperty = AvaloniaProperty.Register<Window, bool>(nameof(HasSystemDecorations), true); /// <summary> /// Defines the <see cref="Title"/> property. /// </summary> public static readonly StyledProperty<string> TitleProperty = AvaloniaProperty.Register<Window, string>(nameof(Title), "Window"); private readonly NameScope _nameScope = new NameScope(); private object _dialogResult; private readonly Size _maxPlatformClientSize; /// <summary> /// Initializes static members of the <see cref="Window"/> class. /// </summary> static Window() { BackgroundProperty.OverrideDefaultValue(typeof(Window), Brushes.White); TitleProperty.Changed.AddClassHandler<Window>((s, e) => s.PlatformImpl.SetTitle((string)e.NewValue)); HasSystemDecorationsProperty.Changed.AddClassHandler<Window>( (s, e) => s.PlatformImpl.SetSystemDecorations((bool) e.NewValue)); } /// <summary> /// Initializes a new instance of the <see cref="Window"/> class. /// </summary> public Window() : base(PlatformManager.CreateWindow()) { _maxPlatformClientSize = this.PlatformImpl.MaxClientSize; } /// <inheritdoc/> event EventHandler<NameScopeEventArgs> INameScope.Registered { add { _nameScope.Registered += value; } remove { _nameScope.Registered -= value; } } /// <inheritdoc/> event EventHandler<NameScopeEventArgs> INameScope.Unregistered { add { _nameScope.Unregistered += value; } remove { _nameScope.Unregistered -= value; } } /// <summary> /// Gets the platform-specific window implementation. /// </summary> public new IWindowImpl PlatformImpl => (IWindowImpl)base.PlatformImpl; /// <summary> /// Gets or sets a value indicating how the window will size itself to fit its content. /// </summary> public SizeToContent SizeToContent { get { return GetValue(SizeToContentProperty); } set { SetValue(SizeToContentProperty, value); } } /// <summary> /// Gets or sets the title of the window. /// </summary> public string Title { get { return GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } /// <summary> /// Enables of disables system window decorations (title bar, buttons, etc) /// </summary> /// public bool HasSystemDecorations { get { return GetValue(HasSystemDecorationsProperty); } set { SetValue(HasSystemDecorationsProperty, value); } } /// <summary> /// Gets or sets the minimized/maximized state of the window. /// </summary> public WindowState WindowState { get { return this.PlatformImpl.WindowState; } set { this.PlatformImpl.WindowState = value; } } /// <inheritdoc/> Size ILayoutRoot.MaxClientSize => _maxPlatformClientSize; /// <inheritdoc/> Type IStyleable.StyleKey => typeof(Window); /// <summary> /// Closes the window. /// </summary> public void Close() { s_windows.Remove(this); PlatformImpl.Dispose(); } protected override void HandleApplicationExiting() { base.HandleApplicationExiting(); Close(); } /// <summary> /// Closes a dialog window with the specified result. /// </summary> /// <param name="dialogResult">The dialog result.</param> /// <remarks> /// When the window is shown with the <see cref="ShowDialog{TResult}"/> method, the /// resulting task will produce the <see cref="_dialogResult"/> value when the window /// is closed. /// </remarks> public void Close(object dialogResult) { _dialogResult = dialogResult; Close(); } /// <summary> /// Hides the window but does not close it. /// </summary> public void Hide() { using (BeginAutoSizing()) { PlatformImpl.Hide(); } } /// <summary> /// Shows the window. /// </summary> public void Show() { s_windows.Add(this); EnsureInitialized(); LayoutManager.Instance.ExecuteInitialLayoutPass(this); using (BeginAutoSizing()) { PlatformImpl.Show(); } } /// <summary> /// Shows the window as a dialog. /// </summary> /// <returns> /// A task that can be used to track the lifetime of the dialog. /// </returns> public Task ShowDialog() { return ShowDialog<object>(); } /// <summary> /// Shows the window as a dialog. /// </summary> /// <typeparam name="TResult"> /// The type of the result produced by the dialog. /// </typeparam> /// <returns>. /// A task that can be used to retrive the result of the dialog when it closes. /// </returns> public Task<TResult> ShowDialog<TResult>() { s_windows.Add(this); EnsureInitialized(); LayoutManager.Instance.ExecuteInitialLayoutPass(this); using (BeginAutoSizing()) { var modal = PlatformImpl.ShowDialog(); var result = new TaskCompletionSource<TResult>(); Observable.FromEventPattern(this, nameof(Closed)) .Take(1) .Subscribe(_ => { modal.Dispose(); result.SetResult((TResult)_dialogResult); }); return result.Task; } } /// <inheritdoc/> void INameScope.Register(string name, object element) { _nameScope.Register(name, element); } /// <inheritdoc/> object INameScope.Find(string name) { return _nameScope.Find(name); } /// <inheritdoc/> void INameScope.Unregister(string name) { _nameScope.Unregister(name); } /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { var sizeToContent = SizeToContent; var size = ClientSize; var desired = base.MeasureOverride(availableSize.Constrain(_maxPlatformClientSize)); switch (sizeToContent) { case SizeToContent.Width: size = new Size(desired.Width, ClientSize.Height); break; case SizeToContent.Height: size = new Size(ClientSize.Width, desired.Height); break; case SizeToContent.WidthAndHeight: size = new Size(desired.Width, desired.Height); break; case SizeToContent.Manual: size = ClientSize; break; default: throw new InvalidOperationException("Invalid value for SizeToContent."); } return size; } /// <inheritdoc/> protected override void HandleResized(Size clientSize) { if (!AutoSizing) { SizeToContent = SizeToContent.Manual; } base.HandleResized(clientSize); } private void EnsureInitialized() { if (!this.IsInitialized) { var init = (ISupportInitialize)this; init.BeginInit(); init.EndInit(); } } } } namespace Avalonia { public static class WindowApplicationExtensions { public static void RunWithMainWindow<TWindow>(this Application app) where TWindow : Avalonia.Controls.Window, new() { var window = new TWindow(); window.Show(); app.Run(window); } } }
using Cake.Common; using Cake.Core; using Cake.Core.Annotations; using Cake.Core.Diagnostics; using System; using System.Linq; namespace CodeCake { /// <summary> /// Contains functionalities related to the interactive mode. /// </summary> [CakeAliasCategory( "Environment" )] public static class InteractiveAliases { /// <summary> /// The "nointeraction" string with no dash before. /// </summary> public static readonly string NoInteractionArgument = "nointeraction"; /// <summary> /// The "autointeraction" string with no dash before. /// </summary> public static readonly string AutoInteractionArgument = "autointeraction"; /// <summary> /// Gets the current <see cref="CodeCake.InteractiveMode"/>. /// </summary> /// <param name="context">The context.</param> /// <returns>The mode.</returns> [CakeAliasCategory( "Interactive mode" )] [CakeMethodAlias] public static InteractiveMode InteractiveMode( this ICakeContext context ) { if( context.HasArgument( NoInteractionArgument ) ) return CodeCake.InteractiveMode.NoInteraction; if( context.HasArgument( AutoInteractionArgument ) ) return CodeCake.InteractiveMode.AutoInteraction; return CodeCake.InteractiveMode.Interactive; } /// <summary> /// Gets whether the context requires interaction with the user: /// False if -nointeraction or -autointeraction argument has been provided, true if no specific argument have been provided. /// </summary> /// <param name="context">The context.</param> /// <returns>True if interactive mode is available, false otherwise.</returns> [Obsolete( "Use the less ambiguous InteractiveMode() enum value instead.", false)] [CakeAliasCategory( "Interactive mode" )] [CakeMethodAlias] public static bool IsInteractiveMode( this ICakeContext context ) { return !context.HasArgument( NoInteractionArgument ); } /// <summary> /// Gets whether the context supports automatic interaction (argument -autointeraction has been provided). /// When this is true, <see cref="IsInteractiveMode"/> is false. /// </summary> /// <param name="context">The context.</param> /// <returns>True if interactive mode is available, false otherwise.</returns> [Obsolete( "Use the less ambiguous InteractiveMode() enum value instead.", false )] [CakeAliasCategory( "Interactive mode" )] [CakeMethodAlias] public static bool IsAutoInteractiveMode( this ICakeContext context ) { return IsInteractiveMode( context ) && context.HasArgument( AutoInteractionArgument ); } /// <summary> /// Prompts the user for one of the <paramref name="options"/> characters that MUST be uppercase. /// <see cref="InteractiveMode()"/> must be <see cref="CodeCake.InteractiveMode.AutoInteraction"/> /// or <see cref="CodeCake.InteractiveMode.Interactive"/> otherwise an <see cref="InvalidOperationException"/> is thrown. /// </summary> /// <param name="context">The context.</param> /// <param name="message"> /// Message that will be displayed in front of the input. /// When null, no message is displayed, when not null, the options are automatically displayed: (Y/N/C). /// </param> /// <param name="options">Allowed characters that must be uppercase.</param> /// <returns>The entered char (always in uppercase). Necessarily one of the <paramref name="options"/>.</returns> [CakeAliasCategory( "Interactive mode" )] [CakeMethodAlias] public static char ReadInteractiveOption( this ICakeContext context, string message, params char[] options ) { return DoReadInteractiveOption( context, null, message, options ); } /// <summary> /// Prompts the user for one of the <paramref name="options"/> characters that MUST be uppercase after /// having looked for a program argument that answers the prompt (ex: -RunUnitTests=N). /// <see cref="InteractiveMode()"/> must be <see cref="CodeCake.InteractiveMode.AutoInteraction"/> /// or <see cref="CodeCake.InteractiveMode.Interactive"/> otherwise an <see cref="InvalidOperationException"/> is thrown. /// </summary> /// <param name="context">The context.</param> /// <param name="argumentName">Name of the command line argument.</param> /// <param name="message"> /// Message that will be displayed in front of the input. /// When null, no message is displayed, when not null, the options are automatically displayed: (Y/N/C). /// </param> /// <param name="options">Allowed characters that must be uppercase.</param> /// <returns>The entered char (always in uppercase). Necessarily one of the <paramref name="options"/>.</returns> [CakeAliasCategory( "Interactive mode" )] [CakeMethodAlias] public static char ReadInteractiveOption( this ICakeContext context, string argumentName, string message, params char[] options ) { if( String.IsNullOrWhiteSpace( argumentName ) ) throw new ArgumentException( "Must be a non empty string.", nameof( argumentName ) ); return DoReadInteractiveOption( context, argumentName, message, options ); } static char DoReadInteractiveOption( ICakeContext context, string argumentName, string message, char[] options ) { if( options == null || options.Length == 0 ) throw new ArgumentException( "At least one (uppercase) character for options must be provided." ); var mode = InteractiveMode( context ); if( mode == CodeCake.InteractiveMode.NoInteraction ) throw new InvalidOperationException( "Interactions are not allowed." ); if( options.Any( c => char.IsLower( c ) ) ) throw new ArgumentException( "Options must be uppercase letter." ); string choices = String.Join( "/", options ); if( string.IsNullOrWhiteSpace( message ) ) Console.Write( "{0}: ", choices ); else Console.Write( "{0} ({1}): ", message, choices ); if( argumentName != null && context.Arguments.HasArgument( argumentName ) ) { string arg = context.Arguments.GetArgument( argumentName ); if( arg.Length != 1 || !options.Contains( char.ToUpperInvariant( arg[0] ) ) ) { Console.WriteLine(); context.Log.Error( $"Provided command line argument -{argumentName}={arg} is invalid. It must be a unique character in: {choices}" ); // Fallback to interactive mode below. } else { var c = char.ToUpperInvariant( arg[0] ); Console.WriteLine( c ); context.Log.Information( $"Answered by command line argument -{argumentName}={arg}." ); return c; } } if( mode == CodeCake.InteractiveMode.AutoInteraction ) { char c = options[0]; Console.WriteLine( c ); if( argumentName != null ) { context.Log.Information( $"Mode -autointeraction (and no command line -{argumentName}=\"value\" argument found): automatically answer with the first choice: {c}." ); } else { context.Log.Information( $"Mode -autointeraction: automatically answer with the first choice: {c}." ); } return c; } for(; ; ) { char c = char.ToUpperInvariant( Console.ReadKey().KeyChar ); Console.WriteLine(); if( options.Contains( c ) ) return c; Console.Write( $"Invalid choice '{c}'. Must be one of {choices}: " ); } } /// <summary> /// Retrieves the value of the environment variable or null if the environment variable do not exist /// and can not be given by the user. /// In -autointeraction mode, the value can be provided on the commannd line using -ENV:<paramref name="variable"/>=... parameter. /// </summary> /// <param name="context">The context.</param> /// <param name="variable">The environment variable.</param> /// <param name="setCache">By default, if the value is interactively read, it is stored in the process environment variables.</param> /// <returns>Retrieves the value of the environment variable or null if the environment variable do not exist.</returns> [CakeAliasCategory( "Environment Variables" )] [CakeMethodAlias] public static string InteractiveEnvironmentVariable( this ICakeContext context, string variable, bool setCache = true ) { string v = context.EnvironmentVariable( variable ); var mode = InteractiveMode( context ); if( v == null && mode != CodeCake.InteractiveMode.NoInteraction ) { Console.Write( $"Environment Variable '{variable}' not found. Enter its value: " ); if( mode == CodeCake.InteractiveMode.AutoInteraction ) { string fromArgName = "ENV:" + variable; string fromArg = context.Arguments.HasArgument( fromArgName ) ? context.Arguments.GetArgument( fromArgName ) : null; if( fromArg != null ) { Console.WriteLine( v = fromArg ); context.Log.Information( $"Mode -autointeraction: automatically answer with command line -{fromArgName}={fromArg} argument." ); } else { Console.WriteLine( v = String.Empty ); context.Log.Information( $"Mode -autointeraction (and no command line -{fromArgName}=XXX argument): automatically answer with an empty string." ); } } else v = Console.ReadLine(); if( setCache ) Environment.SetEnvironmentVariable( variable, v ); } return v; } } }
using System; namespace ServiceStack.ServiceHost { [Flags] public enum EndpointAttributes : long { None = 0, Any = AnyNetworkAccessType | AnySecurityMode | AnyHttpMethod | AnyCallStyle | AnyFormat, AnyNetworkAccessType = External | Localhost | LocalSubnet, AnySecurityMode = Secure | InSecure, AnyHttpMethod = HttpHead | HttpGet | HttpPost | HttpPut | HttpDelete | HttpOther, AnyCallStyle = OneWay | Reply, AnyFormat = Soap11 | Soap12 | Xml | Json | Jsv | Html | ProtoBuf | Csv | MsgPack | Yaml | FormatOther, AnyEndpoint = Http | MessageQueue | Tcp | EndpointOther, InternalNetworkAccess = Localhost | LocalSubnet, //Whether it came from an Internal or External address Localhost = 1 << 0, LocalSubnet = 1 << 1, External = 1 << 2, //Called over a secure or insecure channel Secure = 1 << 3, InSecure = 1 << 4, //HTTP request type HttpHead = 1 << 5, HttpGet = 1 << 6, HttpPost = 1 << 7, HttpPut = 1 << 8, HttpDelete = 1 << 9, HttpPatch = 1 << 10, HttpOptions = 1 << 11, HttpOther = 1 << 12, //Call Styles OneWay = 1 << 13, Reply = 1 << 14, //Different formats Soap11 = 1 << 15, Soap12 = 1 << 16, //POX Xml = 1 << 17, //Javascript Json = 1 << 18, //Jsv i.e. TypeSerializer Jsv = 1 << 19, //e.g. protobuf-net ProtoBuf = 1 << 20, //e.g. text/csv Csv = 1 << 21, Html = 1 << 22, Yaml = 1 << 23, MsgPack = 1 << 24, FormatOther = 1 << 25, //Different endpoints Http = 1 << 26, MessageQueue = 1 << 27, Tcp = 1 << 28, EndpointOther = 1 << 29, } public enum Network : long { Localhost = 1 << 0, LocalSubnet = 1 << 1, External = 1 << 2, } public enum Security : long { Secure = 1 << 3, InSecure = 1 << 4, } public enum Http : long { Head = 1 << 5, Get = 1 << 6, Post = 1 << 7, Put = 1 << 8, Delete = 1 << 9, Patch = 1 << 10, Options = 1 << 11, Other = 1 << 12, } public enum CallStyle : long { OneWay = 1 << 13, Reply = 1 << 14, } public enum Format : long { Soap11 = 1 << 15, Soap12 = 1 << 16, Xml = 1 << 17, Json = 1 << 18, Jsv = 1 << 19, ProtoBuf = 1 << 20, Csv = 1 << 21, Html = 1 << 22, Yaml = 1 << 23, MsgPack = 1 << 24, Other = 1 << 25, } public enum Endpoint : long { Http = 1 << 26, MessageQueue = 1 << 27, Tcp = 1 << 28, Other = 1 << 29, } public static class EndpointAttributesExtensions { public static bool IsLocalhost(this EndpointAttributes attrs) { return (EndpointAttributes.Localhost & attrs) == EndpointAttributes.Localhost; } public static bool IsLocalSubnet(this EndpointAttributes attrs) { return (EndpointAttributes.LocalSubnet & attrs) == EndpointAttributes.LocalSubnet; } public static bool IsExternal(this EndpointAttributes attrs) { return (EndpointAttributes.External & attrs) == EndpointAttributes.External; } public static Format ToFormat(this string format) { try { return (Format)Enum.Parse(typeof(Format), format.ToUpper().Replace("X-", ""), true); } catch (Exception) { return Format.Other; } } public static string FromFormat(this Format format) { var formatStr = format.ToString().ToLower(); if (format == Format.ProtoBuf || format == Format.MsgPack) return "x-" + formatStr; return formatStr; } public static Format ToFormat(this Feature feature) { switch (feature) { case Feature.Xml: return Format.Xml; case Feature.Json: return Format.Json; case Feature.Jsv: return Format.Jsv; case Feature.Csv: return Format.Csv; case Feature.Html: return Format.Html; case Feature.MsgPack: return Format.MsgPack; case Feature.ProtoBuf: return Format.ProtoBuf; case Feature.Soap11: return Format.Soap11; case Feature.Soap12: return Format.Soap12; } return Format.Other; } public static Feature ToFeature(this Format format) { switch (format) { case Format.Xml: return Feature.Xml; case Format.Json: return Feature.Json; case Format.Jsv: return Feature.Jsv; case Format.Csv: return Feature.Csv; case Format.Html: return Feature.Html; case Format.MsgPack: return Feature.MsgPack; case Format.ProtoBuf: return Feature.ProtoBuf; case Format.Soap11: return Feature.Soap11; case Format.Soap12: return Feature.Soap12; } return Feature.CustomFormat; } public static Feature ToSoapFeature(this EndpointAttributes attributes) { if ((EndpointAttributes.Soap11 & attributes) == EndpointAttributes.Soap11) return Feature.Soap11; if ((EndpointAttributes.Soap12 & attributes) == EndpointAttributes.Soap12) return Feature.Soap12; return Feature.None; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Runspaces; namespace Microsoft.PowerShell.Commands { #region PSRunspaceDebug class /// <summary> /// Runspace Debug Options class. /// </summary> public sealed class PSRunspaceDebug { #region Properties /// <summary> /// When true this property will cause any breakpoints set in a Runspace to stop /// the running command or script when the breakpoint is hit, regardless of whether a /// debugger is currently attached. The script or command will remain stopped until /// a debugger is attached to debug the breakpoint. /// </summary> public bool Enabled { get; } /// <summary> /// When true this property will cause any running command or script in the Runspace /// to stop in step mode, regardless of whether a debugger is currently attached. The /// script or command will remain stopped until a debugger is attached to debug the /// current stop point. /// </summary> public bool BreakAll { get; } /// <summary> /// Name of runspace for which the options apply. /// </summary> public string RunspaceName { get; } /// <summary> /// Local Id of runspace for which the options apply. /// </summary> public int RunspaceId { get; } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="PSRunspaceDebug"/> class. /// </summary> /// <param name="enabled">Enable debugger option.</param> /// <param name="breakAll">BreakAll option.</param> /// <param name="runspaceName">Runspace name.</param> /// <param name="runspaceId">Runspace local Id.</param> public PSRunspaceDebug(bool enabled, bool breakAll, string runspaceName, int runspaceId) { if (string.IsNullOrEmpty(runspaceName)) { throw new PSArgumentNullException(nameof(runspaceName)); } this.Enabled = enabled; this.BreakAll = breakAll; this.RunspaceName = runspaceName; this.RunspaceId = runspaceId; } #endregion } #endregion #region CommonRunspaceCommandBase class /// <summary> /// Abstract class that defines common Runspace Command parameters. /// </summary> public abstract class CommonRunspaceCommandBase : PSCmdlet { #region Strings /// <summary> /// RunspaceParameterSet. /// </summary> protected const string RunspaceParameterSet = "RunspaceParameterSet"; /// <summary> /// RunspaceNameParameterSet. /// </summary> protected const string RunspaceNameParameterSet = "RunspaceNameParameterSet"; /// <summary> /// RunspaceIdParameterSet. /// </summary> protected const string RunspaceIdParameterSet = "RunspaceIdParameterSet"; /// <summary> /// RunspaceInstanceIdParameterSet. /// </summary> protected const string RunspaceInstanceIdParameterSet = "RunspaceInstanceIdParameterSet"; /// <summary> /// ProcessNameParameterSet. /// </summary> protected const string ProcessNameParameterSet = "ProcessNameParameterSet"; #endregion #region Parameters /// <summary> /// Runspace Name. /// </summary> [Parameter(Position = 0, ParameterSetName = CommonRunspaceCommandBase.RunspaceNameParameterSet)] [ValidateNotNullOrEmpty()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] RunspaceName { get; set; } /// <summary> /// Runspace. /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, ParameterSetName = CommonRunspaceCommandBase.RunspaceParameterSet)] [ValidateNotNullOrEmpty()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Runspace[] Runspace { get; set; } /// <summary> /// Runspace Id. /// </summary> [Parameter(Position = 0, Mandatory = true, ParameterSetName = CommonRunspaceCommandBase.RunspaceIdParameterSet)] [ValidateNotNullOrEmpty()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public int[] RunspaceId { get; set; } /// <summary> /// RunspaceInstanceId. /// </summary> [Parameter(Position = 0, Mandatory = true, ParameterSetName = CommonRunspaceCommandBase.RunspaceInstanceIdParameterSet)] [ValidateNotNullOrEmpty()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public System.Guid[] RunspaceInstanceId { get; set; } /// <summary> /// Gets or Sets the ProcessName for which runspace debugging has to be enabled or disabled. /// </summary> [Parameter(Position = 0, ParameterSetName = CommonRunspaceCommandBase.ProcessNameParameterSet)] [ValidateNotNullOrEmpty()] public string ProcessName { get; set; } /// <summary> /// Gets or Sets the AppDomain Names for which runspace debugging has to be enabled or disabled. /// </summary> [Parameter(Position = 1, ParameterSetName = CommonRunspaceCommandBase.ProcessNameParameterSet)] [ValidateNotNullOrEmpty()] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", Target = "Microsoft.PowerShell.Commands.CommonRunspaceCommandBase.#AppDomainName")] public string[] AppDomainName { get; set; } #endregion #region Protected Methods /// <summary> /// Returns a list of valid runspaces based on current parameter set. /// </summary> /// <returns>IReadOnlyList.</returns> protected IReadOnlyList<Runspace> GetRunspaces() { IReadOnlyList<Runspace> results = null; if ((ParameterSetName == CommonRunspaceCommandBase.RunspaceNameParameterSet) && ((RunspaceName == null) || RunspaceName.Length == 0)) { results = GetRunspaceUtils.GetAllRunspaces(); } else { switch (ParameterSetName) { case CommonRunspaceCommandBase.RunspaceNameParameterSet: results = GetRunspaceUtils.GetRunspacesByName(RunspaceName); break; case CommonRunspaceCommandBase.RunspaceIdParameterSet: results = GetRunspaceUtils.GetRunspacesById(RunspaceId); break; case CommonRunspaceCommandBase.RunspaceParameterSet: results = new ReadOnlyCollection<Runspace>(new List<Runspace>(Runspace)); break; case CommonRunspaceCommandBase.RunspaceInstanceIdParameterSet: results = GetRunspaceUtils.GetRunspacesByInstanceId(RunspaceInstanceId); break; } } return results; } /// <summary> /// Returns Runspace Debugger. /// </summary> /// <param name="runspace">Runspace.</param> /// <returns>Debugger.</returns> protected System.Management.Automation.Debugger GetDebuggerFromRunspace(Runspace runspace) { System.Management.Automation.Debugger debugger = null; try { debugger = runspace.Debugger; } catch (PSInvalidOperationException) { } if (debugger == null) { WriteError( new ErrorRecord( new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, Debugger.RunspaceOptionNoDebugger, runspace.Name)), "RunspaceDebugOptionNoDebugger", ErrorCategory.InvalidOperation, this) ); } return debugger; } /// <summary> /// SetDebugPreferenceHelper is a helper method used to enable/disable debug preference. /// </summary> /// <param name="processName">Process Name.</param> /// <param name="appDomainName">App Domain Name.</param> /// <param name="enable">Indicates if debug preference has to be enabled or disabled.</param> /// <param name="fullyQualifiedErrorId">FullyQualifiedErrorId to be used on error.</param> protected void SetDebugPreferenceHelper(string processName, string[] appDomainName, bool enable, string fullyQualifiedErrorId) { List<string> appDomainNames = null; if (appDomainName != null) { foreach (string currentAppDomainName in appDomainName) { if (!string.IsNullOrEmpty(currentAppDomainName)) { if (appDomainNames == null) { appDomainNames = new List<string>(); } appDomainNames.Add(currentAppDomainName.ToLowerInvariant()); } } } try { System.Management.Automation.Runspaces.LocalRunspace.SetDebugPreference(processName.ToLowerInvariant(), appDomainNames, enable); } catch (Exception ex) { ErrorRecord errorRecord = new( new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, Debugger.PersistDebugPreferenceFailure, processName), ex), fullyQualifiedErrorId, ErrorCategory.InvalidOperation, this); WriteError(errorRecord); } } #endregion } #endregion #region EnableRunspaceDebugCommand Cmdlet /// <summary> /// This cmdlet enables debugging for selected runspaces in the current or specified process. /// </summary> [Cmdlet(VerbsLifecycle.Enable, "RunspaceDebug", DefaultParameterSetName = CommonRunspaceCommandBase.RunspaceNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096831")] public sealed class EnableRunspaceDebugCommand : CommonRunspaceCommandBase { #region Parameters /// <summary> /// When true this property will cause any running command or script in the Runspace /// to stop in step mode, regardless of whether a debugger is currently attached. The /// script or command will remain stopped until a debugger is attached to debug the /// current stop point. /// </summary> [Parameter(Position = 1, ParameterSetName = CommonRunspaceCommandBase.RunspaceParameterSet)] [Parameter(Position = 1, ParameterSetName = CommonRunspaceCommandBase.RunspaceNameParameterSet)] [Parameter(Position = 1, ParameterSetName = CommonRunspaceCommandBase.RunspaceIdParameterSet)] public SwitchParameter BreakAll { get; set; } #endregion #region Overrides /// <summary> /// Process Record. /// </summary> protected override void ProcessRecord() { if (this.ParameterSetName.Equals(CommonRunspaceCommandBase.ProcessNameParameterSet)) { SetDebugPreferenceHelper(ProcessName, AppDomainName, true, "EnableRunspaceDebugCommandPersistDebugPreferenceFailure"); return; } IReadOnlyList<Runspace> results = GetRunspaces(); foreach (var runspace in results) { if (runspace.RunspaceStateInfo.State != RunspaceState.Opened) { WriteError( new ErrorRecord(new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, Debugger.RunspaceOptionInvalidRunspaceState, runspace.Name)), "SetRunspaceDebugOptionCommandInvalidRunspaceState", ErrorCategory.InvalidOperation, this)); continue; } System.Management.Automation.Debugger debugger = GetDebuggerFromRunspace(runspace); if (debugger == null) { continue; } // Enable debugging by preserving debug stop events. debugger.UnhandledBreakpointMode = UnhandledBreakpointProcessingMode.Wait; if (this.MyInvocation.BoundParameters.ContainsKey(nameof(BreakAll))) { if (BreakAll) { try { debugger.SetDebuggerStepMode(true); } catch (PSInvalidOperationException e) { WriteError( new ErrorRecord( e, "SetRunspaceDebugOptionCommandCannotEnableDebuggerStepping", ErrorCategory.InvalidOperation, this)); } } else { debugger.SetDebuggerStepMode(false); } } } } #endregion } #endregion #region DisableRunspaceDebugCommand Cmdlet /// <summary> /// This cmdlet disables Runspace debugging in selected Runspaces. /// </summary> [Cmdlet(VerbsLifecycle.Disable, "RunspaceDebug", DefaultParameterSetName = CommonRunspaceCommandBase.RunspaceNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096924")] public sealed class DisableRunspaceDebugCommand : CommonRunspaceCommandBase { #region Overrides /// <summary> /// Process Record. /// </summary> protected override void ProcessRecord() { if (this.ParameterSetName.Equals(CommonRunspaceCommandBase.ProcessNameParameterSet)) { SetDebugPreferenceHelper(ProcessName.ToLowerInvariant(), AppDomainName, false, "DisableRunspaceDebugCommandPersistDebugPreferenceFailure"); } else { IReadOnlyList<Runspace> results = GetRunspaces(); foreach (var runspace in results) { if (runspace.RunspaceStateInfo.State != RunspaceState.Opened) { WriteError( new ErrorRecord( new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, Debugger.RunspaceOptionInvalidRunspaceState, runspace.Name)), "SetRunspaceDebugOptionCommandInvalidRunspaceState", ErrorCategory.InvalidOperation, this) ); continue; } System.Management.Automation.Debugger debugger = GetDebuggerFromRunspace(runspace); if (debugger == null) { continue; } debugger.SetDebuggerStepMode(false); debugger.UnhandledBreakpointMode = UnhandledBreakpointProcessingMode.Ignore; } } } #endregion } #endregion #region GetRunspaceDebugCommand Cmdlet /// <summary> /// This cmdlet returns a PSRunspaceDebug object for each found Runspace object. /// </summary> [Cmdlet(VerbsCommon.Get, "RunspaceDebug", DefaultParameterSetName = CommonRunspaceCommandBase.RunspaceNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097015")] [OutputType(typeof(PSRunspaceDebug))] public sealed class GetRunspaceDebugCommand : CommonRunspaceCommandBase { #region Overrides /// <summary> /// Process Record. /// </summary> protected override void ProcessRecord() { IReadOnlyList<Runspace> results = GetRunspaces(); foreach (var runspace in results) { System.Management.Automation.Debugger debugger = GetDebuggerFromRunspace(runspace); if (debugger != null) { WriteObject( new PSRunspaceDebug((debugger.UnhandledBreakpointMode == UnhandledBreakpointProcessingMode.Wait), debugger.IsDebuggerSteppingEnabled, runspace.Name, runspace.Id) ); } } } #endregion } #endregion #region WaitDebuggerCommand Cmdlet /// <summary> /// This cmdlet causes a running script or command to stop in the debugger at the next execution point. /// </summary> [Cmdlet(VerbsLifecycle.Wait, "Debugger", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097035")] public sealed class WaitDebuggerCommand : PSCmdlet { #region Overrides /// <summary> /// EndProcessing. /// </summary> protected override void EndProcessing() { Runspace currentRunspace = this.Context.CurrentRunspace; if (currentRunspace != null && currentRunspace.Debugger != null) { WriteVerbose(string.Format(CultureInfo.InvariantCulture, Debugger.DebugBreakMessage, MyInvocation.ScriptLineNumber, MyInvocation.ScriptName)); currentRunspace.Debugger.Break(); } } #endregion } #endregion }
#if !UNITY_WSA && !UNITY_WP8 using System; using UnityEngine; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading; using PlayFab.SharedModels; #if !DISABLE_PLAYFABCLIENT_API using PlayFab.ClientModels; #endif using PlayFab.Json; namespace PlayFab.Internal { public class PlayFabWebRequest : IPlayFabHttp { private static readonly Queue<Action> ResultQueue = new Queue<Action>(); private static readonly Queue<Action> _tempActions = new Queue<Action>(); private static readonly List<CallRequestContainer> ActiveRequests = new List<CallRequestContainer>(); private static Thread _requestQueueThread; private static readonly object _ThreadLock = new object(); private static readonly TimeSpan ThreadKillTimeout = TimeSpan.FromSeconds(60); private static DateTime _threadKillTime = DateTime.UtcNow + ThreadKillTimeout; // Kill the thread after 1 minute of inactivity private static bool _isApplicationPlaying; private static int _activeCallCount; private static string _unityVersion; private static string _authKey; private static bool _sessionStarted; public bool SessionStarted { get { return _sessionStarted; } set { _sessionStarted = value; } } public string AuthKey { get { return _authKey; } set { _authKey = value; } } public void InitializeHttp() { SetupCertificates(); _isApplicationPlaying = true; _unityVersion = Application.unityVersion; } public void OnDestroy() { _isApplicationPlaying = false; lock (ResultQueue) { ResultQueue.Clear(); } lock (ActiveRequests) { ActiveRequests.Clear(); } lock (_ThreadLock) { _requestQueueThread = null; } } private void SetupCertificates() { // These are performance Optimizations for HttpWebRequests. ServicePointManager.DefaultConnectionLimit = 10; ServicePointManager.Expect100Continue = false; //Support for SSL var rcvc = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); //(sender, cert, chain, ssl) => true ServicePointManager.ServerCertificateValidationCallback = rcvc; } private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; } public void MakeApiCall(CallRequestContainer reqContainer) { reqContainer.HttpState = HttpRequestState.Idle; lock (ActiveRequests) { ActiveRequests.Insert(0, reqContainer); } ActivateThreadWorker(); } private static void ActivateThreadWorker() { lock (_ThreadLock) { if (_requestQueueThread != null) { return; } _requestQueueThread = new Thread(WorkerThreadMainLoop); _requestQueueThread.Start(); } } private static void WorkerThreadMainLoop() { try { bool active; lock (_ThreadLock) { // Kill the thread after 1 minute of inactivity _threadKillTime = DateTime.UtcNow + ThreadKillTimeout; } List<CallRequestContainer> localActiveRequests = new List<CallRequestContainer>(); do { //process active requests lock (ActiveRequests) { localActiveRequests.AddRange(ActiveRequests); ActiveRequests.Clear(); _activeCallCount = localActiveRequests.Count; } var activeCalls = localActiveRequests.Count; for (var i = activeCalls - 1; i >= 0; i--) // We must iterate backwards, because we remove at index i in some cases { switch (localActiveRequests[i].HttpState) { case HttpRequestState.Error: localActiveRequests.RemoveAt(i); break; case HttpRequestState.Idle: Post(localActiveRequests[i]); break; case HttpRequestState.Sent: if (localActiveRequests[i].HttpRequest.HaveResponse) // Else we'll try again next tick ProcessHttpResponse(localActiveRequests[i]); break; case HttpRequestState.Received: ProcessJsonResponse(localActiveRequests[i]); localActiveRequests.RemoveAt(i); break; } } #region Expire Thread. // Check if we've been inactive lock (_ThreadLock) { var now = DateTime.UtcNow; if (activeCalls > 0 && _isApplicationPlaying) { // Still active, reset the _threadKillTime _threadKillTime = now + ThreadKillTimeout; } // Kill the thread after 1 minute of inactivity active = now <= _threadKillTime; if (!active) { _requestQueueThread = null; } // This thread will be stopped, so null this now, inside lock (_threadLock) } #endregion Thread.Sleep(1); } while (active); } catch (Exception e) { Debug.LogException(e); _requestQueueThread = null; } } private static void Post(CallRequestContainer reqContainer) { try { reqContainer.HttpRequest = (HttpWebRequest)WebRequest.Create(reqContainer.FullUrl); reqContainer.HttpRequest.UserAgent = "UnityEngine-Unity; Version: " + _unityVersion; reqContainer.HttpRequest.SendChunked = false; // Prevents hitting a proxy if no proxy is available. TODO: Add support for proxy's. reqContainer.HttpRequest.Proxy = null; foreach (var pair in reqContainer.RequestHeaders) reqContainer.HttpRequest.Headers.Add(pair.Key, pair.Value); reqContainer.HttpRequest.ContentType = "application/json"; reqContainer.HttpRequest.Method = "POST"; reqContainer.HttpRequest.KeepAlive = PlayFabSettings.RequestKeepAlive; reqContainer.HttpRequest.Timeout = PlayFabSettings.RequestTimeout; reqContainer.HttpRequest.AllowWriteStreamBuffering = false; reqContainer.HttpRequest.Proxy = null; reqContainer.HttpRequest.ContentLength = reqContainer.Payload.LongLength; reqContainer.HttpRequest.ReadWriteTimeout = PlayFabSettings.RequestTimeout; //Debug.Log("Get Stream"); // Get Request Stream and send data in the body. using (var stream = reqContainer.HttpRequest.GetRequestStream()) { //Debug.Log("Post Stream"); stream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length); //Debug.Log("After Post stream"); } reqContainer.HttpState = HttpRequestState.Sent; } catch (WebException e) { reqContainer.JsonResponse = ResponseToString(e.Response) ?? e.Status + ": WebException making http request to: " + reqContainer.FullUrl; var enhancedError = new WebException(reqContainer.JsonResponse, e); Debug.LogException(enhancedError); QueueRequestError(reqContainer); } catch (Exception e) { reqContainer.JsonResponse = "Unhandled exception in Post : " + reqContainer.FullUrl; var enhancedError = new Exception(reqContainer.JsonResponse, e); Debug.LogException(enhancedError); QueueRequestError(reqContainer); } } private static void ProcessHttpResponse(CallRequestContainer reqContainer) { try { #if PLAYFAB_REQUEST_TIMING reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds; #endif // Get and check the response var httpResponse = (HttpWebResponse)reqContainer.HttpRequest.GetResponse(); if (httpResponse.StatusCode == HttpStatusCode.OK) { reqContainer.JsonResponse = ResponseToString(httpResponse); } if (httpResponse.StatusCode != HttpStatusCode.OK || string.IsNullOrEmpty(reqContainer.JsonResponse)) { reqContainer.JsonResponse = reqContainer.JsonResponse ?? "No response from server"; QueueRequestError(reqContainer); return; } else { // Response Recieved Successfully, now process. } reqContainer.HttpState = HttpRequestState.Received; } catch (Exception e) { var msg = "Unhandled exception in ProcessHttpResponse : " + reqContainer.FullUrl; reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg; var enhancedError = new Exception(msg, e); Debug.LogException(enhancedError); QueueRequestError(reqContainer); } } /// <summary> /// Set the reqContainer into an error state, and queue it to invoke the ErrorCallback for that request /// </summary> private static void QueueRequestError(CallRequestContainer reqContainer) { reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.JsonResponse, reqContainer.CustomData); // Decode the server-json error reqContainer.HttpState = HttpRequestState.Error; lock (ResultQueue) { //Queue The result callbacks to run on the main thread. ResultQueue.Enqueue(() => { PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error); if (reqContainer.ErrorCallback != null) reqContainer.ErrorCallback(reqContainer.Error); }); } } private static void ProcessJsonResponse(CallRequestContainer reqContainer) { try { var httpResult = JsonWrapper.DeserializeObject<HttpResponseObject>(reqContainer.JsonResponse); #if PLAYFAB_REQUEST_TIMING reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds; #endif //This would happen if playfab returned a 500 internal server error or a bad json response. if (httpResult == null || httpResult.code != 200) { QueueRequestError(reqContainer); return; } reqContainer.JsonResponse = JsonWrapper.SerializeObject(httpResult.data); reqContainer.DeserializeResultJson(); // Assigns Result with a properly typed object reqContainer.ApiResult.Request = reqContainer.ApiRequest; reqContainer.ApiResult.CustomData = reqContainer.CustomData; #if !DISABLE_PLAYFABCLIENT_API var res = reqContainer.ApiResult as ClientModels.LoginResult; var regRes = reqContainer.ApiResult as ClientModels.RegisterPlayFabUserResult; if (res != null) _authKey = res.SessionTicket; else if (regRes != null) _authKey = regRes.SessionTicket; if (res != null || regRes != null) { lock (ResultQueue) { ResultQueue.Enqueue(() => { PlayFabDeviceUtil.OnPlayFabLogin(res, regRes); }); } } #endif lock (ResultQueue) { //Queue The result callbacks to run on the main thread. ResultQueue.Enqueue(() => { #if PLAYFAB_REQUEST_TIMING reqContainer.Stopwatch.Stop(); reqContainer.Timing.MainThreadRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds; PlayFabHttp.SendRequestTiming(reqContainer.Timing); #endif try { PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post); reqContainer.InvokeSuccessCallback(); } catch (Exception e) { Debug.LogException(e); // Log the user's callback exception back to them without halting PlayFabHttp } }); } } catch (Exception e) { var msg = "Unhandled exception in ProcessJsonResponse : " + reqContainer.FullUrl; reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg; var enhancedError = new Exception(msg, e); Debug.LogException(enhancedError); QueueRequestError(reqContainer); } } public void Update() { lock (ResultQueue) { while (ResultQueue.Count > 0) { var actionToQueue = ResultQueue.Dequeue(); _tempActions.Enqueue(actionToQueue); } } while (_tempActions.Count > 0) { var finishedRequest = _tempActions.Dequeue(); finishedRequest(); } } private static string ResponseToString(WebResponse webResponse) { if (webResponse == null) return null; try { using (var responseStream = webResponse.GetResponseStream()) { if (responseStream == null) return null; using (var stream = new StreamReader(responseStream)) { return stream.ReadToEnd(); } } } catch (WebException webException) { try { using (var responseStream = webException.Response.GetResponseStream()) { if (responseStream == null) return null; using (var stream = new StreamReader(responseStream)) { return stream.ReadToEnd(); } } } catch (Exception e) { Debug.LogException(e); return null; } } catch (Exception e) { Debug.LogException(e); return null; } } public int GetPendingMessages() { var count = 0; lock (ActiveRequests) count += ActiveRequests.Count + _activeCallCount; lock (ResultQueue) count += ResultQueue.Count; return count; } } } #endif
#region License /* * Copyright (C) 2002-2009 the original author or 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. */ #endregion using System; using System.Collections.Generic; using System.Threading; using Java.Util.Concurrent.Atomic; namespace Java.Util.Concurrent { //TODO PHASED correct the link to Spring.Threading.Execution.IScheduledExecutorService /// <summary> /// Factory and utility methods for <see cref="IExecutor"/>, /// <see cref="IExecutorService"/>, /// <see cref="T:Spring.Threading.Execution.IScheduledExecutorService"/>, /// <see cref="IThreadFactory"/>, and <see cref="ICallable{T}"/> classes /// defined in this package. /// </summary> /// <remarks> /// This class supports the following kinds of /// methods: /// <list type="bullet"> /// <item>Methods that create and return an <see cref="IExecutorService"/> /// set up with commonly useful configuration settings.</item> /// <item>Methods that create and return a <see cref="T:Spring.Threading.Execution.IScheduledExecutorService"/> /// set up with commonly useful configuration settings.</item> /// <item>Methods that create and return a "wrapped" /// <see cref="IExecutorService"/>, that disables reconfiguration by /// making implementation-specific methods inaccessible.</item> /// <item>Methods that create and return a <see cref="IThreadFactory"/> /// that sets newly created threads to a known state.</item> /// <item>Methods that create and return a <see cref="ICallable{T}"/> /// out of other closure-like forms, so they can be used /// in execution methods requiring <see cref="ICallable{T}"/>.</item> /// </list> /// </remarks> /// <author>Doug Lea</author> /// <author>Griffin Caprio (.NET)</author> /// <author>Kenneth Xu</author> public static class Executors //JDK_1_6 { #region Public Static Methods /// <summary> /// Creates a thread pool that reuses a fixed number of threads /// operating off a shared unbounded queue. /// </summary> /// <remarks> /// At any point, at most /// <paramref name="threadPoolSize"/> threads will be active processing tasks. If /// additional tasks are submitted when all threads are active, /// they will wait in the queue until a thread is available. If /// any thread terminates due to a failure during execution prior /// to shutdown, a new one will take its place if needed to execute /// subsequent tasks. /// </remarks> /// <param name="threadPoolSize">the number of threads in the pool</param> /// <returns> the newly created thread pool</returns> public static IExecutorService NewFixedThreadPool(int threadPoolSize) { CheckPoolSize(threadPoolSize); return new ThreadPoolExecutor(threadPoolSize, threadPoolSize, TimeSpan.Zero, new LinkedBlockingQueue<IRunnable>()); } /// <summary> /// Creates a thread pool that reuses a fixed number of threads /// operating off a shared unbounded queue, using the provided /// <see cref="Spring.Threading.IThreadFactory"/> to create new threads when needed. /// </summary> /// <remarks> /// At any point, at most <paramref name="threadPoolSize"/> threads will be active processing /// tasks. If additional tasks are submitted when all threads are /// active, they will wait in the queue until a thread is /// available. If any thread terminates due to a failure during /// execution prior to shutdown, a new one will take its place if /// needed to execute subsequent tasks. /// </remarks> /// <param name="threadPoolSize">the number of threads in the pool</param> /// <param name="threadFactory">the factory to use when creating new threads</param> /// <returns> the newly created thread pool /// </returns> public static IExecutorService NewFixedThreadPool(int threadPoolSize, IThreadFactory threadFactory) { CheckPoolSize(threadPoolSize); return new ThreadPoolExecutor(threadPoolSize, threadPoolSize, TimeSpan.Zero, new LinkedBlockingQueue<IRunnable>(), threadFactory); } private static void CheckPoolSize(int threadPoolSize) { if(threadPoolSize <= 0) { throw new ArgumentOutOfRangeException( nameof(threadPoolSize), threadPoolSize, "thread pool size must be greater than zero"); } } /// <summary> /// Creates an <see cref="Spring.Threading.IExecutor"/> that uses a single worker thread operating /// off an unbounded queue. /// </summary> /// <remarks> /// <b>Note:</b> however that if this single /// thread terminates due to a failure during execution prior to /// shutdown, a new one will take its place if needed to execute /// subsequent tasks. Tasks are guaranteed to execute /// sequentially, and no more than one task will be active at any /// given time. Unlike the otherwise equivalent <see cref="Spring.Threading.Execution.Executors.NewFixedThreadPool(int)"/>, /// the returned executor is guaranteed not to be reconfigurable to use additional threads. /// </remarks> /// <returns> the newly created single-threaded <see cref="Spring.Threading.IExecutor"/> </returns> public static IExecutorService NewSingleThreadExecutor() { return new FinalizableDelegatedExecutorService( new ThreadPoolExecutor(1, 1, TimeSpan.Zero, new LinkedBlockingQueue<IRunnable>())); } /// <summary> /// Creates an <see cref="Spring.Threading.IExecutor"/> that uses a single worker thread operating /// off an unbounded queue, and uses the provided <see cref="Spring.Threading.IThreadFactory"/> to /// create a new thread when needed. /// </summary> /// <remarks> /// Unlike the otherwise equivalent <see cref="Spring.Threading.Execution.Executors.NewFixedThreadPool(int, IThreadFactory)"/>, the /// returned executor is guaranteed not to be reconfigurable to use /// additional threads. /// </remarks> /// <param name="threadFactory">the factory to use when creating new threads</param> /// <returns> the newly created single-threaded <see cref="Spring.Threading.IExecutor"/></returns> public static IExecutorService NewSingleThreadExecutor(IThreadFactory threadFactory) { return new FinalizableDelegatedExecutorService( new ThreadPoolExecutor(1, 1, TimeSpan.Zero, new LinkedBlockingQueue<IRunnable>(), threadFactory)); } /// <summary> /// Creates a thread pool that creates new threads as needed, but /// will reuse previously constructed threads when they are /// available. /// </summary> /// <remarks> /// These pools will typically improve the performance /// of programs that execute many short-lived asynchronous tasks. /// Calls to <see cref="Spring.Threading.IExecutor.Execute(IRunnable)"/> will reuse previously constructed /// threads if available. If no existing thread is available, a new /// thread will be created and added to the pool. Threads that have /// not been used for sixty seconds are terminated and removed from` /// the cache. Thus, a pool that remains idle for long enough will /// not consume any resources. <b>Note:</b> pools with similar /// properties but different details (for example, timeout parameters) /// may be created using <see cref="Spring.Threading.Execution.ThreadPoolExecutor"/> constructors. /// </remarks> /// <returns>the newly created thread pool</returns> public static IExecutorService NewCachedThreadPool() { return new ThreadPoolExecutor(0, Int32.MaxValue, TimeSpan.FromMinutes(1), new SynchronousQueue<IRunnable>()); } /// <summary> /// Creates a thread pool that creates new threads as needed, but /// will reuse previously constructed threads when they are /// available, and uses the provided <see cref="Spring.Threading.IThreadFactory"/> to create new threads when needed. /// </summary> /// <param name="threadFactory">the factory to use when creating new threads</param> /// <returns> the newly created thread pool</returns> public static IExecutorService NewCachedThreadPool(IThreadFactory threadFactory) { return new ThreadPoolExecutor(0, Int32.MaxValue, TimeSpan.FromMinutes(1), new SynchronousQueue<IRunnable>(), threadFactory); } /// <summary> /// Returns an object that delegates all defined /// <see cref="Spring.Threading.Execution.IExecutorService"/> /// methods to the given executor, but not any /// other methods that might otherwise be accessible using /// casts. /// </summary> /// <remarks> /// This provides a way to safely "freeze" configuration and /// disallow tuning of a given concrete implementation. /// </remarks> /// <param name="executor">the underlying implementation</param> /// <returns> an <see cref="Spring.Threading.Execution.IExecutorService"/> instance</returns> /// <exception cref="System.ArgumentNullException">if <paramref name="executor"/> is null</exception> public static IExecutorService UnconfigurableExecutorService(IExecutorService executor) { if (executor == null) throw new ArgumentNullException(nameof(executor)); return new DelegatedExecutorService(executor); } #if !PHASED /// <summary> /// Creates a single-threaded executor that can schedule commands /// to run after a given delay, or to execute periodically. /// </summary> /// <remarks> /// <b>Note:</b> if this single thread terminates due to a failure during execution prior to /// shutdown, a new one will take its place if needed to execute /// subsequent tasks. Tasks are guaranteed to execute /// sequentially, and no more than one task will be active at any /// given time. Unlike the otherwise equivalent <see cref="Spring.Threading.Execution.Executors.NewScheduledThreadPool(int)"/> /// the returned executor is guaranteed not to be reconfigurable to use additional threads. /// </remarks> /// <returns> the newly created scheduled executor</returns> public static IScheduledExecutorService NewSingleThreadScheduledExecutor<T>() { return new DelegatedScheduledExecutorService(new ScheduledThreadPoolExecutor(1)); } /// <summary> /// Creates a single-threaded executor that can schedule commands /// to run after a given delay, or to execute periodically. /// </summary> /// <remarks> /// Note however that if this single thread terminates due to a failure /// during execution prior to shutdown, a new one will take its /// place if needed to execute subsequent tasks.) Tasks are /// guaranteed to execute sequentially, and no more than one task /// will be active at any given time. Unlike the otherwise /// equivalent <see cref="Spring.Threading.Execution.Executors.NewScheduledThreadPool(int, IThreadFactory)"/> /// the returned executor is guaranteed not to be reconfigurable to /// use additional threads. /// </remarks> /// <param name="threadFactory">the factory to use when creating new threads</param> /// <returns> a newly created scheduled executor</returns> public static IScheduledExecutorService NewSingleThreadScheduledExecutor<T>(IThreadFactory threadFactory) { return new DelegatedScheduledExecutorService(new ScheduledThreadPoolExecutor(1, threadFactory)); } /// <summary> /// Creates a thread pool that can schedule commands to run after a /// given delay, or to execute periodically. /// </summary> /// <param name="corePoolSize">the number of threads to keep in the pool, even if they are idle. /// </param> /// <returns> a newly created scheduled thread pool</returns> public static IScheduledExecutorService NewScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } /// <summary> /// Creates a thread pool that can schedule commands to run after a /// given delay, or to execute periodically and uses the provided <see cref="Spring.Threading.IThreadFactory"/> to /// create a new thread when needed. /// </summary> /// <param name="corePoolSize">the number of threads to keep in the pool, even if they are idle.</param> /// <param name="threadFactory">the factory to use when the executor creates a new thread.</param> /// <returns> a newly created scheduled thread pool</returns> public static IScheduledExecutorService NewScheduledThreadPool(int corePoolSize, IThreadFactory threadFactory) { return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory); } /// <summary> /// Returns an object that delegates all defined <see cref="Spring.Threading.Execution.IScheduledExecutorService"/> /// methods to the given executor, but not any other methods that might otherwise be accessible using /// casts. This provides a way to safely "freeze" configuration and /// disallow tuning of a given concrete implementation. /// </summary> /// <param name="executor">the underlying implementation</param> /// <returns> a <see cref="Spring.Threading.Execution.IScheduledExecutorService"/> instance</returns> /// <exception cref="System.ArgumentNullException">if <paramref name="executor"/> is null</exception> public static IScheduledExecutorService UnconfigurableScheduledExecutorService(IScheduledExecutorService executor) { if (executor == null) throw new ArgumentNullException(nameof(executor)); return new DelegatedScheduledExecutorService(executor); } #endif /// <summary> /// Returns a default thread factory used to create new threads. /// </summary> /// <remarks> /// This factory creates all new threads used by an <see cref="Spring.Threading.IExecutor"/>. /// invoking this <see cref="NewDefaultThreadFactory"/> method. /// New threads have names accessible via <see cref="System.Threading.Thread.Name"/> of /// <i>pool-N-thread-M</i>, where <i>N</i> is the sequence /// number of this factory, and <i>M</i> is the sequence number /// of the thread created by this factory. /// </remarks> /// <returns>a thread factory</returns> public static IThreadFactory NewDefaultThreadFactory() { return new DefaultThreadFactory(); } /// <summary> /// Returns a <see cref="ICallable{T}"/> object that, when /// called, runs the given task and returns <c>null</c>. /// </summary> /// <param name="runnable">the task to run</param> /// <returns> a callable object</returns> /// <exception cref="System.ArgumentNullException">if the task is <c>null</c></exception> public static ICallable<Void> CreateCallable(IRunnable runnable) { return CreateCallable(runnable, default(Void)); } /// <summary> /// Returns a <see cref="ICallable{T}"/> object that, when called, runs /// the given <paramref name="action"/> and returns <c>null</c>. /// </summary> /// <param name="action">The task to run.</param> /// <returns>An <see cref="ICallable{T}"/> object.</returns> /// <exception cref="System.ArgumentNullException"> /// When the <paramref name="action"/> is <c>null</c>. /// </exception> /// <seealso cref="CreateCallable{T}(Action,T)"/> public static ICallable<Void> CreateCallable(Action action) { return CreateCallable(action, default(Void)); } /// <summary> /// Returns a <see cref="ICallable{T}"/> object that, when called, /// runs the given <paramref name="runnable"/> and returns the given /// <paramref name="result"/>. /// </summary> /// <remarks> /// This can be useful when applying methods requiring a /// <see cref="ICallable{T}"/> to an otherwise resultless action. /// </remarks> /// <typeparam name="T">Type of the result.</typeparam> /// <param name="runnable">the task to run</param> /// <param name="result">the result to return</param> /// <returns>An <see cref="ICallable{T}"/> object.</returns> /// <exception cref="System.ArgumentNullException"> /// When the <paramref name="runnable"/> is <c>null</c>. /// </exception> /// <seealso cref="CreateCallable{T}(Action,T)"/> public static ICallable<T> CreateCallable<T>(IRunnable runnable, T result) { return new Callable<T>(CreateCall(runnable, result)); } /// <summary> /// Returns a <see cref="ICallable{T}"/> object that, when called, /// runs the given <paramref name="action"/> and returns the given /// <paramref name="result"/>. /// </summary> /// <remarks> /// This can be useful when applying methods requiring a /// <see cref="ICallable{T}"/> to an otherwise resultless action. /// </remarks> /// <typeparam name="T">Type of the result.</typeparam> /// <param name="action">The task to run.</param> /// <param name="result">The resul to return</param> /// <returns>An <see cref="ICallable{T}"/> object.</returns> /// <exception cref="System.ArgumentNullException"> /// When the <paramref name="action"/> is <c>null</c>. /// </exception> /// <seealso cref="CreateCallable{T}(IRunnable,T)"/> public static ICallable<T> CreateCallable<T>(Action action, T result) { return new Callable<T>(CreateCall(action, result)); } /// <summary> /// Converts a <see cref="Func{T}"/> delegate to an /// <see cref="ICallable{T}"/> object. /// </summary> /// <typeparam name="T"> /// Type of the result to be returned by <paramref name="call"/>. /// </typeparam> /// <param name="call">The <see cref="Func{T}"/></param> delegate. /// <returns>An instance of <see cref="ICallable{T}"/>.</returns> /// <seealso cref="CreateCall{T}(ICallable{T})"/> public static ICallable<T> CreateCallable<T>(Func<T> call) { return new Callable<T>(call); } /// <summary> /// Returns a <see cref="Func{T}"/> delegate that, when called, /// runs the given <paramref name="runnable"/> and returns the given /// <paramref name="result"/>. /// </summary> /// <remarks> /// This can be useful when applying methods requiring a /// <see cref="Func{T}"/> to an otherwise resultless action. /// </remarks> /// <typeparam name="T">Type of the result.</typeparam> /// <param name="runnable">the task to run</param> /// <param name="result">the result to return</param> /// <returns>An <see cref="Func{T}"/> delegate.</returns> /// <exception cref="System.ArgumentNullException"> /// When the <paramref name="runnable"/> is <c>null</c>. /// </exception> /// <seealso cref="CreateCall{T}(Action,T)"/> public static Func<T> CreateCall<T>(IRunnable runnable, T result) { if (runnable == null) throw new ArgumentNullException(nameof(runnable)); return delegate { runnable.Run(); return result; }; } /// <summary> /// Returns a <see cref="Func{T}"/> delegate that, when called, /// runs the given <paramref name="action"/> and returns the given /// <paramref name="result"/>. /// </summary> /// <remarks> /// This can be useful when applying methods requiring a /// <see cref="Func{T}"/> to an otherwise resultless action. /// </remarks> /// <typeparam name="T">Type of the result.</typeparam> /// <param name="action">the task to run</param> /// <param name="result">the result to return</param> /// <returns>An <see cref="Func{T}"/> delegate.</returns> /// <exception cref="System.ArgumentNullException"> /// When the <paramref name="action"/> is <c>null</c>. /// </exception> /// <seealso cref="CreateCall{T}(IRunnable,T)"/> public static Func<T> CreateCall<T>(Action action, T result) { if (action == null) throw new ArgumentNullException(nameof(action)); return delegate { action(); return result; }; } /// <summary> /// Converts an <see cref="ICallable{T}"/> object to a /// <see cref="Func{T}"/> delegate. /// </summary> /// <typeparam name="T"> /// Type of the result to be returned by <paramref name="callable"/>. /// </typeparam> /// <param name="callable">The <see cref="ICallable{T}"/></param> object. /// <returns>A <see cref="Func{T}"/> delegate.</returns> public static Func<T> CreateCall<T>(ICallable<T> callable) { if (callable == null) throw new ArgumentNullException(nameof(callable)); return callable.Call; } /// <summary> /// Converts a <see cref="Action"/> delegate to an /// <see cref="IRunnable"/> object. /// </summary> /// <param name="action">Task to be converted.</param> /// <returns>An <see cref="IRunnable"/> object.</returns> public static IRunnable CreateRunnable(Action action) { return new Runnable(action); } #endregion #region Non-public classes supporting the public methods internal class DefaultThreadFactory : IThreadFactory { internal static readonly AtomicInteger poolNumber = new AtomicInteger(1); internal AtomicInteger threadNumber = new AtomicInteger(1); internal String namePrefix; internal DefaultThreadFactory() { namePrefix = "pool-" + poolNumber.GetAndIncrement() + "-thread-"; } public virtual Thread NewThread(IRunnable r) { Thread t = new Thread(r.Run); t.Name = namePrefix + threadNumber.GetAndIncrement(); if (t.IsBackground) t.IsBackground = false; if (t.Priority != ThreadPriority.Normal) { t.Priority = ThreadPriority.Normal; } return t; } } internal class DelegatedExecutorService : IExecutorService { private readonly IExecutorService _executorService; internal DelegatedExecutorService(IExecutorService executor) { _executorService = executor; } public virtual bool IsShutdown { get { return _executorService.IsShutdown; } } public virtual bool IsTerminated { get { return _executorService.IsTerminated; } } public virtual void Execute(IRunnable command) { _executorService.Execute(command); } public virtual void Execute(Action action) { _executorService.Execute(action); } public virtual void Dispose() { _executorService.Dispose(); } public virtual void Shutdown() { _executorService.Shutdown(); } public virtual IList<IRunnable> ShutdownNow() { return _executorService.ShutdownNow(); } public virtual bool AwaitTermination(TimeSpan duration) { return _executorService.AwaitTermination(duration); } public virtual IFuture<Void> Submit(IRunnable task) { return _executorService.Submit(task); } public virtual IFuture<T> Submit<T>(ICallable<T> task) { return _executorService.Submit(task); } public virtual IFuture<T> Submit<T>(IRunnable task, T result) { return _executorService.Submit(task, result); } public virtual IFuture<T> Submit<T>(Func<T> call) { return _executorService.Submit(call); } public virtual IFuture<T> Submit<T>(Action action, T result) { return _executorService.Submit(action, result); } public virtual IFuture<Void> Submit(Action action) { return _executorService.Submit(action); } public virtual IList<IFuture<T>> InvokeAll<T>(IEnumerable<Func<T>> tasks) { return _executorService.InvokeAll(tasks); } public virtual IList<IFuture<T>> InvokeAll<T>(TimeSpan durationToWait, IEnumerable<Func<T>> tasks) { return _executorService.InvokeAll(durationToWait, tasks); } public virtual IList<IFuture<T>> InvokeAll<T>(IEnumerable<ICallable<T>> tasks) { return _executorService.InvokeAll(tasks); } public virtual IList<IFuture<T>> InvokeAll<T>(TimeSpan durationToWait, IEnumerable<ICallable<T>> tasks) { return _executorService.InvokeAll(durationToWait, tasks); } public virtual T InvokeAny<T>(IEnumerable<Func<T>> tasks) { return _executorService.InvokeAny(tasks); } public virtual T InvokeAny<T>(TimeSpan durationToWait, IEnumerable<Func<T>> tasks) { return _executorService.InvokeAny(durationToWait, tasks); } public virtual T InvokeAny<T>(IEnumerable<ICallable<T>> tasks) { return _executorService.InvokeAny(tasks); } public virtual T InvokeAny<T>(TimeSpan durationToWait, IEnumerable<ICallable<T>> tasks) { return _executorService.InvokeAny(durationToWait, tasks); } public virtual IList<IFuture<T>> InvokeAll<T>(params ICallable<T>[] tasks) { return _executorService.InvokeAll(tasks); } public virtual IList<IFuture<T>> InvokeAll<T>(params Func<T>[] tasks) { return _executorService.InvokeAll(tasks); } public virtual IList<IFuture<T>> InvokeAll<T>(TimeSpan durationToWait, params ICallable<T>[] tasks) { return _executorService.InvokeAll(durationToWait, tasks); } public virtual IList<IFuture<T>> InvokeAll<T>(TimeSpan durationToWait, params Func<T>[] tasks) { return _executorService.InvokeAll(durationToWait, tasks); } public virtual IList<IFuture<T>> InvokeAllOrFail<T>(IEnumerable<ICallable<T>> tasks) { return _executorService.InvokeAllOrFail(tasks); } public virtual IList<IFuture<T>> InvokeAllOrFail<T>(params ICallable<T>[] tasks) { return _executorService.InvokeAllOrFail(tasks); } public virtual IList<IFuture<T>> InvokeAllOrFail<T>(IEnumerable<Func<T>> tasks) { return _executorService.InvokeAllOrFail(tasks); } public virtual IList<IFuture<T>> InvokeAllOrFail<T>(params Func<T>[] tasks) { return _executorService.InvokeAllOrFail(tasks); } public virtual IList<IFuture<T>> InvokeAllOrFail<T>(TimeSpan durationToWait, IEnumerable<ICallable<T>> tasks) { return _executorService.InvokeAllOrFail(durationToWait, tasks); } public virtual IList<IFuture<T>> InvokeAllOrFail<T>(TimeSpan durationToWait, params ICallable<T>[] tasks) { return _executorService.InvokeAllOrFail(durationToWait, tasks); } public virtual IList<IFuture<T>> InvokeAllOrFail<T>(TimeSpan durationToWait, IEnumerable<Func<T>> tasks) { return _executorService.InvokeAllOrFail(durationToWait, tasks); } public virtual IList<IFuture<T>> InvokeAllOrFail<T>(TimeSpan durationToWait, params Func<T>[] tasks) { return _executorService.InvokeAllOrFail(durationToWait, tasks); } public virtual T InvokeAny<T>(params ICallable<T>[] tasks) { return _executorService.InvokeAny(tasks); } public virtual T InvokeAny<T>(params Func<T>[] tasks) { return _executorService.InvokeAny(tasks); } public virtual T InvokeAny<T>(TimeSpan durationToWait, params ICallable<T>[] tasks) { return _executorService.InvokeAny(durationToWait, tasks); } public virtual T InvokeAny<T>(TimeSpan durationToWait, params Func<T>[] tasks) { return _executorService.InvokeAny(durationToWait, tasks); } } internal class FinalizableDelegatedExecutorService : DelegatedExecutorService { internal FinalizableDelegatedExecutorService(IExecutorService executor) : base(executor) { } ~FinalizableDelegatedExecutorService() { base.Shutdown(); } } #if !PHASED /// <summary> A wrapper class that exposes only the <see cref="Spring.Threading.Execution.IExecutorService"/> and /// <see cref="Spring.Threading.Execution.IScheduledExecutorService"/> methods of a <see cref="Spring.Threading.Execution.IScheduledExecutorService"/> implementation. /// </summary> internal class DelegatedScheduledExecutorService : DelegatedExecutorService, IScheduledExecutorService { private readonly IScheduledExecutorService e; internal DelegatedScheduledExecutorService(IScheduledExecutorService executor) : base(executor) { e = executor; } public virtual IScheduledFuture<Void> Schedule(IRunnable command, TimeSpan delay) { return e.Schedule(command, delay); } public virtual IScheduledFuture<T> Schedule<T>(ICallable<T> callable, TimeSpan delay) { return e.Schedule(callable, delay); } public virtual IScheduledFuture<Void> ScheduleAtFixedRate(IRunnable command, TimeSpan initialDelay, TimeSpan period) { return e.ScheduleAtFixedRate(command, initialDelay, period); } public virtual IScheduledFuture<Void> ScheduleWithFixedDelay(IRunnable command, TimeSpan initialDelay, TimeSpan delay) { return e.ScheduleWithFixedDelay(command, initialDelay, delay); } } #endif #endregion } }
using System; using System.Collections.Specialized; using Eto.Forms; using System.Collections.Generic; using System.Linq; using System.Collections; namespace Eto { /// <summary> /// Class to help implement collection changed events on a data store /// </summary> /// <remarks> /// This is used for the platform handler of controls that use collections. /// This class helps detect changes to a collection so that the appropriate action /// can be taken to update the UI with the changes. /// /// This is a simple helper that is much easier to implement than handling /// the <see cref="INotifyCollectionChanged.CollectionChanged"/> event directly. /// </remarks> /// <typeparam name="TItem">Type of the items in the collection</typeparam> /// <typeparam name="TCollection">Type of the collection</typeparam> public abstract class CollectionChangedHandler<TItem, TCollection> where TCollection: class { /// <summary> /// Gets the collection that this handler is observing /// </summary> public TCollection Collection { get; protected set; } /// <summary> /// Called when the object has been registered (attached) to a collection /// </summary> protected virtual void OnRegisterCollection(EventArgs e) { } /// <summary> /// Called when the object has unregistered the collection /// </summary> protected virtual void OnUnregisterCollection(EventArgs e) { RemoveAllItems(); } /// <summary> /// Registers a specific collection to observe /// </summary> /// <param name="collection">collection to observe</param> /// <returns>true if the collection was registered, false otherwise</returns> public virtual bool Register(TCollection collection) { if (Collection != null) Unregister(); Collection = collection; var notify = Collection as INotifyCollectionChanged; if (notify != null) { notify.CollectionChanged += CollectionChanged; } OnRegisterCollection(EventArgs.Empty); return notify != null; } /// <summary> /// Unregisters the current registered collection /// </summary> public virtual void Unregister() { if (Collection == null) return; var notify = Collection as INotifyCollectionChanged; if (notify != null) { notify.CollectionChanged -= CollectionChanged; } OnUnregisterCollection(EventArgs.Empty); Collection = null; } /// <summary> /// Gets the index of the specified item /// </summary> /// <param name="item">Item to find the index of</param> /// <returns>Index of the item if contained in the collection, otherwise -1</returns> public virtual int IndexOf(TItem item) { var list = Collection as IList<TItem>; if (list != null) return list.IndexOf(item); return InternalIndexOf(item); } /// <summary> /// Gets the element at the specified index of the current registered collection. /// </summary> /// <returns>The item at the specified index.</returns> /// <param name="index">Index of the item to get.</param> public virtual TItem ElementAt(int index) { var list = Collection as IList<TItem>; if (list != null) return list[index]; return InternalElementAt(index); } /// <summary> /// Gets the count of the items in the current registered collection. /// </summary> /// <value>The count of items.</value> public abstract int Count { get; } /// <summary> /// Gets the index of the item from the collection /// </summary> /// <remarks> /// Derived classes should implement this to get the index of the item. /// </remarks> /// <param name="item">Item to find the index</param> /// <returns>index of the item in the collection, or -1 if the item is not found</returns> protected abstract int InternalIndexOf(TItem item); /// <summary> /// Gets the element at the specified index. /// </summary> /// <remarks> /// Derived classes should implement this to get the item at the specified index. /// </remarks> /// <returns>The item at the specified index.</returns> /// <param name="index">Index of the item to get.</param> protected abstract TItem InternalElementAt(int index); /// <summary> /// Adds the item to the end of the collection /// </summary> /// <param name="item">Item to add to the collection</param> public abstract void AddItem(TItem item); /// <summary> /// Inserts an item at the specified index in the collection /// </summary> /// <param name="index">Index to insert the item to</param> /// <param name="item">Item to insert</param> public abstract void InsertItem(int index, TItem item); /// <summary> /// Removes the item at the specified index /// </summary> /// <param name="index">Index of the item to remove</param> public abstract void RemoveItem(int index); /// <summary> /// Removes all items from the collection /// </summary> public abstract void RemoveAllItems(); /// <summary> /// Removes the specified item /// </summary> /// <remarks> /// This will remove the item by finding the index and removing based on index. /// Implementors should override this method if there is a faster mechanism to do so. /// </remarks> /// <param name="item">Item to remove from the collection</param> public virtual void RemoveItem(TItem item) { var index = IndexOf(item); if (index >= 0) RemoveItem(index); } /// <summary> /// Adds multiple items to the end of the collection /// </summary> /// <remarks> /// This simply calls <see cref="AddItem"/> for each item in the list. If there /// is a faster mechanism for doing so, implementors should override this method. /// /// For example, sometimes adding a single item will update the UI for each item, this /// should be overridden so the UI is updated after all items have been added. /// </remarks> /// <param name="items">Enumeration of items to add to the end of the collection</param> public virtual void AddRange(IEnumerable<TItem> items) { foreach (var item in items) AddItem(item); } /// <summary> /// Inserts multiple items to the specified index in the collection /// </summary> /// <remarks> /// This simply calls <see cref="InsertItem"/> for each item in the list. If there /// is a faster mechanism for doing so, implementors should override this method. /// /// For example, sometimes inserting a single item will update the UI for each item, this /// should be overridden so the UI is updated after all items have been inserted. /// </remarks> /// <param name="index">Index to start adding the items</param> /// <param name="items">Enumeration of items to add</param> public virtual void InsertRange(int index, IEnumerable<TItem> items) { foreach (var item in items) InsertItem(index++, item); } /// <summary> /// Removes a specified count of items from the collection starting at the specified index /// </summary> /// <remarks> /// This simply calls <see cref="RemoveItem(int)"/> for each item to remove. If there /// is a faster mechanism for doing so, implementors should override this method. /// /// For example, sometimes removing a single item will update the UI for each item, this /// should be overridden so the UI is updated after all items have been removed. /// </remarks> /// <param name="index">Index to start removing the items from</param> /// <param name="count">Number of items to remove</param> public virtual void RemoveRange(int index, int count) { for (int i = 0; i < count; i++) RemoveItem(index); } /// <summary> /// Removes the specified items from the collection /// </summary> /// <remarks> /// This simply calls <see cref="RemoveItem(TItem)"/> for each item to remove. If there /// is a faster mechanism for doing so, implementors should override this method. /// /// For example, sometimes removing a single item will update the UI for each item, this /// should be overridden so the UI is updated after all items have been removed. /// </remarks> /// <param name="items">List of items to remove</param> public virtual void RemoveRange(IEnumerable<TItem> items) { foreach (var item in items) RemoveItem(item); } void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: if (e.NewStartingIndex != -1) { if (e.NewItems.Count == 1) InsertItem(e.NewStartingIndex, (TItem)e.NewItems[0]); else InsertRange(e.NewStartingIndex, e.NewItems.Cast<TItem>()); } else AddRange(e.NewItems.Cast<TItem>()); break; case NotifyCollectionChangedAction.Move: if (e.OldStartingIndex != -1) RemoveRange(e.OldStartingIndex, e.OldItems.Count); else RemoveRange(e.OldItems.Cast<TItem>()); InsertRange(e.NewStartingIndex, e.NewItems.Cast<TItem>()); break; case NotifyCollectionChangedAction.Remove: if (e.OldStartingIndex != -1) { if (e.OldItems.Count == 1) RemoveItem(e.OldStartingIndex); else RemoveRange(e.OldStartingIndex, e.OldItems.Count); } else RemoveRange(e.OldItems.Cast<TItem>()); break; case NotifyCollectionChangedAction.Replace: if (e.OldStartingIndex != -1) { RemoveRange(e.OldStartingIndex, e.OldItems.Count); InsertRange(e.OldStartingIndex, e.NewItems.Cast<TItem>()); } else { for (int i = 0; i < e.OldItems.Count; i++) { var index = IndexOf((TItem)e.OldItems[i]); RemoveItem(index); InsertItem(index, (TItem)e.NewItems[i]); } } break; case NotifyCollectionChangedAction.Reset: RemoveAllItems(); break; } } } /// <summary> /// Helper class to handle collection change events of an <see cref="IEnumerable"/> /// </summary> /// <remarks> /// This is used for the platform handler of controls that use collections. /// This class helps detect changes to a collection so that the appropriate action /// can be taken to update the UI with the changes. /// /// Use this class as a base when you only have an <see cref="IEnumerable"/>. If the object /// also implements <see cref="INotifyCollectionChanged"/> it will get changed events /// otherwise you must register a new collection each time. /// </remarks> /// <typeparam name="TItem">Type of each item in the enumerable</typeparam> public abstract class EnumerableChangedHandler<TItem> : EnumerableChangedHandler<TItem, IEnumerable<TItem>> { } /// <summary> /// Helper class to handle collection change events of an <see cref="IEnumerable"/> /// </summary> /// <remarks> /// This is used for the platform handler of controls that use collections. /// This class helps detect changes to a collection so that the appropriate action /// can be taken to update the UI with the changes. /// /// Use this class as a base when you only have an <see cref="IEnumerable"/>. If the object /// also implements <see cref="INotifyCollectionChanged"/> it will get changed events /// otherwise you must register a new collection each time. /// </remarks> /// <typeparam name="TItem">Type of each item in the enumerable</typeparam> /// <typeparam name="TCollection">Type of the collection to handle the change events for</typeparam> public abstract class EnumerableChangedHandler<TItem, TCollection> : CollectionChangedHandler<TItem, TCollection> where TCollection: class, IEnumerable<TItem> { /// <summary> /// Implements the mechanism for finding the index of an item (the slow way) /// </summary> /// <remarks> /// If the collection object implements <see cref="IList"/>, this will not get called /// as it will call it's method of getting the index. This is used as a fallback. /// </remarks> /// <param name="item">Item to find in the collection</param> /// <returns>Index of the item, or -1 if not found</returns> protected override int InternalIndexOf(TItem item) { return Collection.IndexOf(item); } /// <summary> /// Gets the count of the items in the current registered collection. /// </summary> /// <value>The count of items.</value> public override int Count { get { // mono doesn't test for ICollection, causing performance issues var coll = Collection as ICollection; if (coll != null) return coll.Count; return Collection != null ? Collection.Count() : 0; } } /// <summary> /// Gets the element at the specified index. /// </summary> /// <remarks>Derived classes should implement this to get the item at the specified index.</remarks> /// <returns>The item at the specified index.</returns> /// <param name="index">Index of the item to get.</param> protected override TItem InternalElementAt(int index) { var list = Collection as IList<TItem>; if (list != null) return (TItem)list[index]; var list2 = Collection as IList; if (list2 != null) return (TItem)list2[index]; return Collection.ElementAt(index); } /// <summary> /// Called when the collection is registered /// </summary> protected override void OnRegisterCollection(EventArgs e) { base.OnRegisterCollection(e); InitializeCollection(); } /// <summary> /// Initializes the collection, usually by adding the collection to the underlying handler. /// </summary> protected virtual void InitializeCollection() { if (Collection != null) AddRange(Collection); } } /// <summary> /// Class to help implement change handling for a <see cref="IDataStore{T}"/> /// </summary> /// <remarks> /// This is used for the platform handler of controls that use collections. /// This class helps detect changes to a collection so that the appropriate action /// can be taken to update the UI with the changes. /// /// Use this class as a base when you are detecting changes for an <see cref="IDataStore{T}"/>. /// If the object also implements <see cref="INotifyCollectionChanged"/>, it will get changed events. /// Otherwise, you must register a new collection each time. /// </remarks> /// <typeparam name="TItem">Type of items in the data store</typeparam> /// <typeparam name="TCollection">Type of the data store to detect changes on</typeparam> public abstract class DataStoreChangedHandler<TItem, TCollection> : CollectionChangedHandler<TItem, TCollection>, IEnumerable<TItem> where TCollection: class, IDataStore<TItem> { /// <summary> /// Gets the enumerator. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<TItem> GetEnumerator() { return new DataStoreVirtualCollection<TItem>(Collection).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Called when the collection is registered /// </summary> protected override void OnRegisterCollection(EventArgs e) { base.OnRegisterCollection(e); AddRange(this); } /// <summary> /// Implements the mechanism for finding the index of an item (the slow way) /// </summary> /// <remarks> /// If the collection object implements <see cref="IList"/>, this will not get called /// as it will call it's method of getting the index. This is used as a fallback. /// </remarks> /// <param name="item">Item to find in the collection</param> /// <returns>Index of the item, or -1 if not found</returns> protected override int InternalIndexOf(TItem item) { for (int i = 0; i < Collection.Count; i++) { if (object.ReferenceEquals(item, Collection[i])) return i; } return -1; } /// <summary> /// Gets the count of the items in the current registered collection. /// </summary> /// <value>The count of items.</value> public override int Count { get { return Collection.Count; } } /// <summary> /// Gets the element at the specified index. /// </summary> /// <remarks>Derived classes should implement this to get the item at the specified index.</remarks> /// <returns>The item at the specified index.</returns> /// <param name="index">Index of the item to get.</param> protected override TItem InternalElementAt(int index) { return Collection[index]; } } }
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 memory_game.Areas.HelpPage.Models; namespace memory_game.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); } } } }
// 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.Reflection; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Reflection.Emit { internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo { #region Private Static Members internal static MethodInfo GetMethod(MethodInfo method, TypeBuilderInstantiation type) { return new MethodOnTypeBuilderInstantiation(method, type); } #endregion #region Private Data Members internal MethodInfo m_method; private TypeBuilderInstantiation m_type; #endregion #region Constructor internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type) { Debug.Assert(method is MethodBuilder || method is RuntimeMethodInfo); m_method = method; m_type = type; } #endregion internal override Type[] GetParameterTypes() { return m_method.GetParameterTypes(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return m_method.MemberType; } } public override String Name { get { return m_method.Name; } } public override Type DeclaringType { get { return m_type; } } public override Type ReflectedType { get { return m_type; } } public override Object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); } public override Module Module { get { return m_method.Module; } } #endregion #region MethodBase Members [Pure] public override ParameterInfo[] GetParameters() { return m_method.GetParameters(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); } public override RuntimeMethodHandle MethodHandle { get { return m_method.MethodHandle; } } public override MethodAttributes Attributes { get { return m_method.Attributes; } } public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { throw new NotSupportedException(); } public override CallingConventions CallingConvention { get { return m_method.CallingConvention; } } public override Type[] GetGenericArguments() { return m_method.GetGenericArguments(); } public override MethodInfo GetGenericMethodDefinition() { return m_method; } public override bool IsGenericMethodDefinition { get { return m_method.IsGenericMethodDefinition; } } public override bool ContainsGenericParameters { get { return m_method.ContainsGenericParameters; } } public override MethodInfo MakeGenericMethod(params Type[] typeArgs) { if (!IsGenericMethodDefinition) throw new InvalidOperationException(SR.Arg_NotGenericMethodDefinition); Contract.EndContractBlock(); return MethodBuilderInstantiation.MakeGenericMethod(this, typeArgs); } public override bool IsGenericMethod { get { return m_method.IsGenericMethod; } } #endregion #region Public Abstract\Virtual Members public override Type ReturnType { get { return m_method.ReturnType; } } public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } } public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); } #endregion } internal sealed class ConstructorOnTypeBuilderInstantiation : ConstructorInfo { #region Private Static Members internal static ConstructorInfo GetConstructor(ConstructorInfo Constructor, TypeBuilderInstantiation type) { return new ConstructorOnTypeBuilderInstantiation(Constructor, type); } #endregion #region Private Data Members internal ConstructorInfo m_ctor; private TypeBuilderInstantiation m_type; #endregion #region Constructor internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type) { Debug.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo); m_ctor = constructor; m_type = type; } #endregion internal override Type[] GetParameterTypes() { return m_ctor.GetParameterTypes(); } internal override Type GetReturnType() { return DeclaringType; } #region MemberInfo Overrides public override MemberTypes MemberType { get { return m_ctor.MemberType; } } public override String Name { get { return m_ctor.Name; } } public override Type DeclaringType { get { return m_type; } } public override Type ReflectedType { get { return m_type; } } public override Object[] GetCustomAttributes(bool inherit) { return m_ctor.GetCustomAttributes(inherit); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_ctor.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_ctor.IsDefined(attributeType, inherit); } internal int MetadataTokenInternal { get { ConstructorBuilder cb = m_ctor as ConstructorBuilder; if (cb != null) return cb.MetadataTokenInternal; else { Debug.Assert(m_ctor is RuntimeConstructorInfo); return m_ctor.MetadataToken; } } } public override Module Module { get { return m_ctor.Module; } } #endregion #region MethodBase Members [Pure] public override ParameterInfo[] GetParameters() { return m_ctor.GetParameters(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_ctor.GetMethodImplementationFlags(); } public override RuntimeMethodHandle MethodHandle { get { return m_ctor.MethodHandle; } } public override MethodAttributes Attributes { get { return m_ctor.Attributes; } } public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { throw new NotSupportedException(); } public override CallingConventions CallingConvention { get { return m_ctor.CallingConvention; } } public override Type[] GetGenericArguments() { return m_ctor.GetGenericArguments(); } public override bool IsGenericMethodDefinition { get { return false; } } public override bool ContainsGenericParameters { get { return false; } } public override bool IsGenericMethod { get { return false; } } #endregion #region ConstructorInfo Members public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { throw new InvalidOperationException(); } #endregion } internal sealed class FieldOnTypeBuilderInstantiation : FieldInfo { #region Private Static Members internal static FieldInfo GetField(FieldInfo Field, TypeBuilderInstantiation type) { FieldInfo m = null; // This ifdef was introduced when non-generic collections were pulled from // silverlight. See code:Dictionary#DictionaryVersusHashtableThreadSafety // for information about this change. // // There is a pre-existing race condition in this code with the side effect // that the second thread's value clobbers the first in the hashtable. This is // an acceptable race condition since we make no guarantees that this will return the // same object. // // We're not entirely sure if this cache helps any specific scenarios, so // long-term, one could investigate whether it's needed. In any case, this // method isn't expected to be on any critical paths for performance. if (type.m_hashtable.Contains(Field)) { m = type.m_hashtable[Field] as FieldInfo; } else { m = new FieldOnTypeBuilderInstantiation(Field, type); type.m_hashtable[Field] = m; } return m; } #endregion #region Private Data Members private FieldInfo m_field; private TypeBuilderInstantiation m_type; #endregion #region Constructor internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type) { Debug.Assert(field is FieldBuilder || field is RuntimeFieldInfo); m_field = field; m_type = type; } #endregion internal FieldInfo FieldInfo { get { return m_field; } } #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } } public override String Name { get { return m_field.Name; } } public override Type DeclaringType { get { return m_type; } } public override Type ReflectedType { get { return m_type; } } public override Object[] GetCustomAttributes(bool inherit) { return m_field.GetCustomAttributes(inherit); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_field.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_field.IsDefined(attributeType, inherit); } internal int MetadataTokenInternal { get { FieldBuilder fb = m_field as FieldBuilder; if (fb != null) return fb.MetadataTokenInternal; else { Debug.Assert(m_field is RuntimeFieldInfo); return m_field.MetadataToken; } } } public override Module Module { get { return m_field.Module; } } #endregion #region Public Abstract\Virtual Members public override Type[] GetRequiredCustomModifiers() { return m_field.GetRequiredCustomModifiers(); } public override Type[] GetOptionalCustomModifiers() { return m_field.GetOptionalCustomModifiers(); } public override void SetValueDirect(TypedReference obj, Object value) { throw new NotImplementedException(); } public override Object GetValueDirect(TypedReference obj) { throw new NotImplementedException(); } public override RuntimeFieldHandle FieldHandle { get { throw new NotImplementedException(); } } public override Type FieldType { get { throw new NotImplementedException(); } } public override Object GetValue(Object obj) { throw new InvalidOperationException(); } public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new InvalidOperationException(); } public override FieldAttributes Attributes { get { return m_field.Attributes; } } #endregion } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; namespace XenAPI { /// <summary> /// Describes the SDN controller that is to connect with the pool /// First published in XenServer 7.2. /// </summary> public partial class SDN_controller : XenObject<SDN_controller> { public SDN_controller() { } public SDN_controller(string uuid, sdn_controller_protocol protocol, string address, long port) { this.uuid = uuid; this.protocol = protocol; this.address = address; this.port = port; } /// <summary> /// Creates a new SDN_controller from a Proxy_SDN_controller. /// </summary> /// <param name="proxy"></param> public SDN_controller(Proxy_SDN_controller proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(SDN_controller update) { uuid = update.uuid; protocol = update.protocol; address = update.address; port = update.port; } internal void UpdateFromProxy(Proxy_SDN_controller proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; protocol = proxy.protocol == null ? (sdn_controller_protocol) 0 : (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), (string)proxy.protocol); address = proxy.address == null ? null : (string)proxy.address; port = proxy.port == null ? 0 : long.Parse((string)proxy.port); } public Proxy_SDN_controller ToProxy() { Proxy_SDN_controller result_ = new Proxy_SDN_controller(); result_.uuid = uuid ?? ""; result_.protocol = sdn_controller_protocol_helper.ToString(protocol); result_.address = address ?? ""; result_.port = port.ToString(); return result_; } /// <summary> /// Creates a new SDN_controller from a Hashtable. /// </summary> /// <param name="table"></param> public SDN_controller(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); protocol = (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), Marshalling.ParseString(table, "protocol")); address = Marshalling.ParseString(table, "address"); port = Marshalling.ParseLong(table, "port"); } public bool DeepEquals(SDN_controller other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._protocol, other._protocol) && Helper.AreEqual2(this._address, other._address) && Helper.AreEqual2(this._port, other._port); } public override string SaveChanges(Session session, string opaqueRef, SDN_controller server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given SDN_controller. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param> public static SDN_controller get_record(Session session, string _sdn_controller) { return new SDN_controller((Proxy_SDN_controller)session.proxy.sdn_controller_get_record(session.uuid, _sdn_controller ?? "").parse()); } /// <summary> /// Get a reference to the SDN_controller instance with the specified UUID. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<SDN_controller> get_by_uuid(Session session, string _uuid) { return XenRef<SDN_controller>.Create(session.proxy.sdn_controller_get_by_uuid(session.uuid, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given SDN_controller. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param> public static string get_uuid(Session session, string _sdn_controller) { return (string)session.proxy.sdn_controller_get_uuid(session.uuid, _sdn_controller ?? "").parse(); } /// <summary> /// Get the protocol field of the given SDN_controller. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param> public static sdn_controller_protocol get_protocol(Session session, string _sdn_controller) { return (sdn_controller_protocol)Helper.EnumParseDefault(typeof(sdn_controller_protocol), (string)session.proxy.sdn_controller_get_protocol(session.uuid, _sdn_controller ?? "").parse()); } /// <summary> /// Get the address field of the given SDN_controller. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param> public static string get_address(Session session, string _sdn_controller) { return (string)session.proxy.sdn_controller_get_address(session.uuid, _sdn_controller ?? "").parse(); } /// <summary> /// Get the port field of the given SDN_controller. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param> public static long get_port(Session session, string _sdn_controller) { return long.Parse((string)session.proxy.sdn_controller_get_port(session.uuid, _sdn_controller ?? "").parse()); } /// <summary> /// Introduce an SDN controller to the pool. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_protocol">Protocol to connect with the controller.</param> /// <param name="_address">IP address of the controller.</param> /// <param name="_port">TCP port of the controller.</param> public static XenRef<SDN_controller> introduce(Session session, sdn_controller_protocol _protocol, string _address, long _port) { return XenRef<SDN_controller>.Create(session.proxy.sdn_controller_introduce(session.uuid, sdn_controller_protocol_helper.ToString(_protocol), _address ?? "", _port.ToString()).parse()); } /// <summary> /// Introduce an SDN controller to the pool. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_protocol">Protocol to connect with the controller.</param> /// <param name="_address">IP address of the controller.</param> /// <param name="_port">TCP port of the controller.</param> public static XenRef<Task> async_introduce(Session session, sdn_controller_protocol _protocol, string _address, long _port) { return XenRef<Task>.Create(session.proxy.async_sdn_controller_introduce(session.uuid, sdn_controller_protocol_helper.ToString(_protocol), _address ?? "", _port.ToString()).parse()); } /// <summary> /// Remove the OVS manager of the pool and destroy the db record. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param> public static void forget(Session session, string _sdn_controller) { session.proxy.sdn_controller_forget(session.uuid, _sdn_controller ?? "").parse(); } /// <summary> /// Remove the OVS manager of the pool and destroy the db record. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_sdn_controller">The opaque_ref of the given sdn_controller</param> public static XenRef<Task> async_forget(Session session, string _sdn_controller) { return XenRef<Task>.Create(session.proxy.async_sdn_controller_forget(session.uuid, _sdn_controller ?? "").parse()); } /// <summary> /// Return a list of all the SDN_controllers known to the system. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> public static List<XenRef<SDN_controller>> get_all(Session session) { return XenRef<SDN_controller>.Create(session.proxy.sdn_controller_get_all(session.uuid).parse()); } /// <summary> /// Get all the SDN_controller Records at once, in a single XML RPC call /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<SDN_controller>, SDN_controller> get_all_records(Session session) { return XenRef<SDN_controller>.Create<Proxy_SDN_controller>(session.proxy.sdn_controller_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// Protocol to connect with SDN controller /// </summary> public virtual sdn_controller_protocol protocol { get { return _protocol; } set { if (!Helper.AreEqual(value, _protocol)) { _protocol = value; Changed = true; NotifyPropertyChanged("protocol"); } } } private sdn_controller_protocol _protocol; /// <summary> /// IP address of the controller /// </summary> public virtual string address { get { return _address; } set { if (!Helper.AreEqual(value, _address)) { _address = value; Changed = true; NotifyPropertyChanged("address"); } } } private string _address; /// <summary> /// TCP port of the controller /// </summary> public virtual long port { get { return _port; } set { if (!Helper.AreEqual(value, _port)) { _port = value; Changed = true; NotifyPropertyChanged("port"); } } } private long _port; } }
// 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.Reflection.Emit { using System; using System.Collections.Generic; using CultureInfo = System.Globalization.CultureInfo; using System.Reflection; using System.Security; using System.Security.Permissions; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; [System.Runtime.InteropServices.ComVisible(true)] public sealed class DynamicMethod : MethodInfo { private RuntimeType[] m_parameterTypes; internal IRuntimeMethodInfo m_methodHandle; private RuntimeType m_returnType; private DynamicILGenerator m_ilGenerator; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif private DynamicILInfo m_DynamicILInfo; private bool m_fInitLocals; private RuntimeModule m_module; internal bool m_skipVisibility; internal RuntimeType m_typeOwner; // can be null // We want the creator of the DynamicMethod to control who has access to the // DynamicMethod (just like we do for delegates). However, a user can get to // the corresponding RTDynamicMethod using Exception.TargetSite, StackFrame.GetMethod, etc. // If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would // not be able to bound access to the DynamicMethod. Hence, we need to ensure that // we do not allow direct use of RTDynamicMethod. private RTDynamicMethod m_dynMethod; // needed to keep the object alive during jitting // assigned by the DynamicResolver ctor internal DynamicResolver m_resolver; // Always false unless we are in an immersive (non dev mode) process. #if FEATURE_APPX private bool m_profileAPICheck; private RuntimeAssembly m_creatorAssembly; #endif internal bool m_restrictedSkipVisibility; // The context when the method was created. We use this to do the RestrictedMemberAccess checks. // These checks are done when the method is compiled. This can happen at an arbitrary time, // when CreateDelegate or Invoke is called, or when another DynamicMethod executes OpCodes.Call. // We capture the creation context so that we can do the checks against the same context, // irrespective of when the method gets compiled. Note that the DynamicMethod does not know when // it is ready for use since there is not API which indictates that IL generation has completed. #if FEATURE_COMPRESSEDSTACK internal CompressedStack m_creationContext; #endif // FEATURE_COMPRESSEDSTACK private static volatile InternalModuleBuilder s_anonymouslyHostedDynamicMethodsModule; private static readonly object s_anonymouslyHostedDynamicMethodsModuleLock = new object(); // // class initialization (ctor and init) // private DynamicMethod() { } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, Type[] parameterTypes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, // owner null, // m false, // skipVisibility true, ref stackMark); // transparentMethod } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, // owner null, // m restrictedSkipVisibility, true, ref stackMark); // transparentMethod } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Module m) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; PerformSecurityCheck(m, ref stackMark, false); Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, // owner m, // m false, // skipVisibility false, ref stackMark); // transparentMethod } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; PerformSecurityCheck(m, ref stackMark, skipVisibility); Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, // owner m, // m skipVisibility, false, ref stackMark); // transparentMethod } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Module m, bool skipVisibility) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; PerformSecurityCheck(m, ref stackMark, skipVisibility); Init(name, attributes, callingConvention, returnType, parameterTypes, null, // owner m, // m skipVisibility, false, ref stackMark); // transparentMethod } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; PerformSecurityCheck(owner, ref stackMark, false); Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, // owner null, // m false, // skipVisibility false, ref stackMark); // transparentMethod } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; PerformSecurityCheck(owner, ref stackMark, skipVisibility); Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, // owner null, // m skipVisibility, false, ref stackMark); // transparentMethod } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; PerformSecurityCheck(owner, ref stackMark, skipVisibility); Init(name, attributes, callingConvention, returnType, parameterTypes, owner, // owner null, // m skipVisibility, false, ref stackMark); // transparentMethod } // helpers for intialization static private void CheckConsistency(MethodAttributes attributes, CallingConventions callingConvention) { // only static public for method attributes if ((attributes & ~MethodAttributes.MemberAccessMask) != MethodAttributes.Static) throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags")); if ((attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags")); Contract.EndContractBlock(); // only standard or varargs supported if (callingConvention != CallingConventions.Standard && callingConvention != CallingConventions.VarArgs) throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags")); // vararg is not supported at the moment if (callingConvention == CallingConventions.VarArgs) throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags")); } // We create a transparent assembly to host DynamicMethods. Since the assembly does not have any // non-public fields (or any fields at all), it is a safe anonymous assembly to host DynamicMethods [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable private static RuntimeModule GetDynamicMethodsModule() { if (s_anonymouslyHostedDynamicMethodsModule != null) return s_anonymouslyHostedDynamicMethodsModule; lock (s_anonymouslyHostedDynamicMethodsModuleLock) { if (s_anonymouslyHostedDynamicMethodsModule != null) return s_anonymouslyHostedDynamicMethodsModule; ConstructorInfo transparencyCtor = typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes); CustomAttributeBuilder transparencyAttribute = new CustomAttributeBuilder(transparencyCtor, EmptyArray<Object>.Value); List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>(); assemblyAttributes.Add(transparencyAttribute); #if !FEATURE_CORECLR // On the desktop, we need to use the security rule set level 1 for anonymously hosted // dynamic methods. In level 2, transparency rules are strictly enforced, which leads to // errors when a fully trusted application causes a dynamic method to be generated that tries // to call a method with a LinkDemand or a SecurityCritical method. To retain compatibility // with the v2.0 and v3.x frameworks, these calls should be allowed. // // If this rule set was not explicitly called out, then the anonymously hosted dynamic methods // assembly would inherit the rule set from the creating assembly - which would cause it to // be level 2 because mscorlib.dll is using the level 2 rules. ConstructorInfo securityRulesCtor = typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) }); CustomAttributeBuilder securityRulesAttribute = new CustomAttributeBuilder(securityRulesCtor, new object[] { SecurityRuleSet.Level1 }); assemblyAttributes.Add(securityRulesAttribute); #endif // !FEATURE_CORECLR AssemblyName assemblyName = new AssemblyName("Anonymously Hosted DynamicMethods Assembly"); StackCrawlMark stackMark = StackCrawlMark.LookForMe; AssemblyBuilder assembly = AssemblyBuilder.InternalDefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Run, null, null, null, null, null, ref stackMark, assemblyAttributes, SecurityContextSource.CurrentAssembly); AppDomain.PublishAnonymouslyHostedDynamicMethodsAssembly(assembly.GetNativeHandle()); // this always gets the internal module. s_anonymouslyHostedDynamicMethodsModule = (InternalModuleBuilder)assembly.ManifestModule; } return s_anonymouslyHostedDynamicMethodsModule; } [System.Security.SecurityCritical] // auto-generated private unsafe void Init(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] signature, Type owner, Module m, bool skipVisibility, bool transparentMethod, ref StackCrawlMark stackMark) { DynamicMethod.CheckConsistency(attributes, callingConvention); // check and store the signature if (signature != null) { m_parameterTypes = new RuntimeType[signature.Length]; for (int i = 0; i < signature.Length; i++) { if (signature[i] == null) throw new ArgumentException(Environment.GetResourceString("Arg_InvalidTypeInSignature")); m_parameterTypes[i] = signature[i].UnderlyingSystemType as RuntimeType; if ( m_parameterTypes[i] == null || !(m_parameterTypes[i] is RuntimeType) || m_parameterTypes[i] == (RuntimeType)typeof(void) ) throw new ArgumentException(Environment.GetResourceString("Arg_InvalidTypeInSignature")); } } else { m_parameterTypes = Array.Empty<RuntimeType>(); } // check and store the return value m_returnType = (returnType == null) ? (RuntimeType)typeof(void) : returnType.UnderlyingSystemType as RuntimeType; if ( (m_returnType == null) || !(m_returnType is RuntimeType) || m_returnType.IsByRef ) throw new NotSupportedException(Environment.GetResourceString("Arg_InvalidTypeInRetType")); if (transparentMethod) { Contract.Assert(owner == null && m == null, "owner and m cannot be set for transparent methods"); m_module = GetDynamicMethodsModule(); if (skipVisibility) { m_restrictedSkipVisibility = true; } #if FEATURE_COMPRESSEDSTACK m_creationContext = CompressedStack.Capture(); #endif // FEATURE_COMPRESSEDSTACK } else { Contract.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set"); Contract.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly"); Contract.Assert(m == null || owner == null, "m and owner cannot both be set"); if (m != null) m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects. else { RuntimeType rtOwner = null; if (owner != null) rtOwner = owner.UnderlyingSystemType as RuntimeType; if (rtOwner != null) { if (rtOwner.HasElementType || rtOwner.ContainsGenericParameters || rtOwner.IsGenericParameter || rtOwner.IsInterface) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeForDynamicMethod")); m_typeOwner = rtOwner; m_module = rtOwner.GetRuntimeModule(); } } m_skipVisibility = skipVisibility; } // initialize remaining fields m_ilGenerator = null; m_fInitLocals = true; m_methodHandle = null; if (name == null) throw new ArgumentNullException("name"); #if FEATURE_APPX if (AppDomain.ProfileAPICheck) { if (m_creatorAssembly == null) m_creatorAssembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (m_creatorAssembly != null && !m_creatorAssembly.IsFrameworkAssembly()) m_profileAPICheck = true; } #endif // FEATURE_APPX m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention); } [System.Security.SecurityCritical] // auto-generated private void PerformSecurityCheck(Module m, ref StackCrawlMark stackMark, bool skipVisibility) { if (m == null) throw new ArgumentNullException("m"); Contract.EndContractBlock(); RuntimeModule rtModule; ModuleBuilder mb = m as ModuleBuilder; if (mb != null) rtModule = mb.InternalModule; else rtModule = m as RuntimeModule; if (rtModule == null) { throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeModule"), "m"); } // The user cannot explicitly use this assembly if (rtModule == s_anonymouslyHostedDynamicMethodsModule) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"), "m"); // ask for member access if skip visibility if (skipVisibility) new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); #if !FEATURE_CORECLR // ask for control evidence if outside of the caller assembly RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark); m_creatorAssembly = callingType.GetRuntimeAssembly(); if (m.Assembly != m_creatorAssembly) { // Demand the permissions of the assembly where the DynamicMethod will live CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence, m.Assembly.PermissionSet); } #else //FEATURE_CORECLR #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); #pragma warning restore 618 #endif //FEATURE_CORECLR } [System.Security.SecurityCritical] // auto-generated private void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility) { if (owner == null) throw new ArgumentNullException("owner"); RuntimeType rtOwner = owner as RuntimeType; if (rtOwner == null) rtOwner = owner.UnderlyingSystemType as RuntimeType; if (rtOwner == null) throw new ArgumentNullException("owner", Environment.GetResourceString("Argument_MustBeRuntimeType")); // get the type the call is coming from RuntimeType callingType = RuntimeMethodHandle.GetCallerType(ref stackMark); // ask for member access if skip visibility if (skipVisibility) new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); else { // if the call is not coming from the same class ask for member access if (callingType != rtOwner) new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); } #if !FEATURE_CORECLR m_creatorAssembly = callingType.GetRuntimeAssembly(); // ask for control evidence if outside of the caller module if (rtOwner.Assembly != m_creatorAssembly) { // Demand the permissions of the assembly where the DynamicMethod will live CodeAccessSecurityEngine.ReflectionTargetDemandHelper(PermissionType.SecurityControlEvidence, owner.Assembly.PermissionSet); } #else //FEATURE_CORECLR #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); #pragma warning restore 618 #endif //FEATURE_CORECLR } // // Delegate and method creation // [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public sealed override Delegate CreateDelegate(Type delegateType) { if (m_restrictedSkipVisibility) { // Compile the method since accessibility checks are done as part of compilation. GetMethodDescriptor(); System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle); } MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, null, GetMethodDescriptor()); // stash this MethodInfo by brute force. d.StoreDynamicMethod(GetMethodInfo()); return d; } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public sealed override Delegate CreateDelegate(Type delegateType, Object target) { if (m_restrictedSkipVisibility) { // Compile the method since accessibility checks are done as part of compilation GetMethodDescriptor(); System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle); } MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, target, GetMethodDescriptor()); // stash this MethodInfo by brute force. d.StoreDynamicMethod(GetMethodInfo()); return d; } #if FEATURE_APPX internal bool ProfileAPICheck { get { return m_profileAPICheck; } [FriendAccessAllowed] set { m_profileAPICheck = value; } } #endif // This is guaranteed to return a valid handle [System.Security.SecurityCritical] // auto-generated internal unsafe RuntimeMethodHandle GetMethodDescriptor() { if (m_methodHandle == null) { lock (this) { if (m_methodHandle == null) { if (m_DynamicILInfo != null) m_DynamicILInfo.GetCallableMethod(m_module, this); else { if (m_ilGenerator == null || m_ilGenerator.ILOffset == 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadEmptyMethodBody", Name)); m_ilGenerator.GetCallableMethod(m_module, this); } } } } return new RuntimeMethodHandle(m_methodHandle); } // // MethodInfo api. They mostly forward to RTDynamicMethod // public override String ToString() { return m_dynMethod.ToString(); } public override String Name { get { return m_dynMethod.Name; } } public override Type DeclaringType { get { return m_dynMethod.DeclaringType; } } public override Type ReflectedType { get { return m_dynMethod.ReflectedType; } } public override Module Module { get { return m_dynMethod.Module; } } // we cannot return a MethodHandle because we cannot track it via GC so this method is off limits public override RuntimeMethodHandle MethodHandle { get { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } } public override MethodAttributes Attributes { get { return m_dynMethod.Attributes; } } public override CallingConventions CallingConvention { get { return m_dynMethod.CallingConvention; } } public override MethodInfo GetBaseDefinition() { return this; } [Pure] public override ParameterInfo[] GetParameters() { return m_dynMethod.GetParameters(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_dynMethod.GetMethodImplementationFlags(); } // // Security transparency accessors // // Since the dynamic method may not be JITed yet, we don't always have the runtime method handle // which is needed to determine the official runtime transparency status of the dynamic method. We // fall back to saying that the dynamic method matches the transparency of its containing module // until we get a JITed version, since dynamic methods cannot have attributes of their own. // public override bool IsSecurityCritical { [SecuritySafeCritical] get { if (m_methodHandle != null) { return RuntimeMethodHandle.IsSecurityCritical(m_methodHandle); } else if (m_typeOwner != null) { RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly; Contract.Assert(assembly != null); return assembly.IsAllSecurityCritical(); } else { RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly; Contract.Assert(assembly != null); return assembly.IsAllSecurityCritical(); } } } public override bool IsSecuritySafeCritical { [SecuritySafeCritical] get { if (m_methodHandle != null) { return RuntimeMethodHandle.IsSecuritySafeCritical(m_methodHandle); } else if (m_typeOwner != null) { RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly; Contract.Assert(assembly != null); return assembly.IsAllPublicAreaSecuritySafeCritical(); } else { RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly; Contract.Assert(assembly != null); return assembly.IsAllSecuritySafeCritical(); } } } public override bool IsSecurityTransparent { [SecuritySafeCritical] get { if (m_methodHandle != null) { return RuntimeMethodHandle.IsSecurityTransparent(m_methodHandle); } else if (m_typeOwner != null) { RuntimeAssembly assembly = m_typeOwner.Assembly as RuntimeAssembly; Contract.Assert(assembly != null); return !assembly.IsAllSecurityCritical(); } else { RuntimeAssembly assembly = m_module.Assembly as RuntimeAssembly; Contract.Assert(assembly != null); return !assembly.IsAllSecurityCritical(); } } } [System.Security.SecuritySafeCritical] // auto-generated public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) throw new NotSupportedException(Environment.GetResourceString("NotSupported_CallToVarArg")); Contract.EndContractBlock(); // // We do not demand any permission here because the caller already has access // to the current DynamicMethod object, and it could just as easily emit another // Transparent DynamicMethod to call the current DynamicMethod. // RuntimeMethodHandle method = GetMethodDescriptor(); // ignore obj since it's a static method // create a signature object Signature sig = new Signature( this.m_methodHandle, m_parameterTypes, m_returnType, CallingConvention); // verify arguments int formalCount = sig.Arguments.Length; int actualCount = (parameters != null) ? parameters.Length : 0; if (formalCount != actualCount) throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); // if we are here we passed all the previous checks. Time to look at the arguments Object retValue = null; if (actualCount > 0) { Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, false); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) parameters[index] = arguments[index]; } else { retValue = RuntimeMethodHandle.InvokeMethod(null, null, sig, false); } GC.KeepAlive(this); return retValue; } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_dynMethod.GetCustomAttributes(attributeType, inherit); } public override Object[] GetCustomAttributes(bool inherit) { return m_dynMethod.GetCustomAttributes(inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_dynMethod.IsDefined(attributeType, inherit); } public override Type ReturnType { get { return m_dynMethod.ReturnType; } } public override ParameterInfo ReturnParameter { get { return m_dynMethod.ReturnParameter; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return m_dynMethod.ReturnTypeCustomAttributes; } } // // DynamicMethod specific methods // public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String parameterName) { if (position < 0 || position > m_parameterTypes.Length) throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence")); position--; // it's 1 based. 0 is the return value if (position >= 0) { ParameterInfo[] parameters = m_dynMethod.LoadParameters(); parameters[position].SetName(parameterName); parameters[position].SetAttributes(attributes); } return null; } [System.Security.SecuritySafeCritical] // auto-generated public DynamicILInfo GetDynamicILInfo() { #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 if (m_DynamicILInfo != null) return m_DynamicILInfo; return GetDynamicILInfo(new DynamicScope()); } [System.Security.SecurityCritical] // auto-generated internal DynamicILInfo GetDynamicILInfo(DynamicScope scope) { if (m_DynamicILInfo == null) { byte[] methodSignature = SignatureHelper.GetMethodSigHelper( null, CallingConvention, ReturnType, null, null, m_parameterTypes, null, null).GetSignature(true); m_DynamicILInfo = new DynamicILInfo(scope, this, methodSignature); } return m_DynamicILInfo; } public ILGenerator GetILGenerator() { return GetILGenerator(64); } [System.Security.SecuritySafeCritical] // auto-generated public ILGenerator GetILGenerator(int streamSize) { if (m_ilGenerator == null) { byte[] methodSignature = SignatureHelper.GetMethodSigHelper( null, CallingConvention, ReturnType, null, null, m_parameterTypes, null, null).GetSignature(true); m_ilGenerator = new DynamicILGenerator(this, methodSignature, streamSize); } return m_ilGenerator; } public bool InitLocals { get {return m_fInitLocals;} set {m_fInitLocals = value;} } // // Internal API // internal MethodInfo GetMethodInfo() { return m_dynMethod; } ////////////////////////////////////////////////////////////////////////////////////////////// // RTDynamicMethod // // this is actually the real runtime instance of a method info that gets used for invocation // We need this so we never leak the DynamicMethod out via an exception. // This way the DynamicMethod creator is the only one responsible for DynamicMethod access, // and can control exactly who gets access to it. // internal class RTDynamicMethod : MethodInfo { internal DynamicMethod m_owner; ParameterInfo[] m_parameters; String m_name; MethodAttributes m_attributes; CallingConventions m_callingConvention; // // ctors // private RTDynamicMethod() {} internal RTDynamicMethod(DynamicMethod owner, String name, MethodAttributes attributes, CallingConventions callingConvention) { m_owner = owner; m_name = name; m_attributes = attributes; m_callingConvention = callingConvention; } // // MethodInfo api // public override String ToString() { return ReturnType.FormatTypeName() + " " + FormatNameAndSig(); } public override String Name { get { return m_name; } } public override Type DeclaringType { get { return null; } } public override Type ReflectedType { get { return null; } } public override Module Module { get { return m_owner.m_module; } } public override RuntimeMethodHandle MethodHandle { get { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } } public override MethodAttributes Attributes { get { return m_attributes; } } public override CallingConventions CallingConvention { get { return m_callingConvention; } } public override MethodInfo GetBaseDefinition() { return this; } [Pure] public override ParameterInfo[] GetParameters() { ParameterInfo[] privateParameters = LoadParameters(); ParameterInfo[] parameters = new ParameterInfo[privateParameters.Length]; Array.Copy(privateParameters, parameters, privateParameters.Length); return parameters; } public override MethodImplAttributes GetMethodImplementationFlags() { return MethodImplAttributes.IL | MethodImplAttributes.NoInlining; } public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { // We want the creator of the DynamicMethod to control who has access to the // DynamicMethod (just like we do for delegates). However, a user can get to // the corresponding RTDynamicMethod using Exception.TargetSite, StackFrame.GetMethod, etc. // If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would // not be able to bound access to the DynamicMethod. Hence, we do not allow // direct use of RTDynamicMethod. throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "this"); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) return new Object[] { new MethodImplAttribute(GetMethodImplementationFlags()) }; else return EmptyArray<Object>.Value; } public override Object[] GetCustomAttributes(bool inherit) { // support for MethodImplAttribute PCA return new Object[] { new MethodImplAttribute(GetMethodImplementationFlags()) }; } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) return true; else return false; } public override bool IsSecurityCritical { get { return m_owner.IsSecurityCritical; } } public override bool IsSecuritySafeCritical { get { return m_owner.IsSecuritySafeCritical; } } public override bool IsSecurityTransparent { get { return m_owner.IsSecurityTransparent; } } public override Type ReturnType { get { return m_owner.m_returnType; } } public override ParameterInfo ReturnParameter { get { return null; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return GetEmptyCAHolder(); } } // // private implementation // internal ParameterInfo[] LoadParameters() { if (m_parameters == null) { Type[] parameterTypes = m_owner.m_parameterTypes; ParameterInfo[] parameters = new ParameterInfo[parameterTypes.Length]; for (int i = 0; i < parameterTypes.Length; i++) parameters[i] = new RuntimeParameterInfo(this, null, parameterTypes[i], i); if (m_parameters == null) // should we interlockexchange? m_parameters = parameters; } return m_parameters; } // private implementation of CA for the return type private ICustomAttributeProvider GetEmptyCAHolder() { return new EmptyCAHolder(); } /////////////////////////////////////////////////// // EmptyCAHolder private class EmptyCAHolder : ICustomAttributeProvider { internal EmptyCAHolder() {} Object[] ICustomAttributeProvider.GetCustomAttributes(Type attributeType, bool inherit) { return EmptyArray<Object>.Value; } Object[] ICustomAttributeProvider.GetCustomAttributes(bool inherit) { return EmptyArray<Object>.Value; } bool ICustomAttributeProvider.IsDefined (Type attributeType, bool inherit) { return false; } } } } }
// // Source.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2005-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.Reflection; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Mono.Unix; using Hyena; using Hyena.Data; using Hyena.Query; using Banshee.Base; using Banshee.Collection; using Banshee.Configuration; using Banshee.ServiceStack; namespace Banshee.Sources { [NDesk.DBus.IgnoreMarshalByRefObjectBaseClass] public abstract class Source : MarshalByRefObject, ISource { private Source parent; private PropertyStore properties = new PropertyStore (); protected SourceMessage status_message; private List<SourceMessage> messages = new List<SourceMessage> (); private List<Source> child_sources = new List<Source> (); private ReadOnlyCollection<Source> read_only_children; private SourceSortType child_sort; private bool sort_children = true; private SchemaEntry<string> child_sort_schema; private SchemaEntry<bool> separate_by_type_schema; public event EventHandler Updated; public event EventHandler UserNotifyUpdated; public event EventHandler MessageNotify; public event SourceEventHandler ChildSourceAdded; public event SourceEventHandler ChildSourceRemoved; public delegate void OpenPropertiesDelegate (); protected Source (string generic_name, string name, int order) : this (generic_name, name, order, null) { } protected Source (string generic_name, string name, int order, string type_unique_id) : this () { GenericName = generic_name; Name = name; Order = order; TypeUniqueId = type_unique_id; SourceInitialize (); } protected Source () { child_sort = DefaultChildSort; } // This method is chained to subclasses intialize methods, // allowing at any state for delayed intialization by using the empty ctor. protected virtual void Initialize () { SourceInitialize (); } private void SourceInitialize () { // If this source is not defined in Banshee.Services, set its // ResourceAssembly to the assembly where it is defined. Assembly asm = Assembly.GetAssembly (this.GetType ());//Assembly.GetCallingAssembly (); if (asm != Assembly.GetExecutingAssembly ()) { Properties.Set<Assembly> ("ResourceAssembly", asm); } properties.PropertyChanged += OnPropertyChanged; read_only_children = new ReadOnlyCollection<Source> (child_sources); if (ApplicationContext.Debugging && ApplicationContext.CommandLine.Contains ("test-source-messages")) { TestMessages (); } LoadSortSchema (); } protected void OnSetupComplete () { /*ITrackModelSource tm_source = this as ITrackModelSource; if (tm_source != null) { tm_source.TrackModel.Parent = this; ServiceManager.DBusServiceManager.RegisterObject (tm_source.TrackModel); // TODO if/when browsable models can be added/removed on the fly, this would need to change to reflect that foreach (IListModel model in tm_source.FilterModels) { Banshee.Collection.ExportableModel exportable = model as Banshee.Collection.ExportableModel; if (exportable != null) { exportable.Parent = this; ServiceManager.DBusServiceManager.RegisterObject (exportable); } } }*/ } protected void Remove () { if (prefs_page != null) { prefs_page.Dispose (); } if (ServiceManager.SourceManager.ContainsSource (this)) { if (this.Parent != null) { this.Parent.RemoveChildSource (this); } else { ServiceManager.SourceManager.RemoveSource (this); } } } protected void PauseSorting () { sort_children = false; } protected void ResumeSorting () { sort_children = true; } #region Public Methods public virtual void Activate () { } public virtual void Deactivate () { } public virtual void Rename (string newName) { properties.SetString ("Name", newName); } public virtual bool AcceptsInputFromSource (Source source) { return false; } public virtual bool AcceptsUserInputFromSource (Source source) { return AcceptsInputFromSource (source); } public virtual void MergeSourceInput (Source source, SourceMergeType mergeType) { Log.ErrorFormat ("MergeSourceInput not implemented by {0}", this); } public virtual SourceMergeType SupportedMergeTypes { get { return SourceMergeType.None; } } public virtual void SetParentSource (Source parent) { this.parent = parent; } public virtual bool ContainsChildSource (Source child) { lock (Children) { return child_sources.Contains (child); } } public virtual void AddChildSource (Source child) { lock (Children) { if (!child_sources.Contains (child)) { child.SetParentSource (this); child_sources.Add (child); OnChildSourceAdded (child); } } } public virtual void RemoveChildSource (Source child) { lock (Children) { if (child.Children.Count > 0) { child.ClearChildSources (); } child_sources.Remove (child); OnChildSourceRemoved (child); } } public virtual void ClearChildSources () { lock (Children) { while (child_sources.Count > 0) { RemoveChildSource (child_sources[child_sources.Count - 1]); } } } private class SizeComparer : IComparer<Source> { public int Compare (Source a, Source b) { return a.Count.CompareTo (b.Count); } } public virtual void SortChildSources (SourceSortType sort_type) { child_sort = sort_type; child_sort_schema.Set (child_sort.Id); SortChildSources (); } public virtual void SortChildSources () { lock (this) { if (!sort_children) { return; } sort_children = false; } if (child_sort != null && child_sort.SortType != SortType.None) { lock (Children) { child_sort.Sort (child_sources, SeparateChildrenByType); int i = 0; foreach (Source child in child_sources) { // Leave children with negative orders alone, so they can be manually // placed at the top if (child.Order >= 0) { child.Order = i++; } } } } sort_children = true; } private void LoadSortSchema () { if (ChildSortTypes.Length == 0) { return; } if (unique_id == null && type_unique_id == null) { Hyena.Log.WarningFormat ("Trying to LoadSortSchema, but source's id not set! {0}", UniqueId); return; } child_sort_schema = CreateSchema<string> ("child_sort_id", DefaultChildSort.Id, "", ""); string child_sort_id = child_sort_schema.Get (); foreach (SourceSortType sort_type in ChildSortTypes) { if (sort_type.Id == child_sort_id) { child_sort = sort_type; break; } } separate_by_type_schema = CreateSchema<bool> ("separate_by_type", false, "", ""); SortChildSources (); } public T GetProperty<T> (string name, bool inherited) { return inherited ? GetInheritedProperty<T> (name) : Properties.Get<T> (name); } public T GetInheritedProperty<T> (string name) { return Properties.Contains (name) ? Properties.Get<T> (name) : Parent != null ? Parent.GetInheritedProperty<T> (name) : default (T); } #endregion #region Protected Methods public virtual void SetStatus (string message, bool error) { SetStatus (message, !error, !error, error ? "dialog-error" : null); } public virtual void SetStatus (string message, bool can_close, bool is_spinning, string icon_name) { lock (this) { if (status_message == null) { status_message = new SourceMessage (this); PushMessage (status_message); } string status_name = String.Format ("<i>{0}</i>", GLib.Markup.EscapeText (Name)); status_message.FreezeNotify (); status_message.Text = String.Format (GLib.Markup.EscapeText (message), status_name); status_message.CanClose = can_close; status_message.IsSpinning = is_spinning; status_message.SetIconName (icon_name); status_message.IsHidden = false; status_message.ClearActions (); } status_message.ThawNotify (); } public virtual void HideStatus () { lock (this) { if (status_message != null) { RemoveMessage (status_message); status_message = null; } } } public void PushMessage (SourceMessage message) { lock (this) { messages.Insert (0, message); message.Updated += HandleMessageUpdated; } OnMessageNotify (); } protected SourceMessage PopMessage () { try { lock (this) { if (messages.Count > 0) { SourceMessage message = messages[0]; message.Updated -= HandleMessageUpdated; messages.RemoveAt (0); return message; } return null; } } finally { OnMessageNotify (); } } protected void ClearMessages () { lock (this) { if (messages.Count > 0) { foreach (SourceMessage message in messages) { message.Updated -= HandleMessageUpdated; } messages.Clear (); OnMessageNotify (); } status_message = null; } } private void TestMessages () { int count = 0; SourceMessage message_3 = null; Application.RunTimeout (5000, delegate { if (count++ > 5) { if (count == 7) { RemoveMessage (message_3); } PopMessage (); return true; } else if (count > 10) { return false; } SourceMessage message = new SourceMessage (this); message.FreezeNotify (); message.Text = String.Format ("Testing message {0}", count); message.IsSpinning = count % 2 == 0; message.CanClose = count % 2 == 1; if (count % 3 == 0) { for (int i = 2; i < count; i++) { message.AddAction (new MessageAction (String.Format ("Button {0}", i))); } } message.ThawNotify (); PushMessage (message); if (count == 3) { message_3 = message; } return true; }); } public void RemoveMessage (SourceMessage message) { lock (this) { if (messages.Remove (message)) { message.Updated -= HandleMessageUpdated; OnMessageNotify (); } } } private void HandleMessageUpdated (object o, EventArgs args) { if (CurrentMessage == o && CurrentMessage.IsHidden) { PopMessage (); } OnMessageNotify (); } protected virtual void OnMessageNotify () { EventHandler handler = MessageNotify; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnChildSourceAdded (Source source) { SortChildSources (); source.Updated += OnChildSourceUpdated; ThreadAssist.ProxyToMain (delegate { SourceEventHandler handler = ChildSourceAdded; if (handler != null) { SourceEventArgs args = new SourceEventArgs (); args.Source = source; handler (args); } }); } protected virtual void OnChildSourceRemoved (Source source) { source.Updated -= OnChildSourceUpdated; ThreadAssist.ProxyToMain (delegate { SourceEventHandler handler = ChildSourceRemoved; if (handler != null) { SourceEventArgs args = new SourceEventArgs (); args.Source = source; handler (args); } }); } protected virtual void OnUpdated () { EventHandler handler = Updated; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnChildSourceUpdated (object o, EventArgs args) { SortChildSources (); } public void NotifyUser () { OnUserNotifyUpdated (); } protected void OnUserNotifyUpdated () { if (this != ServiceManager.SourceManager.ActiveSource) { EventHandler handler = UserNotifyUpdated; if (handler != null) { handler (this, EventArgs.Empty); } } } #endregion #region Private Methods private void OnPropertyChanged (object o, PropertyChangeEventArgs args) { OnUpdated (); } #endregion #region Public Properties public ReadOnlyCollection<Source> Children { get { return read_only_children; } } string [] ISource.Children { get { return null; } } public Source Parent { get { return parent; } } public virtual string TypeName { get { return GetType ().Name; } } private string unique_id; public string UniqueId { get { if (unique_id == null && type_unique_id == null) { Log.ErrorFormat ("Creating Source.UniqueId for {0} (type {1}), but TypeUniqueId is null; trace is {2}", this.Name, GetType ().Name, System.Environment.StackTrace); } return unique_id ?? (unique_id = String.Format ("{0}-{1}", this.GetType ().Name, TypeUniqueId)); } } private string type_unique_id; protected string TypeUniqueId { get { return type_unique_id; } set { type_unique_id = value; } } public virtual bool CanRename { get { return false; } } public virtual bool HasProperties { get { return false; } } public virtual bool HasViewableTrackProperties { get { return false; } } public virtual bool HasEditableTrackProperties { get { return false; } } public virtual string Name { get { return properties.Get<string> ("Name"); } set { properties.SetString ("Name", value); } } public virtual string GenericName { get { return properties.Get<string> ("GenericName"); } set { properties.SetString ("GenericName", value); } } public int Order { get { return properties.GetInteger ("Order"); } set { properties.SetInteger ("Order", value); } } public SourceMessage CurrentMessage { get { lock (this) { return messages.Count > 0 ? messages[0] : null; } } } public virtual bool ImplementsCustomSearch { get { return false; } } public virtual bool CanSearch { get { return false; } } public virtual string FilterQuery { get { return properties.Get<string> ("FilterQuery"); } set { properties.SetString ("FilterQuery", value); } } public TrackFilterType FilterType { get { return (TrackFilterType)properties.GetInteger ("FilterType"); } set { properties.SetInteger ("FilterType", (int)value); } } public virtual bool Expanded { get { return properties.GetBoolean ("Expanded"); } set { properties.SetBoolean ("Expanded", value); } } public virtual bool? AutoExpand { get { return true; } } public virtual PropertyStore Properties { get { return properties; } } public virtual bool CanActivate { get { return true; } } public virtual int Count { get { return 0; } } public virtual int EnabledCount { get { return Count; } } private string parent_conf_id; public string ParentConfigurationId { get { if (parent_conf_id == null) { parent_conf_id = (Parent ?? this).UniqueId.Replace ('.', '_'); } return parent_conf_id; } } private string conf_id; public string ConfigurationId { get { return conf_id ?? (conf_id = UniqueId.Replace ('.', '_')); } } public virtual int FilteredCount { get { return Count; } } public virtual string TrackModelPath { get { return null; } } public static readonly SourceSortType SortNameAscending = new SourceSortType ( "NameAsc", Catalog.GetString ("Name"), SortType.Ascending, null); // null comparer b/c we already fall back to sorting by name public static readonly SourceSortType SortSizeAscending = new SourceSortType ( "SizeAsc", Catalog.GetString ("Size Ascending"), SortType.Ascending, new SizeComparer ()); public static readonly SourceSortType SortSizeDescending = new SourceSortType ( "SizeDesc", Catalog.GetString ("Size Descending"), SortType.Descending, new SizeComparer ()); private static SourceSortType[] sort_types = new SourceSortType[] {}; public virtual SourceSortType[] ChildSortTypes { get { return sort_types; } } public SourceSortType ActiveChildSort { get { return child_sort; } } public virtual SourceSortType DefaultChildSort { get { return null; } } public bool SeparateChildrenByType { get { return separate_by_type_schema.Get (); } set { separate_by_type_schema.Set (value); SortChildSources (); } } #endregion #region Status Message Stuff private static DurationStatusFormatters duration_status_formatters = new DurationStatusFormatters (); public static DurationStatusFormatters DurationStatusFormatters { get { return duration_status_formatters; } } protected virtual int StatusFormatsCount { get { return duration_status_formatters.Count; } } public virtual int CurrentStatusFormat { get { return ConfigurationClient.Get<int> (String.Format ("sources.{0}", ParentConfigurationId), "status_format", 0); } set { ConfigurationClient.Set<int> (String.Format ("sources.{0}", ParentConfigurationId), "status_format", value); } } public SchemaEntry<T> CreateSchema<T> (string name) { return CreateSchema<T> (name, default(T), null, null); } public SchemaEntry<T> CreateSchema<T> (string name, T defaultValue, string shortDescription, string longDescription) { return new SchemaEntry<T> (String.Format ("sources.{0}", ParentConfigurationId), name, defaultValue, shortDescription, longDescription); } public SchemaEntry<T> CreateSchema<T> (string ns, string name, T defaultValue, string shortDescription, string longDescription) { return new SchemaEntry<T> (String.Format ("sources.{0}.{1}", ParentConfigurationId, ns), name, defaultValue, shortDescription, longDescription); } public virtual string PreferencesPageId { get { return null; } } private Banshee.Preferences.SourcePage prefs_page; public Banshee.Preferences.Page PreferencesPage { get { return prefs_page ?? (prefs_page = new Banshee.Preferences.SourcePage (this)); } } public void CycleStatusFormat () { int new_status_format = CurrentStatusFormat + 1; if (new_status_format >= StatusFormatsCount) { new_status_format = 0; } CurrentStatusFormat = new_status_format; } private const string STATUS_BAR_SEPARATOR = " \u2013 "; public virtual string GetStatusText () { StringBuilder builder = new StringBuilder (); int count = FilteredCount; if (count == 0) { return String.Empty; } var count_str = String.Format ("{0:N0}", count); builder.AppendFormat (GetPluralItemCountString (count), count_str); if (this is IDurationAggregator && StatusFormatsCount > 0) { var duration = ((IDurationAggregator)this).Duration; if (duration > TimeSpan.Zero) { builder.Append (STATUS_BAR_SEPARATOR); duration_status_formatters[CurrentStatusFormat] (builder, ((IDurationAggregator)this).Duration); } } if (this is IFileSizeAggregator) { long bytes = (this as IFileSizeAggregator).FileSize; if (bytes > 0) { builder.Append (STATUS_BAR_SEPARATOR); builder.AppendFormat (new FileSizeQueryValue (bytes).ToUserQuery ()); } } return builder.ToString (); } public virtual string GetPluralItemCountString (int count) { return Catalog.GetPluralString ("{0} item", "{0} items", count); } #endregion public override string ToString () { return Name; } /*string IService.ServiceName { get { return String.Format ("{0}{1}", DBusServiceManager.MakeDBusSafeString (Name), "Source"); } }*/ // FIXME: Replace ISource with IRemoteExportable when it's enabled again ISource ISource.Parent { get { if (Parent != null) { return ((Source)this).Parent; } else { return null /*ServiceManager.SourceManager*/; } } } } }
// 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 Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Network Client /// </summary> public partial class NetworkManagementClient : ServiceClient<NetworkManagementClient>, INetworkManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The subscription credentials which uniquely identify the Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IApplicationGatewaysOperations. /// </summary> public virtual IApplicationGatewaysOperations ApplicationGateways { get; private set; } /// <summary> /// Gets the IExpressRouteCircuitAuthorizationsOperations. /// </summary> public virtual IExpressRouteCircuitAuthorizationsOperations ExpressRouteCircuitAuthorizations { get; private set; } /// <summary> /// Gets the IExpressRouteCircuitPeeringsOperations. /// </summary> public virtual IExpressRouteCircuitPeeringsOperations ExpressRouteCircuitPeerings { get; private set; } /// <summary> /// Gets the IExpressRouteCircuitsOperations. /// </summary> public virtual IExpressRouteCircuitsOperations ExpressRouteCircuits { get; private set; } /// <summary> /// Gets the IExpressRouteServiceProvidersOperations. /// </summary> public virtual IExpressRouteServiceProvidersOperations ExpressRouteServiceProviders { get; private set; } /// <summary> /// Gets the ILoadBalancersOperations. /// </summary> public virtual ILoadBalancersOperations LoadBalancers { get; private set; } /// <summary> /// Gets the ILoadBalancerBackendAddressPoolsOperations. /// </summary> public virtual ILoadBalancerBackendAddressPoolsOperations LoadBalancerBackendAddressPools { get; private set; } /// <summary> /// Gets the ILoadBalancerFrontendIPConfigurationsOperations. /// </summary> public virtual ILoadBalancerFrontendIPConfigurationsOperations LoadBalancerFrontendIPConfigurations { get; private set; } /// <summary> /// Gets the IInboundNatRulesOperations. /// </summary> public virtual IInboundNatRulesOperations InboundNatRules { get; private set; } /// <summary> /// Gets the ILoadBalancerLoadBalancingRulesOperations. /// </summary> public virtual ILoadBalancerLoadBalancingRulesOperations LoadBalancerLoadBalancingRules { get; private set; } /// <summary> /// Gets the ILoadBalancerNetworkInterfacesOperations. /// </summary> public virtual ILoadBalancerNetworkInterfacesOperations LoadBalancerNetworkInterfaces { get; private set; } /// <summary> /// Gets the ILoadBalancerProbesOperations. /// </summary> public virtual ILoadBalancerProbesOperations LoadBalancerProbes { get; private set; } /// <summary> /// Gets the INetworkInterfacesOperations. /// </summary> public virtual INetworkInterfacesOperations NetworkInterfaces { get; private set; } /// <summary> /// Gets the INetworkInterfaceIPConfigurationsOperations. /// </summary> public virtual INetworkInterfaceIPConfigurationsOperations NetworkInterfaceIPConfigurations { get; private set; } /// <summary> /// Gets the INetworkInterfaceLoadBalancersOperations. /// </summary> public virtual INetworkInterfaceLoadBalancersOperations NetworkInterfaceLoadBalancers { get; private set; } /// <summary> /// Gets the INetworkSecurityGroupsOperations. /// </summary> public virtual INetworkSecurityGroupsOperations NetworkSecurityGroups { get; private set; } /// <summary> /// Gets the ISecurityRulesOperations. /// </summary> public virtual ISecurityRulesOperations SecurityRules { get; private set; } /// <summary> /// Gets the IDefaultSecurityRulesOperations. /// </summary> public virtual IDefaultSecurityRulesOperations DefaultSecurityRules { get; private set; } /// <summary> /// Gets the INetworkWatchersOperations. /// </summary> public virtual INetworkWatchersOperations NetworkWatchers { get; private set; } /// <summary> /// Gets the IPacketCapturesOperations. /// </summary> public virtual IPacketCapturesOperations PacketCaptures { get; private set; } /// <summary> /// Gets the IPublicIPAddressesOperations. /// </summary> public virtual IPublicIPAddressesOperations PublicIPAddresses { get; private set; } /// <summary> /// Gets the IRouteFiltersOperations. /// </summary> public virtual IRouteFiltersOperations RouteFilters { get; private set; } /// <summary> /// Gets the IRouteFilterRulesOperations. /// </summary> public virtual IRouteFilterRulesOperations RouteFilterRules { get; private set; } /// <summary> /// Gets the IRouteTablesOperations. /// </summary> public virtual IRouteTablesOperations RouteTables { get; private set; } /// <summary> /// Gets the IRoutesOperations. /// </summary> public virtual IRoutesOperations Routes { get; private set; } /// <summary> /// Gets the IBgpServiceCommunitiesOperations. /// </summary> public virtual IBgpServiceCommunitiesOperations BgpServiceCommunities { get; private set; } /// <summary> /// Gets the IUsagesOperations. /// </summary> public virtual IUsagesOperations Usages { get; private set; } /// <summary> /// Gets the IVirtualNetworksOperations. /// </summary> public virtual IVirtualNetworksOperations VirtualNetworks { get; private set; } /// <summary> /// Gets the ISubnetsOperations. /// </summary> public virtual ISubnetsOperations Subnets { get; private set; } /// <summary> /// Gets the IVirtualNetworkPeeringsOperations. /// </summary> public virtual IVirtualNetworkPeeringsOperations VirtualNetworkPeerings { get; private set; } /// <summary> /// Gets the IVirtualNetworkGatewaysOperations. /// </summary> public virtual IVirtualNetworkGatewaysOperations VirtualNetworkGateways { get; private set; } /// <summary> /// Gets the IVirtualNetworkGatewayConnectionsOperations. /// </summary> public virtual IVirtualNetworkGatewayConnectionsOperations VirtualNetworkGatewayConnections { get; private set; } /// <summary> /// Gets the ILocalNetworkGatewaysOperations. /// </summary> public virtual ILocalNetworkGatewaysOperations LocalNetworkGateways { get; private set; } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected NetworkManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected NetworkManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected NetworkManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected NetworkManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public NetworkManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public NetworkManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public NetworkManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public NetworkManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { ApplicationGateways = new ApplicationGatewaysOperations(this); ExpressRouteCircuitAuthorizations = new ExpressRouteCircuitAuthorizationsOperations(this); ExpressRouteCircuitPeerings = new ExpressRouteCircuitPeeringsOperations(this); ExpressRouteCircuits = new ExpressRouteCircuitsOperations(this); ExpressRouteServiceProviders = new ExpressRouteServiceProvidersOperations(this); LoadBalancers = new LoadBalancersOperations(this); LoadBalancerBackendAddressPools = new LoadBalancerBackendAddressPoolsOperations(this); LoadBalancerFrontendIPConfigurations = new LoadBalancerFrontendIPConfigurationsOperations(this); InboundNatRules = new InboundNatRulesOperations(this); LoadBalancerLoadBalancingRules = new LoadBalancerLoadBalancingRulesOperations(this); LoadBalancerNetworkInterfaces = new LoadBalancerNetworkInterfacesOperations(this); LoadBalancerProbes = new LoadBalancerProbesOperations(this); NetworkInterfaces = new NetworkInterfacesOperations(this); NetworkInterfaceIPConfigurations = new NetworkInterfaceIPConfigurationsOperations(this); NetworkInterfaceLoadBalancers = new NetworkInterfaceLoadBalancersOperations(this); NetworkSecurityGroups = new NetworkSecurityGroupsOperations(this); SecurityRules = new SecurityRulesOperations(this); DefaultSecurityRules = new DefaultSecurityRulesOperations(this); NetworkWatchers = new NetworkWatchersOperations(this); PacketCaptures = new PacketCapturesOperations(this); PublicIPAddresses = new PublicIPAddressesOperations(this); RouteFilters = new RouteFiltersOperations(this); RouteFilterRules = new RouteFilterRulesOperations(this); RouteTables = new RouteTablesOperations(this); Routes = new RoutesOperations(this); BgpServiceCommunities = new BgpServiceCommunitiesOperations(this); Usages = new UsagesOperations(this); VirtualNetworks = new VirtualNetworksOperations(this); Subnets = new SubnetsOperations(this); VirtualNetworkPeerings = new VirtualNetworkPeeringsOperations(this); VirtualNetworkGateways = new VirtualNetworkGatewaysOperations(this); VirtualNetworkGatewayConnections = new VirtualNetworkGatewayConnectionsOperations(this); LocalNetworkGateways = new LocalNetworkGatewaysOperations(this); BaseUri = new System.Uri("https://management.azure.com"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Checks whether a domain name in the cloudapp.net zone is available for use. /// </summary> /// <param name='location'> /// The location of the domain name. /// </param> /// <param name='domainNameLabel'> /// The domain name to be verified. It must conform to the following regular /// expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DnsNameAvailabilityResult>> CheckDnsNameAvailabilityWithHttpMessagesAsync(string location, string domainNameLabel = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("domainNameLabel", domainNameLabel); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CheckDnsNameAvailability", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/CheckDnsNameAvailability").ToString(); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId)); List<string> _queryParameters = new List<string>(); if (domainNameLabel != null) { _queryParameters.Add(string.Format("domainNameLabel={0}", System.Uri.EscapeDataString(domainNameLabel))); } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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, 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<DnsNameAvailabilityResult>(); _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<DnsNameAvailabilityResult>(_responseContent, 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) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using log4net; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenMetaverse.Assets; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.CoreModules.Avatar.AvatarFactory; using OpenSim.Region.OptionalModules.World.NPC; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; using OpenSim.Region.ScriptEngine.Shared.Instance; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.ScriptEngine.Shared.Tests { /// <summary> /// Tests for inventory functions in LSL /// </summary> [TestFixture] public class LSL_ApiInventoryTests : OpenSimTestCase { protected Scene m_scene; protected XEngine.XEngine m_engine; [SetUp] public override void SetUp() { base.SetUp(); IConfigSource initConfigSource = new IniConfigSource(); IConfig config = initConfigSource.AddConfig("XEngine"); config.Set("Enabled", "true"); m_scene = new SceneHelpers().SetupScene(); SceneHelpers.SetupSceneModules(m_scene, initConfigSource); m_engine = new XEngine.XEngine(); m_engine.Initialise(initConfigSource); m_engine.AddRegion(m_scene); } /// <summary> /// Test giving inventory from an object to an object where both are owned by the same user. /// </summary> [Test] public void TestLlGiveInventoryO2OSameOwner() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); UUID userId = TestHelpers.ParseTail(0x1); string inventoryItemName = "item1"; SceneObjectGroup so1 = SceneHelpers.CreateSceneObject(1, userId, "so1", 0x10); m_scene.AddSceneObject(so1); // Create an object embedded inside the first UUID itemId = TestHelpers.ParseTail(0x20); TaskInventoryHelpers.AddSceneObject(m_scene.AssetService, so1.RootPart, inventoryItemName, itemId, userId); LSL_Api api = new LSL_Api(); api.Initialize(m_engine, so1.RootPart, null); // Create a second object SceneObjectGroup so2 = SceneHelpers.CreateSceneObject(1, userId, "so2", 0x100); m_scene.AddSceneObject(so2); api.llGiveInventory(so2.UUID.ToString(), inventoryItemName); // Item has copy permissions so original should stay intact. List<TaskInventoryItem> originalItems = so1.RootPart.Inventory.GetInventoryItems(); Assert.That(originalItems.Count, Is.EqualTo(1)); List<TaskInventoryItem> copiedItems = so2.RootPart.Inventory.GetInventoryItems(inventoryItemName); Assert.That(copiedItems.Count, Is.EqualTo(1)); Assert.That(copiedItems[0].Name, Is.EqualTo(inventoryItemName)); } /// <summary> /// Test giving inventory from an object to an object where they have different owners /// </summary> [Test] public void TestLlGiveInventoryO2ODifferentOwners() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); UUID user1Id = TestHelpers.ParseTail(0x1); UUID user2Id = TestHelpers.ParseTail(0x2); string inventoryItemName = "item1"; SceneObjectGroup so1 = SceneHelpers.CreateSceneObject(1, user1Id, "so1", 0x10); m_scene.AddSceneObject(so1); LSL_Api api = new LSL_Api(); api.Initialize(m_engine, so1.RootPart, null); // Create an object embedded inside the first UUID itemId = TestHelpers.ParseTail(0x20); TaskInventoryHelpers.AddSceneObject(m_scene.AssetService, so1.RootPart, inventoryItemName, itemId, user1Id); // Create a second object SceneObjectGroup so2 = SceneHelpers.CreateSceneObject(1, user2Id, "so2", 0x100); m_scene.AddSceneObject(so2); LSL_Api api2 = new LSL_Api(); api2.Initialize(m_engine, so2.RootPart, null); // *** Firstly, we test where llAllowInventoryDrop() has not been called. *** api.llGiveInventory(so2.UUID.ToString(), inventoryItemName); { // Item has copy permissions so original should stay intact. List<TaskInventoryItem> originalItems = so1.RootPart.Inventory.GetInventoryItems(); Assert.That(originalItems.Count, Is.EqualTo(1)); // Should have not copied List<TaskInventoryItem> copiedItems = so2.RootPart.Inventory.GetInventoryItems(inventoryItemName); Assert.That(copiedItems.Count, Is.EqualTo(0)); } // *** Secondly, we turn on allow inventory drop in the target and retest. *** api2.llAllowInventoryDrop(1); api.llGiveInventory(so2.UUID.ToString(), inventoryItemName); { // Item has copy permissions so original should stay intact. List<TaskInventoryItem> originalItems = so1.RootPart.Inventory.GetInventoryItems(); Assert.That(originalItems.Count, Is.EqualTo(1)); // Should now have copied. List<TaskInventoryItem> copiedItems = so2.RootPart.Inventory.GetInventoryItems(inventoryItemName); Assert.That(copiedItems.Count, Is.EqualTo(1)); Assert.That(copiedItems[0].Name, Is.EqualTo(inventoryItemName)); } } /// <summary> /// Test giving inventory from an object to an avatar that is not the object's owner. /// </summary> [Test] public void TestLlGiveInventoryO2DifferentAvatar() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID user1Id = TestHelpers.ParseTail(0x1); UUID user2Id = TestHelpers.ParseTail(0x2); string inventoryItemName = "item1"; SceneObjectGroup so1 = SceneHelpers.CreateSceneObject(1, user1Id, "so1", 0x10); m_scene.AddSceneObject(so1); LSL_Api api = new LSL_Api(); api.Initialize(m_engine, so1.RootPart, null); // Create an object embedded inside the first UUID itemId = TestHelpers.ParseTail(0x20); TaskInventoryHelpers.AddSceneObject(m_scene.AssetService, so1.RootPart, inventoryItemName, itemId, user1Id); UserAccountHelpers.CreateUserWithInventory(m_scene, user2Id); api.llGiveInventory(user2Id.ToString(), inventoryItemName); InventoryItemBase receivedItem = UserInventoryHelpers.GetInventoryItem( m_scene.InventoryService, user2Id, string.Format("Objects/{0}", inventoryItemName)); Assert.IsNotNull(receivedItem); } /// <summary> /// Test giving inventory from an object to an avatar that is not the object's owner and where the next /// permissions do not include mod. /// </summary> [Test] public void TestLlGiveInventoryO2DifferentAvatarNoMod() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID user1Id = TestHelpers.ParseTail(0x1); UUID user2Id = TestHelpers.ParseTail(0x2); string inventoryItemName = "item1"; SceneObjectGroup so1 = SceneHelpers.CreateSceneObject(1, user1Id, "so1", 0x10); m_scene.AddSceneObject(so1); LSL_Api api = new LSL_Api(); api.Initialize(m_engine, so1.RootPart, null); // Create an object embedded inside the first UUID itemId = TestHelpers.ParseTail(0x20); TaskInventoryItem tii = TaskInventoryHelpers.AddSceneObject(m_scene.AssetService, so1.RootPart, inventoryItemName, itemId, user1Id); tii.NextPermissions &= ~((uint)PermissionMask.Modify); UserAccountHelpers.CreateUserWithInventory(m_scene, user2Id); api.llGiveInventory(user2Id.ToString(), inventoryItemName); InventoryItemBase receivedItem = UserInventoryHelpers.GetInventoryItem( m_scene.InventoryService, user2Id, string.Format("Objects/{0}", inventoryItemName)); Assert.IsNotNull(receivedItem); Assert.AreEqual(0, receivedItem.CurrentPermissions & (uint)PermissionMask.Modify); } [Test] public void TestLlRemoteLoadScriptPin() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID user1Id = TestHelpers.ParseTail(0x1); UUID user2Id = TestHelpers.ParseTail(0x2); SceneObjectGroup sourceSo = SceneHelpers.AddSceneObject(m_scene, "sourceSo", user1Id); m_scene.AddSceneObject(sourceSo); LSL_Api api = new LSL_Api(); api.Initialize(m_engine, sourceSo.RootPart, null); TaskInventoryHelpers.AddScript(m_scene.AssetService, sourceSo.RootPart, "script", "Hello World"); SceneObjectGroup targetSo = SceneHelpers.AddSceneObject(m_scene, "targetSo", user1Id); SceneObjectGroup otherOwnedTargetSo = SceneHelpers.AddSceneObject(m_scene, "otherOwnedTargetSo", user2Id); // Test that we cannot load a script when the target pin has never been set (i.e. it is zero) api.llRemoteLoadScriptPin(targetSo.UUID.ToString(), "script", 0, 0, 0); Assert.IsNull(targetSo.RootPart.Inventory.GetInventoryItem("script")); // Test that we cannot load a script when the given pin does not match the target targetSo.RootPart.ScriptAccessPin = 5; api.llRemoteLoadScriptPin(targetSo.UUID.ToString(), "script", 3, 0, 0); Assert.IsNull(targetSo.RootPart.Inventory.GetInventoryItem("script")); // Test that we cannot load into a prim with a different owner otherOwnedTargetSo.RootPart.ScriptAccessPin = 3; api.llRemoteLoadScriptPin(otherOwnedTargetSo.UUID.ToString(), "script", 3, 0, 0); Assert.IsNull(otherOwnedTargetSo.RootPart.Inventory.GetInventoryItem("script")); // Test that we can load a script when given pin and dest pin match. targetSo.RootPart.ScriptAccessPin = 3; api.llRemoteLoadScriptPin(targetSo.UUID.ToString(), "script", 3, 0, 0); TaskInventoryItem insertedItem = targetSo.RootPart.Inventory.GetInventoryItem("script"); Assert.IsNotNull(insertedItem); // Test that we can no longer load if access pin is unset targetSo.RootPart.Inventory.RemoveInventoryItem(insertedItem.ItemID); Assert.IsNull(targetSo.RootPart.Inventory.GetInventoryItem("script")); targetSo.RootPart.ScriptAccessPin = 0; api.llRemoteLoadScriptPin(otherOwnedTargetSo.UUID.ToString(), "script", 3, 0, 0); Assert.IsNull(otherOwnedTargetSo.RootPart.Inventory.GetInventoryItem("script")); } } }
namespace Azure.Communication.Administration { public partial class CommunicationIdentityClient { protected CommunicationIdentityClient() { } public CommunicationIdentityClient(string connectionString, Azure.Communication.Administration.CommunicationIdentityClientOptions? options = null) { } public virtual Azure.Response<Azure.Communication.CommunicationUser> CreateUser(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.CommunicationUser>> CreateUserAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response DeleteUser(Azure.Communication.CommunicationUser communicationUser, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DeleteUserAsync(Azure.Communication.CommunicationUser communicationUser, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.Administration.Models.CommunicationUserToken> IssueToken(Azure.Communication.CommunicationUser communicationUser, System.Collections.Generic.IEnumerable<Azure.Communication.Administration.CommunicationTokenScope> scopes, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.Administration.Models.CommunicationUserToken>> IssueTokenAsync(Azure.Communication.CommunicationUser communicationUser, System.Collections.Generic.IEnumerable<Azure.Communication.Administration.CommunicationTokenScope> scopes, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response RevokeTokens(Azure.Communication.CommunicationUser communicationUser, System.DateTimeOffset? issuedBefore = default(System.DateTimeOffset?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> RevokeTokensAsync(Azure.Communication.CommunicationUser communicationUser, System.DateTimeOffset? issuedBefore = default(System.DateTimeOffset?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class CommunicationIdentityClientOptions : Azure.Core.ClientOptions { public const Azure.Communication.Administration.CommunicationIdentityClientOptions.ServiceVersion LatestVersion = Azure.Communication.Administration.CommunicationIdentityClientOptions.ServiceVersion.V1; public CommunicationIdentityClientOptions(Azure.Communication.Administration.CommunicationIdentityClientOptions.ServiceVersion version = Azure.Communication.Administration.CommunicationIdentityClientOptions.ServiceVersion.V1, Azure.Core.RetryOptions? retryOptions = null, Azure.Core.Pipeline.HttpPipelineTransport? transport = null) { } public enum ServiceVersion { V1 = 1, } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct CommunicationTokenScope : System.IEquatable<Azure.Communication.Administration.CommunicationTokenScope> { private readonly object _dummy; private readonly int _dummyPrimitive; public CommunicationTokenScope(string value) { throw null; } public static Azure.Communication.Administration.CommunicationTokenScope Chat { get { throw null; } } public static Azure.Communication.Administration.CommunicationTokenScope Pstn { get { throw null; } } public static Azure.Communication.Administration.CommunicationTokenScope VoIP { get { throw null; } } public bool Equals(Azure.Communication.Administration.CommunicationTokenScope other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.Administration.CommunicationTokenScope left, Azure.Communication.Administration.CommunicationTokenScope right) { throw null; } public static implicit operator Azure.Communication.Administration.CommunicationTokenScope (string value) { throw null; } public static bool operator !=(Azure.Communication.Administration.CommunicationTokenScope left, Azure.Communication.Administration.CommunicationTokenScope right) { throw null; } public override string ToString() { throw null; } } public partial class PhoneNumberAdministrationClient { protected PhoneNumberAdministrationClient() { } public PhoneNumberAdministrationClient(string connectionString) { } public PhoneNumberAdministrationClient(string connectionString, Azure.Communication.Administration.PhoneNumberAdministrationClientOptions? options = null) { } public virtual Azure.Response CancelSearch(string searchId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> CancelSearchAsync(string searchId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response ConfigureNumber(Azure.Communication.Administration.Models.PstnConfiguration pstnConfiguration, Azure.Communication.PhoneNumber phoneNumber, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> ConfigureNumberAsync(Azure.Communication.Administration.Models.PstnConfiguration pstnConfiguration, Azure.Communication.PhoneNumber phoneNumber, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.Administration.Models.CreateSearchResponse> CreateSearch(Azure.Communication.Administration.Models.CreateSearchOptions body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.Administration.Models.CreateSearchResponse>> CreateSearchAsync(Azure.Communication.Administration.Models.CreateSearchOptions body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.Administration.Models.AreaCodes> GetAllAreaCodes(string locationType, string countryCode, string phonePlanId, System.Collections.Generic.IEnumerable<Azure.Communication.Administration.Models.LocationOptionsQuery> locationOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.Administration.Models.AreaCodes>> GetAllAreaCodesAsync(string locationType, string countryCode, string phonePlanId, System.Collections.Generic.IEnumerable<Azure.Communication.Administration.Models.LocationOptionsQuery> locationOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.Communication.Administration.Models.AcquiredPhoneNumber> GetAllPhoneNumbers(string? locale = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.Communication.Administration.Models.AcquiredPhoneNumber> GetAllPhoneNumbersAsync(string? locale = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.Communication.Administration.Models.PhoneNumberEntity> GetAllReleases(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.Communication.Administration.Models.PhoneNumberEntity> GetAllReleasesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.Communication.Administration.Models.PhoneNumberEntity> GetAllSearches(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.Communication.Administration.Models.PhoneNumberEntity> GetAllSearchesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.Communication.Administration.Models.PhoneNumberCountry> GetAllSupportedCountries(string? locale = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.Communication.Administration.Models.PhoneNumberCountry> GetAllSupportedCountriesAsync(string? locale = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.Administration.Models.UpdatePhoneNumberCapabilitiesResponse> GetCapabilitiesUpdate(string capabilitiesUpdateId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.Administration.Models.UpdatePhoneNumberCapabilitiesResponse>> GetCapabilitiesUpdateAsync(string capabilitiesUpdateId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.Administration.Models.NumberConfigurationResponse> GetNumberConfiguration(Azure.Communication.PhoneNumber phoneNumber, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.Administration.Models.NumberConfigurationResponse>> GetNumberConfigurationAsync(Azure.Communication.PhoneNumber phoneNumber, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.Communication.Administration.Models.PhonePlanGroup> GetPhonePlanGroups(string countryCode, string? locale = null, bool? includeRateInformation = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.Communication.Administration.Models.PhonePlanGroup> GetPhonePlanGroupsAsync(string countryCode, string? locale = null, bool? includeRateInformation = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.Administration.Models.LocationOptionsResponse> GetPhonePlanLocationOptions(string countryCode, string phonePlanGroupId, string phonePlanId, string? locale = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.Administration.Models.LocationOptionsResponse>> GetPhonePlanLocationOptionsAsync(string countryCode, string phonePlanGroupId, string phonePlanId, string? locale = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.Communication.Administration.Models.PhonePlan> GetPhonePlans(string countryCode, string phonePlanGroupId, string? locale = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.Communication.Administration.Models.PhonePlan> GetPhonePlansAsync(string countryCode, string phonePlanGroupId, string? locale = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.Administration.Models.PhoneNumberRelease> GetReleaseById(string releaseId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.Administration.Models.PhoneNumberRelease>> GetReleaseByIdAsync(string releaseId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.Administration.Models.PhoneNumberSearch> GetSearchById(string searchId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.Administration.Models.PhoneNumberSearch>> GetSearchByIdAsync(string searchId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response PurchaseSearch(string searchId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> PurchaseSearchAsync(string searchId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.Administration.Models.ReleaseResponse> ReleasePhoneNumbers(System.Collections.Generic.IEnumerable<Azure.Communication.PhoneNumber> phoneNumbers, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.Administration.Models.ReleaseResponse>> ReleasePhoneNumbersAsync(System.Collections.Generic.IEnumerable<Azure.Communication.PhoneNumber> phoneNumbers, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response UnconfigureNumber(Azure.Communication.PhoneNumber phoneNumber, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> UnconfigureNumberAsync(Azure.Communication.PhoneNumber phoneNumber, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Communication.Administration.Models.UpdateNumberCapabilitiesResponse> UpdateCapabilities(System.Collections.Generic.IDictionary<string, Azure.Communication.Administration.Models.NumberUpdateCapabilities> phoneNumberUpdateCapabilities, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Communication.Administration.Models.UpdateNumberCapabilitiesResponse>> UpdateCapabilitiesAsync(System.Collections.Generic.IDictionary<string, Azure.Communication.Administration.Models.NumberUpdateCapabilities> phoneNumberUpdateCapabilities, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class PhoneNumberAdministrationClientOptions : Azure.Core.ClientOptions { public const Azure.Communication.Administration.PhoneNumberAdministrationClientOptions.ServiceVersion LatestVersion = Azure.Communication.Administration.PhoneNumberAdministrationClientOptions.ServiceVersion.V1; public PhoneNumberAdministrationClientOptions(Azure.Communication.Administration.PhoneNumberAdministrationClientOptions.ServiceVersion version = Azure.Communication.Administration.PhoneNumberAdministrationClientOptions.ServiceVersion.V1, Azure.Core.RetryOptions? retryOptions = null, Azure.Core.Pipeline.HttpPipelineTransport? transport = null) { } public enum ServiceVersion { V1 = 1, } } } namespace Azure.Communication.Administration.Models { public partial class AcquiredPhoneNumber { internal AcquiredPhoneNumber() { } public System.Collections.Generic.IReadOnlyList<Azure.Communication.Administration.Models.PhoneNumberCapability> AcquiredCapabilities { get { throw null; } } public Azure.Communication.Administration.Models.ActivationState? ActivationState { get { throw null; } } public Azure.Communication.Administration.Models.AssignmentStatus? AssignmentStatus { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.Communication.Administration.Models.PhoneNumberCapability> AvailableCapabilities { get { throw null; } } public string PhoneNumber { get { throw null; } } public string PlaceName { get { throw null; } } } public partial class AcquiredPhoneNumbers { internal AcquiredPhoneNumbers() { } public string NextLink { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.Communication.Administration.Models.AcquiredPhoneNumber> PhoneNumbers { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ActivationState : System.IEquatable<Azure.Communication.Administration.Models.ActivationState> { private readonly object _dummy; private readonly int _dummyPrimitive; public ActivationState(string value) { throw null; } public static Azure.Communication.Administration.Models.ActivationState Activated { get { throw null; } } public static Azure.Communication.Administration.Models.ActivationState AssignmentFailed { get { throw null; } } public static Azure.Communication.Administration.Models.ActivationState AssignmentPending { get { throw null; } } public static Azure.Communication.Administration.Models.ActivationState UpdateFailed { get { throw null; } } public static Azure.Communication.Administration.Models.ActivationState UpdatePending { get { throw null; } } public bool Equals(Azure.Communication.Administration.Models.ActivationState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.Administration.Models.ActivationState left, Azure.Communication.Administration.Models.ActivationState right) { throw null; } public static implicit operator Azure.Communication.Administration.Models.ActivationState (string value) { throw null; } public static bool operator !=(Azure.Communication.Administration.Models.ActivationState left, Azure.Communication.Administration.Models.ActivationState right) { throw null; } public override string ToString() { throw null; } } public partial class AreaCodes { internal AreaCodes() { } public string NextLink { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> PrimaryAreaCodes { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> SecondaryAreaCodes { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct AssignmentStatus : System.IEquatable<Azure.Communication.Administration.Models.AssignmentStatus> { private readonly object _dummy; private readonly int _dummyPrimitive; public AssignmentStatus(string value) { throw null; } public static Azure.Communication.Administration.Models.AssignmentStatus ConferenceAssigned { get { throw null; } } public static Azure.Communication.Administration.Models.AssignmentStatus FirstPartyAppAssigned { get { throw null; } } public static Azure.Communication.Administration.Models.AssignmentStatus ThirdPartyAppAssigned { get { throw null; } } public static Azure.Communication.Administration.Models.AssignmentStatus Unassigned { get { throw null; } } public static Azure.Communication.Administration.Models.AssignmentStatus Unknown { get { throw null; } } public static Azure.Communication.Administration.Models.AssignmentStatus UserAssigned { get { throw null; } } public bool Equals(Azure.Communication.Administration.Models.AssignmentStatus other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.Administration.Models.AssignmentStatus left, Azure.Communication.Administration.Models.AssignmentStatus right) { throw null; } public static implicit operator Azure.Communication.Administration.Models.AssignmentStatus (string value) { throw null; } public static bool operator !=(Azure.Communication.Administration.Models.AssignmentStatus left, Azure.Communication.Administration.Models.AssignmentStatus right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct CapabilitiesUpdateStatus : System.IEquatable<Azure.Communication.Administration.Models.CapabilitiesUpdateStatus> { private readonly object _dummy; private readonly int _dummyPrimitive; public CapabilitiesUpdateStatus(string value) { throw null; } public static Azure.Communication.Administration.Models.CapabilitiesUpdateStatus Complete { get { throw null; } } public static Azure.Communication.Administration.Models.CapabilitiesUpdateStatus Error { get { throw null; } } public static Azure.Communication.Administration.Models.CapabilitiesUpdateStatus InProgress { get { throw null; } } public static Azure.Communication.Administration.Models.CapabilitiesUpdateStatus Pending { get { throw null; } } public bool Equals(Azure.Communication.Administration.Models.CapabilitiesUpdateStatus other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.Administration.Models.CapabilitiesUpdateStatus left, Azure.Communication.Administration.Models.CapabilitiesUpdateStatus right) { throw null; } public static implicit operator Azure.Communication.Administration.Models.CapabilitiesUpdateStatus (string value) { throw null; } public static bool operator !=(Azure.Communication.Administration.Models.CapabilitiesUpdateStatus left, Azure.Communication.Administration.Models.CapabilitiesUpdateStatus right) { throw null; } public override string ToString() { throw null; } } public partial class CarrierDetails { internal CarrierDetails() { } public string LocalizedName { get { throw null; } } public string Name { get { throw null; } } } public partial class CommunicationUserToken { internal CommunicationUserToken() { } public System.DateTimeOffset ExpiresOn { get { throw null; } } public string Token { get { throw null; } } public Azure.Communication.CommunicationUser User { get { throw null; } } } public partial class CreateSearchOptions { public CreateSearchOptions(string displayName, string description, System.Collections.Generic.IEnumerable<string> phonePlanIds, string areaCode) { } public string AreaCode { get { throw null; } } public string Description { get { throw null; } } public string DisplayName { get { throw null; } } public System.Collections.Generic.IList<Azure.Communication.Administration.Models.LocationOptionsDetails> LocationOptions { get { throw null; } } public System.Collections.Generic.IList<string> PhonePlanIds { get { throw null; } } public int? Quantity { get { throw null; } set { } } } public partial class CreateSearchResponse { internal CreateSearchResponse() { } public string SearchId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct CurrencyType : System.IEquatable<Azure.Communication.Administration.Models.CurrencyType> { private readonly object _dummy; private readonly int _dummyPrimitive; public CurrencyType(string value) { throw null; } public static Azure.Communication.Administration.Models.CurrencyType USD { get { throw null; } } public bool Equals(Azure.Communication.Administration.Models.CurrencyType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.Administration.Models.CurrencyType left, Azure.Communication.Administration.Models.CurrencyType right) { throw null; } public static implicit operator Azure.Communication.Administration.Models.CurrencyType (string value) { throw null; } public static bool operator !=(Azure.Communication.Administration.Models.CurrencyType left, Azure.Communication.Administration.Models.CurrencyType right) { throw null; } public override string ToString() { throw null; } } public partial class LocationOptions { public LocationOptions() { } public string LabelId { get { throw null; } set { } } public string LabelName { get { throw null; } set { } } public System.Collections.Generic.IList<Azure.Communication.Administration.Models.LocationOptionsDetails> Options { get { throw null; } } } public partial class LocationOptionsDetails { public LocationOptionsDetails() { } public System.Collections.Generic.IList<Azure.Communication.Administration.Models.LocationOptions> LocationOptions { get { throw null; } } public string Name { get { throw null; } set { } } public string Value { get { throw null; } set { } } } public partial class LocationOptionsQuery { public LocationOptionsQuery() { } public string LabelId { get { throw null; } set { } } public string OptionsValue { get { throw null; } set { } } } public partial class LocationOptionsResponse { internal LocationOptionsResponse() { } public Azure.Communication.Administration.Models.LocationOptions LocationOptions { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct LocationType : System.IEquatable<Azure.Communication.Administration.Models.LocationType> { private readonly object _dummy; private readonly int _dummyPrimitive; public LocationType(string value) { throw null; } public static Azure.Communication.Administration.Models.LocationType CivicAddress { get { throw null; } } public static Azure.Communication.Administration.Models.LocationType NotRequired { get { throw null; } } public static Azure.Communication.Administration.Models.LocationType Selection { get { throw null; } } public bool Equals(Azure.Communication.Administration.Models.LocationType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.Administration.Models.LocationType left, Azure.Communication.Administration.Models.LocationType right) { throw null; } public static implicit operator Azure.Communication.Administration.Models.LocationType (string value) { throw null; } public static bool operator !=(Azure.Communication.Administration.Models.LocationType left, Azure.Communication.Administration.Models.LocationType right) { throw null; } public override string ToString() { throw null; } } public partial class NumberConfigurationResponse { internal NumberConfigurationResponse() { } public Azure.Communication.Administration.Models.PstnConfiguration PstnConfiguration { get { throw null; } } } public partial class NumberUpdateCapabilities { public NumberUpdateCapabilities() { } public System.Collections.Generic.IList<Azure.Communication.Administration.Models.PhoneNumberCapability> Add { get { throw null; } } public System.Collections.Generic.IList<Azure.Communication.Administration.Models.PhoneNumberCapability> Remove { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct PhoneNumberCapability : System.IEquatable<Azure.Communication.Administration.Models.PhoneNumberCapability> { private readonly object _dummy; private readonly int _dummyPrimitive; public PhoneNumberCapability(string value) { throw null; } public static Azure.Communication.Administration.Models.PhoneNumberCapability A2PSmsCapable { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability A2PSmsEnabled { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability Azure { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability Calling { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability ConferenceAssignment { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability FirstPartyAppAssignment { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability FirstPartyVoiceAppAssignment { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability Geographic { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability InboundA2PSms { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability InboundCalling { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability InboundP2PSms { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability NonGeographic { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability Office365 { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability OutboundA2PSms { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability OutboundCalling { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability OutboundP2PSms { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability P2PSmsCapable { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability P2PSmsEnabled { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability Premium { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability ThirdPartyAppAssignment { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability TollCalling { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability TollFree { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability TollFreeCalling { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberCapability UserAssignment { get { throw null; } } public bool Equals(Azure.Communication.Administration.Models.PhoneNumberCapability other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.Administration.Models.PhoneNumberCapability left, Azure.Communication.Administration.Models.PhoneNumberCapability right) { throw null; } public static implicit operator Azure.Communication.Administration.Models.PhoneNumberCapability (string value) { throw null; } public static bool operator !=(Azure.Communication.Administration.Models.PhoneNumberCapability left, Azure.Communication.Administration.Models.PhoneNumberCapability right) { throw null; } public override string ToString() { throw null; } } public partial class PhoneNumberCountries { internal PhoneNumberCountries() { } public System.Collections.Generic.IReadOnlyList<Azure.Communication.Administration.Models.PhoneNumberCountry> Countries { get { throw null; } } public string NextLink { get { throw null; } } } public partial class PhoneNumberCountry { internal PhoneNumberCountry() { } public string CountryCode { get { throw null; } } public string LocalizedName { get { throw null; } } } public partial class PhoneNumberEntities { internal PhoneNumberEntities() { } public System.Collections.Generic.IReadOnlyList<Azure.Communication.Administration.Models.PhoneNumberEntity> Entities { get { throw null; } } public string NextLink { get { throw null; } } } public partial class PhoneNumberEntity { internal PhoneNumberEntity() { } public System.DateTimeOffset? CreatedAt { get { throw null; } } public string DisplayName { get { throw null; } } public System.DateTimeOffset? FocDate { get { throw null; } } public string Id { get { throw null; } } public int? Quantity { get { throw null; } } public int? QuantityObtained { get { throw null; } } public string Status { get { throw null; } } } public partial class PhoneNumberRelease { internal PhoneNumberRelease() { } public System.DateTimeOffset? CreatedAt { get { throw null; } } public string ErrorMessage { get { throw null; } } public System.Collections.Generic.IReadOnlyDictionary<string, Azure.Communication.Administration.Models.PhoneNumberReleaseDetails> PhoneNumberReleaseStatusDetails { get { throw null; } } public string ReleaseId { get { throw null; } } public Azure.Communication.Administration.Models.ReleaseStatus? Status { get { throw null; } } } public partial class PhoneNumberReleaseDetails { internal PhoneNumberReleaseDetails() { } public int? ErrorCode { get { throw null; } } public Azure.Communication.Administration.Models.PhoneNumberReleaseStatus? Status { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct PhoneNumberReleaseStatus : System.IEquatable<Azure.Communication.Administration.Models.PhoneNumberReleaseStatus> { private readonly object _dummy; private readonly int _dummyPrimitive; public PhoneNumberReleaseStatus(string value) { throw null; } public static Azure.Communication.Administration.Models.PhoneNumberReleaseStatus Error { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberReleaseStatus InProgress { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberReleaseStatus Pending { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberReleaseStatus Success { get { throw null; } } public bool Equals(Azure.Communication.Administration.Models.PhoneNumberReleaseStatus other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.Administration.Models.PhoneNumberReleaseStatus left, Azure.Communication.Administration.Models.PhoneNumberReleaseStatus right) { throw null; } public static implicit operator Azure.Communication.Administration.Models.PhoneNumberReleaseStatus (string value) { throw null; } public static bool operator !=(Azure.Communication.Administration.Models.PhoneNumberReleaseStatus left, Azure.Communication.Administration.Models.PhoneNumberReleaseStatus right) { throw null; } public override string ToString() { throw null; } } public partial class PhoneNumberSearch { internal PhoneNumberSearch() { } public string AreaCode { get { throw null; } } public System.DateTimeOffset? CreatedAt { get { throw null; } } public string Description { get { throw null; } } public string DisplayName { get { throw null; } } public int? ErrorCode { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.Communication.Administration.Models.LocationOptionsDetails> LocationOptions { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> PhoneNumbers { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> PhonePlanIds { get { throw null; } } public int? Quantity { get { throw null; } } public System.DateTimeOffset? ReservationExpiryDate { get { throw null; } } public string SearchId { get { throw null; } } public Azure.Communication.Administration.Models.SearchStatus? Status { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct PhoneNumberType : System.IEquatable<Azure.Communication.Administration.Models.PhoneNumberType> { private readonly object _dummy; private readonly int _dummyPrimitive; public PhoneNumberType(string value) { throw null; } public static Azure.Communication.Administration.Models.PhoneNumberType Geographic { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberType Indirect { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberType TollFree { get { throw null; } } public static Azure.Communication.Administration.Models.PhoneNumberType Unknown { get { throw null; } } public bool Equals(Azure.Communication.Administration.Models.PhoneNumberType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.Administration.Models.PhoneNumberType left, Azure.Communication.Administration.Models.PhoneNumberType right) { throw null; } public static implicit operator Azure.Communication.Administration.Models.PhoneNumberType (string value) { throw null; } public static bool operator !=(Azure.Communication.Administration.Models.PhoneNumberType left, Azure.Communication.Administration.Models.PhoneNumberType right) { throw null; } public override string ToString() { throw null; } } public partial class PhonePlan { internal PhonePlan() { } public System.Collections.Generic.IReadOnlyList<string> AreaCodes { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.Communication.Administration.Models.PhoneNumberCapability> Capabilities { get { throw null; } } public string LocalizedName { get { throw null; } } public Azure.Communication.Administration.Models.LocationType LocationType { get { throw null; } } public int? MaximumSearchSize { get { throw null; } } public string PhonePlanId { get { throw null; } } } public partial class PhonePlanGroup { internal PhonePlanGroup() { } public Azure.Communication.Administration.Models.CarrierDetails CarrierDetails { get { throw null; } } public string LocalizedDescription { get { throw null; } } public string LocalizedName { get { throw null; } } public Azure.Communication.Administration.Models.PhoneNumberType? PhoneNumberType { get { throw null; } } public string PhonePlanGroupId { get { throw null; } } public Azure.Communication.Administration.Models.RateInformation RateInformation { get { throw null; } } } public partial class PhonePlanGroups { internal PhonePlanGroups() { } public string NextLink { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.Communication.Administration.Models.PhonePlanGroup> PhonePlanGroupsValue { get { throw null; } } } public partial class PhonePlansResponse { internal PhonePlansResponse() { } public string NextLink { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.Communication.Administration.Models.PhonePlan> PhonePlans { get { throw null; } } } public partial class PstnConfiguration { public PstnConfiguration(string callbackUrl) { } public string ApplicationId { get { throw null; } set { } } public string CallbackUrl { get { throw null; } set { } } } public partial class RateInformation { internal RateInformation() { } public Azure.Communication.Administration.Models.CurrencyType? CurrencyType { get { throw null; } } public double? MonthlyRate { get { throw null; } } public string RateErrorMessage { get { throw null; } } } public partial class ReleaseResponse { internal ReleaseResponse() { } public string ReleaseId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ReleaseStatus : System.IEquatable<Azure.Communication.Administration.Models.ReleaseStatus> { private readonly object _dummy; private readonly int _dummyPrimitive; public ReleaseStatus(string value) { throw null; } public static Azure.Communication.Administration.Models.ReleaseStatus Complete { get { throw null; } } public static Azure.Communication.Administration.Models.ReleaseStatus Expired { get { throw null; } } public static Azure.Communication.Administration.Models.ReleaseStatus Failed { get { throw null; } } public static Azure.Communication.Administration.Models.ReleaseStatus InProgress { get { throw null; } } public static Azure.Communication.Administration.Models.ReleaseStatus Pending { get { throw null; } } public bool Equals(Azure.Communication.Administration.Models.ReleaseStatus other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.Administration.Models.ReleaseStatus left, Azure.Communication.Administration.Models.ReleaseStatus right) { throw null; } public static implicit operator Azure.Communication.Administration.Models.ReleaseStatus (string value) { throw null; } public static bool operator !=(Azure.Communication.Administration.Models.ReleaseStatus left, Azure.Communication.Administration.Models.ReleaseStatus right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct SearchStatus : System.IEquatable<Azure.Communication.Administration.Models.SearchStatus> { private readonly object _dummy; private readonly int _dummyPrimitive; public SearchStatus(string value) { throw null; } public static Azure.Communication.Administration.Models.SearchStatus Cancelled { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus Cancelling { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus Completing { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus Error { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus Expired { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus Expiring { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus InProgress { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus Manual { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus Pending { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus PurchasePending { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus Refreshing { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus Reserved { get { throw null; } } public static Azure.Communication.Administration.Models.SearchStatus Success { get { throw null; } } public bool Equals(Azure.Communication.Administration.Models.SearchStatus other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Communication.Administration.Models.SearchStatus left, Azure.Communication.Administration.Models.SearchStatus right) { throw null; } public static implicit operator Azure.Communication.Administration.Models.SearchStatus (string value) { throw null; } public static bool operator !=(Azure.Communication.Administration.Models.SearchStatus left, Azure.Communication.Administration.Models.SearchStatus right) { throw null; } public override string ToString() { throw null; } } public partial class UpdateNumberCapabilitiesResponse { internal UpdateNumberCapabilitiesResponse() { } public string CapabilitiesUpdateId { get { throw null; } } } public partial class UpdatePhoneNumberCapabilitiesResponse { internal UpdatePhoneNumberCapabilitiesResponse() { } public string CapabilitiesUpdateId { get { throw null; } } public Azure.Communication.Administration.Models.CapabilitiesUpdateStatus? CapabilitiesUpdateStatus { get { throw null; } } public System.DateTimeOffset? CreatedAt { get { throw null; } } public System.Collections.Generic.IReadOnlyDictionary<string, Azure.Communication.Administration.Models.NumberUpdateCapabilities> PhoneNumberCapabilitiesUpdates { get { throw null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Bars2Db.Expressions; using Bars2Db.Extensions; using Bars2Db.Mapping; namespace Bars2Db.Reflection { public class MemberAccessor { public MemberAccessor(TypeAccessor typeAccessor, string memberName) { TypeAccessor = typeAccessor; if (memberName.IndexOf('.') < 0) { SetSimple(Expression.PropertyOrField(Expression.Constant(null, typeAccessor.Type), memberName).Member); } else { IsComplex = true; HasGetter = true; HasSetter = true; var members = memberName.Split('.'); var objParam = Expression.Parameter(TypeAccessor.Type, "obj"); var expr = (Expression) objParam; var infos = members.Select(m => { expr = Expression.PropertyOrField(expr, m); return new { member = ((MemberExpression) expr).Member, type = expr.Type }; }).ToArray(); var lastInfo = infos[infos.Length - 1]; MemberInfo = lastInfo.member; Type = lastInfo.type; var checkNull = infos.Take(infos.Length - 1) .Any(info => info.type.IsClassEx() || info.type.IsNullable()); // Build getter. // { if (checkNull) { var ret = Expression.Variable(Type, "ret"); Func<Expression, int, Expression> makeGetter = null; makeGetter = (ex, i) => { var info = infos[i]; var next = Expression.MakeMemberAccess(ex, info.member); if (i == infos.Length - 1) return Expression.Assign(ret, next); if (next.Type.IsClassEx() || next.Type.IsNullable()) { var local = Expression.Variable(next.Type); return Expression.Block( new[] {local}, Expression.Assign(local, next) as Expression, Expression.IfThen( Expression.NotEqual(local, Expression.Constant(null)), makeGetter(local, i + 1))); } return makeGetter(next, i + 1); }; expr = Expression.Block( new[] {ret}, Expression.Assign(ret, new DefaultValueExpression(MappingSchema.Default, Type)), makeGetter(objParam, 0), ret); } else { expr = objParam; foreach (var info in infos) expr = Expression.MakeMemberAccess(expr, info.member); } GetterExpression = Expression.Lambda(expr, objParam); } // Build setter. // { HasSetter = !infos.Any( info => { var propertyInfo = info.member as PropertyInfo; return propertyInfo != null && propertyInfo.GetSetMethodEx(true) == null; }); var valueParam = Expression.Parameter(Type, "value"); if (HasSetter) { if (checkNull) { var vars = new List<ParameterExpression>(); var exprs = new List<Expression>(); Action<Expression, int> makeSetter = null; makeSetter = (ex, i) => { var info = infos[i]; var next = Expression.MakeMemberAccess(ex, info.member); if (i == infos.Length - 1) { exprs.Add(Expression.Assign(next, valueParam)); } else { if (next.Type.IsClassEx() || next.Type.IsNullable()) { var local = Expression.Variable(next.Type); vars.Add(local); exprs.Add(Expression.Assign(local, next)); exprs.Add( Expression.IfThen( Expression.Equal(local, Expression.Constant(null)), Expression.Block( Expression.Assign(local, Expression.New(local.Type)), Expression.Assign(next, local)))); makeSetter(local, i + 1); } else { makeSetter(next, i + 1); } } }; makeSetter(objParam, 0); expr = Expression.Block(vars, exprs); } else { expr = objParam; foreach (var info in infos) expr = Expression.MakeMemberAccess(expr, info.member); expr = Expression.Assign(expr, valueParam); } SetterExpression = Expression.Lambda(expr, objParam, valueParam); } else { var fakeParam = Expression.Parameter(typeof(int)); SetterExpression = Expression.Lambda( Expression.Block( new[] {fakeParam}, Expression.Assign(fakeParam, Expression.Constant(0))), objParam, valueParam); } } } SetExpressions(); } public MemberAccessor(TypeAccessor typeAccessor, MemberInfo memberInfo) { TypeAccessor = typeAccessor; SetSimple(memberInfo); SetExpressions(); } private void SetSimple(MemberInfo memberInfo) { MemberInfo = memberInfo; var propertyInfo = MemberInfo as PropertyInfo; Type = propertyInfo?.PropertyType ?? ((FieldInfo) MemberInfo).FieldType; HasGetter = true; var info = memberInfo as PropertyInfo; if (info != null) HasSetter = info.GetSetMethodEx(true) != null; else HasSetter = !((FieldInfo) memberInfo).IsInitOnly; var objParam = Expression.Parameter(TypeAccessor.Type, "obj"); var valueParam = Expression.Parameter(Type, "value"); GetterExpression = Expression.Lambda(Expression.MakeMemberAccess(objParam, memberInfo), objParam); if (HasSetter) { SetterExpression = Expression.Lambda( Expression.Assign(GetterExpression.Body, valueParam), objParam, valueParam); } else { var fakeParam = Expression.Parameter(typeof(int)); SetterExpression = Expression.Lambda( Expression.Block( new[] {fakeParam}, Expression.Assign(fakeParam, Expression.Constant(0))), objParam, valueParam); } } private void SetExpressions() { var objParam = Expression.Parameter(typeof(object), "obj"); var getterExpr = GetterExpression.GetBody(Expression.Convert(objParam, TypeAccessor.Type)); var getter = Expression.Lambda<Func<object, object>>(Expression.Convert(getterExpr, typeof(object)), objParam); Getter = getter.Compile(); var valueParam = Expression.Parameter(typeof(object), "value"); var setterExpr = SetterExpression.GetBody( Expression.Convert(objParam, TypeAccessor.Type), Expression.Convert(valueParam, Type)); var setter = Expression.Lambda<Action<object, object>>(setterExpr, objParam, valueParam); Setter = setter.Compile(); } #region Public Properties public MemberInfo MemberInfo { get; private set; } public TypeAccessor TypeAccessor { get; } public bool HasGetter { get; private set; } public bool HasSetter { get; private set; } public Type Type { get; private set; } public bool IsComplex { get; private set; } public LambdaExpression GetterExpression { get; private set; } public LambdaExpression SetterExpression { get; private set; } public Func<object, object> Getter { get; private set; } public Action<object, object> Setter { get; private set; } public string Name => MemberInfo.Name; #endregion #region Public Methods public T GetAttribute<T>() where T : Attribute { var attrs = MemberInfo.GetCustomAttributesEx(typeof(T), true); return attrs.Length > 0 ? (T) attrs[0] : null; } public T[] GetAttributes<T>() where T : Attribute { Array attrs = MemberInfo.GetCustomAttributesEx(typeof(T), true); return attrs.Length > 0 ? (T[]) attrs : null; } public object[] GetAttributes() { var attrs = MemberInfo.GetCustomAttributesEx(true); return attrs.Length > 0 ? attrs : null; } public T[] GetTypeAttributes<T>() where T : Attribute { return TypeAccessor.Type.GetAttributes<T>(); } #endregion #region Set/Get Value public virtual object GetValue(object o) { return Getter(o); } public virtual void SetValue(object o, object value) { Setter(o, value); } #endregion } }