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 System; using System.Diagnostics; using System.Xml.Schema; using System.Collections; namespace System.Xml { /// <summary> /// Implementations of XmlRawWriter are intended to be wrapped by the XmlWellFormedWriter. The /// well-formed writer performs many checks in behalf of the raw writer, and keeps state that the /// raw writer otherwise would have to keep. Therefore, the well-formed writer will call the /// XmlRawWriter using the following rules, in order to make raw writers easier to implement: /// /// 1. The well-formed writer keeps a stack of element names, and always calls /// WriteEndElement(string, string, string) instead of WriteEndElement(). /// 2. The well-formed writer tracks namespaces, and will pass himself in via the /// WellformedWriter property. It is used in the XmlRawWriter's implementation of IXmlNamespaceResolver. /// Thus, LookupPrefix does not have to be implemented. /// 3. The well-formed writer tracks write states, so the raw writer doesn't need to. /// 4. The well-formed writer will always call StartElementContent. /// 5. The well-formed writer will always call WriteNamespaceDeclaration for namespace nodes, /// rather than calling WriteStartAttribute(). If the writer is supporting namespace declarations in chunks /// (SupportsNamespaceDeclarationInChunks is true), the XmlWellFormedWriter will call WriteStartNamespaceDeclaration, /// then any method that can be used to write out a value of an attribute (WriteString, WriteChars, WriteRaw, WriteCharEntity...) /// and then WriteEndNamespaceDeclaration - instead of just a single WriteNamespaceDeclaration call. This feature will be /// supported by raw writers serializing to text that wish to preserve the attribute value escaping etc. /// 6. The well-formed writer guarantees a well-formed document, including correct call sequences, /// correct namespaces, and correct document rule enforcement. /// 7. All element and attribute names will be fully resolved and validated. Null will never be /// passed for any of the name parts. /// 8. The well-formed writer keeps track of xml:space and xml:lang. /// 9. The well-formed writer verifies NmToken, Name, and QName values and calls WriteString(). /// </summary> internal abstract partial class XmlRawWriter : XmlWriter { // // Fields // // base64 converter protected XmlRawWriterBase64Encoder base64Encoder; // namespace resolver protected IXmlNamespaceResolver resolver; // // XmlWriter implementation // // Raw writers do not have to track whether this is a well-formed document. public override void WriteStartDocument() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override void WriteStartDocument(bool standalone) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override void WriteEndDocument() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to keep a stack of element names. public override void WriteEndElement() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to keep a stack of element names. public override void WriteFullEndElement() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // By default, convert base64 value to string and call WriteString. public override void WriteBase64(byte[] buffer, int index, int count) { if (base64Encoder == null) { base64Encoder = new XmlRawWriterBase64Encoder(this); } // Encode will call WriteRaw to write out the encoded characters base64Encoder.Encode(buffer, index, count); } // Raw writers do not have to keep track of namespaces. public override string LookupPrefix(string ns) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to keep track of write states. public override WriteState WriteState { get { throw new InvalidOperationException(SR.Xml_InvalidOperation); } } // Raw writers do not have to keep track of xml:space. public override XmlSpace XmlSpace { get { throw new InvalidOperationException(SR.Xml_InvalidOperation); } } // Raw writers do not have to keep track of xml:lang. public override string XmlLang { get { throw new InvalidOperationException(SR.Xml_InvalidOperation); } } // Raw writers do not have to verify NmToken values. public override void WriteNmToken(string name) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to verify Name values. public override void WriteName(string name) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to verify QName values. public override void WriteQualifiedName(string localName, string ns) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Override in order to handle Xml simple typed values and to pass resolver for QName values public override void WriteValue(object value) { if (value == null) { throw new ArgumentNullException("value"); } WriteString(XmlUntypedStringConverter.Instance.ToString(value, resolver)); } // Override in order to handle Xml simple typed values and to pass resolver for QName values public override void WriteValue(string value) { WriteString(value); } public override void WriteValue(DateTimeOffset value) { // For compatibility with custom writers, XmlWriter writes DateTimeOffset as DateTime. // Our internal writers should use the DateTimeOffset-String conversion from XmlConvert. WriteString(XmlConvert.ToString(value)); } // Copying to XmlRawWriter is not currently supported. public override void WriteAttributes(XmlReader reader, bool defattr) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override void WriteNode(XmlReader reader, bool defattr) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // // XmlRawWriter methods and properties // // Get and set the namespace resolver that's used by this RawWriter to resolve prefixes. internal virtual IXmlNamespaceResolver NamespaceResolver { get { return resolver; } set { resolver = value; } } // Write the xml declaration. This must be the first call. internal abstract void WriteXmlDeclaration(XmlStandalone standalone); internal abstract void WriteXmlDeclaration(string xmldecl); // Called after an element's attributes have been enumerated, but before any children have been // enumerated. This method must always be called, even for empty elements. internal abstract void StartElementContent(); // Called before a root element is written (before the WriteStartElement call) // the conformanceLevel specifies the current conformance level the writer is operating with. internal virtual void OnRootElement(ConformanceLevel conformanceLevel) { } // WriteEndElement() and WriteFullEndElement() overloads, in which caller gives the full name of the // element, so that raw writers do not need to keep a stack of element names. This method should // always be called instead of WriteEndElement() or WriteFullEndElement() without parameters. internal abstract void WriteEndElement(string prefix, string localName, string ns); internal abstract void WriteFullEndElement(string prefix, string localName, string ns); internal virtual void WriteQualifiedName(string prefix, string localName, string ns) { if (prefix.Length != 0) { WriteString(prefix); WriteString(":"); } WriteString(localName); } // This method must be called instead of WriteStartAttribute() for namespaces. internal abstract void WriteNamespaceDeclaration(string prefix, string ns); // When true, the XmlWellFormedWriter will call: // 1) WriteStartNamespaceDeclaration // 2) any method that can be used to write out a value of an attribute: WriteString, WriteChars, WriteRaw, WriteCharEntity... // 3) WriteEndNamespaceDeclaration // instead of just a single WriteNamespaceDeclaration call. // // This feature will be supported by raw writers serializing to text that wish to preserve the attribute value escaping and entities. internal virtual bool SupportsNamespaceDeclarationInChunks { get { return false; } } internal virtual void WriteStartNamespaceDeclaration(string prefix) { throw new NotSupportedException(); } internal virtual void WriteEndNamespaceDeclaration() { throw new NotSupportedException(); } // This is called when the remainder of a base64 value should be output. internal virtual void WriteEndBase64() { // The Flush will call WriteRaw to write out the rest of the encoded characters base64Encoder.Flush(); } } }
using System; using Xunit; using static System.FormattableString; namespace SourceCode.Clay.Net.Tests { public static class TemplateCompilerTests { private class Formattable : IFormattable { public string ToString(string format, IFormatProvider formatProvider) => "f" + format; } private struct NotFormattable { public override string ToString() => "Foo!"; } private enum NormalEnum { First = 0, Second = 1 } [Flags] private enum FlagsEnum { None = 0, First = 1, Second = 2 } private struct Values { public int Field; public int? NullableField; public NotFormattable? NotFormattable; public Formattable Formattable; public string[] Collection; public NormalEnum Normal; public FlagsEnum Flags; public NormalEnum? NormalNullable; } [Fact] public static void TemplateCompiler_Compile_Constant() { var template = RawUriTemplate.Parse("/test/url?some=value&foo=bar"); Func<object, string> compiled = TemplateCompiler.Compile<object>(template); string result = compiled(new object()); Assert.Equal("/test/url?some=value&foo=bar", result); } [Fact] public static void TemplateCompiler_Compile_Path() { var values = new Values() { Field = 100 }; var template = RawUriTemplate.Parse("/test/{Field}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("/test/100", result); } [Fact] public static void TemplateCompiler_Compile_NullablePath() { var values = new Values() { NullableField = 100 }; var template = RawUriTemplate.Parse("/test/{NullableField:x}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("/test/64", result); } [Fact] public static void TemplateCompiler_Compile_DefaultPath() { var values = new Values(); var template = RawUriTemplate.Parse("/test/{NullableField=Default}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("/test/Default", result); } [Fact] public static void TemplateCompiler_Compile_Query() { var values = new Values() { Field = 100 }; var template = RawUriTemplate.Parse("?f={Field}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f=100", result); } [Fact] public static void TemplateCompiler_Compile_NullableQuery() { var values = new Values() { NullableField = 100 }; var template = RawUriTemplate.Parse("?f={NullableField:x}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f=64", result); } [Fact] public static void TemplateCompiler_Compile_NullableQuery_Null() { var values = new Values(); var template = RawUriTemplate.Parse("?f={NullableField:x}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("", result); } [Fact] public static void TemplateCompiler_Compile_DefaultQuery() { var values = new Values(); var template = RawUriTemplate.Parse("?f={NullableField=Default}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f=Default", result); } [Fact] public static void TemplateCompiler_Compile_CollectionQuery_Empty() { var values = new Values(); var template = RawUriTemplate.Parse("?f={Collection[]}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("", result); } [Fact] public static void TemplateCompiler_Compile_CollectionQuery() { var values = new Values() { Collection = new[] { "Test", null, "Foo" } }; var template = RawUriTemplate.Parse("?f={Collection[]}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f=Test&f&f=Foo", result); } [Fact] public static void TemplateCompiler_Compile_CollectionQuery_NotCollection() { var template = RawUriTemplate.Parse("?f={Field[]}"); InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => TemplateCompiler.Compile<Values>(template)); Assert.Equal("An enumerable was expected for Field.", ex.Message); } [Fact] public static void TemplateCompiler_Compile_EnumQuery() { var values = new Values() { Normal = NormalEnum.Second }; var template = RawUriTemplate.Parse("?f={Normal.First}&s={Normal.Second}&t={Normal.Second}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?s&t", result); } [Fact] public static void TemplateCompiler_Compile_EnumQuery_NotEnum() { var template = RawUriTemplate.Parse("?f={Field.First}"); InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() => TemplateCompiler.Compile<Values>(template)); Assert.Equal("An enum was expected for Field.", ex.Message); } [Fact] public static void TemplateCompiler_Compile_EnumQuery_Named() { var values = new Values() { Normal = NormalEnum.Second }; var template = RawUriTemplate.Parse("?f={Normal.First}&s={Normal.Second=second}&t={Normal.Second}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?s=second&t", result); } [Fact] public static void TemplateCompiler_Compile_EnumQuery_Nullable() { var values = new Values() { NormalNullable = NormalEnum.First }; var template = RawUriTemplate.Parse("?f={NormalNullable.First}&s={NormalNullable.Second}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f", result); } [Fact] public static void TemplateCompiler_Compile_EnumQuery_Nullable_Null() { var values = new Values(); var template = RawUriTemplate.Parse("?f={NormalNullable.First}&s={NormalNullable.Second}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("", result); } [Fact] public static void TemplateCompiler_Compile_EnumQuery_Nullable_Named() { var values = new Values() { NormalNullable = NormalEnum.First }; var template = RawUriTemplate.Parse("?f={NormalNullable.First=foo}&s={NormalNullable.Second=bar}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f=foo", result); } [Fact] public static void TemplateCompiler_Compile_EnumQuery_Nullable_Named_Null() { var values = new Values(); var template = RawUriTemplate.Parse("?f={NormalNullable.First=foo}&s={NormalNullable.Second=bar}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("", result); } [Fact] public static void TemplateCompiler_Compile_EnumQuery_Flags() { var values = new Values() { Flags = FlagsEnum.First | FlagsEnum.Second }; var template = RawUriTemplate.Parse("?f={Flags.First}&s={Flags.Second}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f&s", result); } [Fact] public static void TemplateCompiler_Compile_EnumQuery_Flags_Named() { var values = new Values() { Flags = FlagsEnum.First | FlagsEnum.Second }; var template = RawUriTemplate.Parse("?f={Flags.First=first}&s={Flags.Second=baz}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f=first&s=baz", result); } [Fact] public static void TemplateCompiler_Compile_NotFormattable() { var values = new Values() { NotFormattable = new NotFormattable() }; var template = RawUriTemplate.Parse("?f={NotFormattable}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f=Foo%21", result); } [Fact] public static void TemplateCompiler_Compile_NotFormattable_Null() { var values = new Values(); var template = RawUriTemplate.Parse("?f={NotFormattable}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("", result); } [Fact] public static void TemplateCompiler_Compile_NotFormattable_Default() { var values = new Values(); var template = RawUriTemplate.Parse("?f={NotFormattable=Value}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f=Value", result); } [Fact] public static void TemplateCompiler_Compile_Formattable() { var values = new Values() { Formattable = new Formattable() }; var template = RawUriTemplate.Parse("?f={Formattable:x}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f=fx", result); } [Fact] public static void TemplateCompiler_Compile_Formattable_Null() { var values = new Values(); var template = RawUriTemplate.Parse("?f={Formattable:x}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("", result); } [Fact] public static void TemplateCompiler_Compile_Formattable_Default() { var values = new Values(); var template = RawUriTemplate.Parse("?f={Formattable=Value}"); Func<Values, string> compiled = TemplateCompiler.Compile<Values>(template); string result = compiled(values); Assert.Equal("?f=Value", result); } } }
using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis; namespace Orleans.CodeGenerator { [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "These property names reflect type names.")] internal class WellKnownTypes { public WellKnownTypes(Compilation compilation) { Attribute = Type("System.Attribute"); Action_2 = Type("System.Action`2"); AlwaysInterleaveAttribute = Type("Orleans.Concurrency.AlwaysInterleaveAttribute"); CopierMethodAttribute = Type("Orleans.CodeGeneration.CopierMethodAttribute"); DeserializerMethodAttribute = Type("Orleans.CodeGeneration.DeserializerMethodAttribute"); Delegate = compilation.GetSpecialType(SpecialType.System_Delegate); DebuggerStepThroughAttribute = Type("System.Diagnostics.DebuggerStepThroughAttribute"); Exception = Type("System.Exception"); ExcludeFromCodeCoverageAttribute = Type("System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute"); FormatterServices = Type("System.Runtime.Serialization.FormatterServices"); FieldInfo = Type("System.Reflection.FieldInfo"); Func_2 = Type("System.Func`2"); GeneratedCodeAttribute = Type("System.CodeDom.Compiler.GeneratedCodeAttribute"); Grain = Type("Orleans.Grain"); GrainFactoryBase = Type("Orleans.CodeGeneration.GrainFactoryBase"); GrainOfT = Type("Orleans.Grain`1"); GrainReference = Type("Orleans.Runtime.GrainReference"); GrainReferenceAttribute = Type("Orleans.CodeGeneration.GrainReferenceAttribute"); IAddressable = Type("Orleans.Runtime.IAddressable"); IGrainContext = Type("Orleans.Runtime.IGrainContext"); ICopyContext = Type("Orleans.Serialization.ICopyContext"); IDeserializationContext = Type("Orleans.Serialization.IDeserializationContext"); IFieldUtils = Type("Orleans.Serialization.IFieldUtils"); IGrain = Type("Orleans.IGrain"); IGrainExtension = Type("Orleans.Runtime.IGrainExtension"); IGrainExtensionMethodInvoker = Type("Orleans.CodeGeneration.IGrainExtensionMethodInvoker"); IGrainMethodInvoker = Type("Orleans.CodeGeneration.IGrainMethodInvoker"); IGrainObserver = Type("Orleans.IGrainObserver"); IGrainWithGuidCompoundKey = Type("Orleans.IGrainWithGuidCompoundKey"); IGrainWithGuidKey = Type("Orleans.IGrainWithGuidKey"); IGrainWithIntegerCompoundKey = Type("Orleans.IGrainWithIntegerCompoundKey"); IGrainWithIntegerKey = Type("Orleans.IGrainWithIntegerKey"); IGrainWithStringKey = Type("Orleans.IGrainWithStringKey"); Immutable_1 = Type("Orleans.Concurrency.Immutable`1"); ImmutableAttribute = Type("Orleans.Concurrency.ImmutableAttribute"); Int32 = compilation.GetSpecialType(SpecialType.System_Int32); InvokeMethodOptions = Type("Orleans.CodeGeneration.InvokeMethodOptions"); InvokeMethodRequest = Type("Orleans.CodeGeneration.InvokeMethodRequest"); IOnDeserialized = Type("Orleans.Serialization.IOnDeserialized"); ISerializationContext = Type("Orleans.Serialization.ISerializationContext"); ISystemTarget = Type("Orleans.ISystemTarget"); MarshalByRefObject = Type("System.MarshalByRefObject"); MethodInvokerAttribute = Type("Orleans.CodeGeneration.MethodInvokerAttribute"); NonSerializedAttribute = Type("System.NonSerializedAttribute"); NotImplementedException = Type("System.NotImplementedException"); Object = compilation.GetSpecialType(SpecialType.System_Object); ObsoleteAttribute = Type("System.ObsoleteAttribute"); OneWayAttribute = Type("Orleans.Concurrency.OneWayAttribute"); ReadOnlyAttribute = Type("Orleans.Concurrency.ReadOnlyAttribute"); SerializableAttribute = Type("System.SerializableAttribute"); SerializerAttribute = Type("Orleans.CodeGeneration.SerializerAttribute"); SerializerMethodAttribute = Type("Orleans.CodeGeneration.SerializerMethodAttribute"); SerializerFeature = Type("Orleans.Serialization.SerializerFeature"); String = compilation.GetSpecialType(SpecialType.System_String); Task = Type("System.Threading.Tasks.Task"); Task_1 = Type("System.Threading.Tasks.Task`1"); ValueTask = OptionalType("System.Threading.Tasks.ValueTask"); TimeSpan = Type("System.TimeSpan"); IPAddress = Type("System.Net.IPAddress"); IPEndPoint = Type("System.Net.IPEndPoint"); SiloAddress = Type("Orleans.Runtime.SiloAddress"); GrainId = Type("Orleans.Runtime.GrainId"); GrainInterfaceMetadata = Type("Orleans.Metadata.GrainInterfaceMetadata"); GrainClassMetadata = Type("Orleans.Metadata.GrainClassMetadata"); IFeaturePopulator_1 = Type("Orleans.Metadata.IFeaturePopulator`1"); FeaturePopulatorAttribute = Type("Orleans.Metadata.FeaturePopulatorAttribute"); GrainClassFeature = Type("Orleans.Metadata.GrainClassFeature"); GrainInterfaceFeature = Type("Orleans.Metadata.GrainInterfaceFeature"); ActivationId = Type("Orleans.Runtime.ActivationId"); ActivationAddress = Type("Orleans.Runtime.ActivationAddress"); CorrelationId = OptionalType("Orleans.Runtime.CorrelationId"); CancellationToken = Type("System.Threading.CancellationToken"); TransactionAttribute = Type("Orleans.TransactionAttribute"); TransactionOption = Type("Orleans.TransactionOption"); this.Type = Type("System.Type"); TypeCodeOverrideAttribute = Type("Orleans.CodeGeneration.TypeCodeOverrideAttribute"); MethodIdAttribute = Type("Orleans.CodeGeneration.MethodIdAttribute"); UInt16 = compilation.GetSpecialType(SpecialType.System_UInt16); UnorderedAttribute = Type("Orleans.Concurrency.UnorderedAttribute"); ValueTypeSetter_2 = Type("Orleans.Serialization.ValueTypeSetter`2"); VersionAttribute = Type("Orleans.CodeGeneration.VersionAttribute"); Void = compilation.GetSpecialType(SpecialType.System_Void); GenericMethodInvoker = OptionalType("Orleans.CodeGeneration.GenericMethodInvoker"); KnownAssemblyAttribute = Type("Orleans.CodeGeneration.KnownAssemblyAttribute"); KnownBaseTypeAttribute = Type("Orleans.CodeGeneration.KnownBaseTypeAttribute"); ConsiderForCodeGenerationAttribute = Type("Orleans.CodeGeneration.ConsiderForCodeGenerationAttribute"); OrleansCodeGenerationTargetAttribute = Type("Orleans.CodeGeneration.OrleansCodeGenerationTargetAttribute"); SupportedRefAsmBaseTypes = new[] { Type("System.Collections.Generic.EqualityComparer`1"), Type("System.Collections.Generic.Comparer`1") }; TupleTypes = new[] { Type("System.Tuple`1"), Type("System.Tuple`2"), Type("System.Tuple`3"), Type("System.Tuple`4"), Type("System.Tuple`5"), Type("System.Tuple`6"), Type("System.Tuple`7"), Type("System.Tuple`8"), }; INamedTypeSymbol Type(string type) { var result = ResolveType(type); if (result == null) { throw new InvalidOperationException($"Unable to find type with metadata name \"{type}\"."); } return result; } OptionalType OptionalType(string type) { var result = ResolveType(type); if (result == null) return None.Instance; return new Some(result); } INamedTypeSymbol ResolveType(string type) { var result = compilation.GetTypeByMetadataName(type); if (result == null) { foreach (var reference in compilation.References) { var asm = compilation.GetAssemblyOrModuleSymbol(reference) as IAssemblySymbol; if (asm == null) continue; result = asm.GetTypeByMetadataName(type); if (result != null) break; } } return result; } } public INamedTypeSymbol[] SupportedRefAsmBaseTypes { get; } public INamedTypeSymbol[] TupleTypes { get; } public INamedTypeSymbol Attribute { get; } public INamedTypeSymbol TimeSpan { get; } public INamedTypeSymbol GrainClassMetadata { get; } public INamedTypeSymbol GrainInterfaceMetadata { get; } public INamedTypeSymbol IPAddress { get; } public INamedTypeSymbol IPEndPoint { get; } public INamedTypeSymbol SiloAddress { get; } public INamedTypeSymbol GrainId { get; } public INamedTypeSymbol IFeaturePopulator_1 { get; } public INamedTypeSymbol FeaturePopulatorAttribute { get; } public INamedTypeSymbol GrainInterfaceFeature { get; } public INamedTypeSymbol ActivationId { get; } public INamedTypeSymbol ActivationAddress { get; } public OptionalType CorrelationId { get; } public INamedTypeSymbol CancellationToken { get; } public INamedTypeSymbol Action_2 { get; } public INamedTypeSymbol AlwaysInterleaveAttribute { get; } public INamedTypeSymbol CopierMethodAttribute { get; } public INamedTypeSymbol Delegate { get; } public INamedTypeSymbol DeserializerMethodAttribute { get; } public INamedTypeSymbol DebuggerStepThroughAttribute { get; } public INamedTypeSymbol Exception { get; } public INamedTypeSymbol ExcludeFromCodeCoverageAttribute { get; } public INamedTypeSymbol FormatterServices { get; } public INamedTypeSymbol FieldInfo { get; } public INamedTypeSymbol Func_2 { get; } public INamedTypeSymbol GeneratedCodeAttribute { get; } public OptionalType GenericMethodInvoker { get; } public INamedTypeSymbol Grain { get; } public INamedTypeSymbol GrainFactoryBase { get; } public INamedTypeSymbol GrainOfT { get; } public INamedTypeSymbol GrainReference { get; } public INamedTypeSymbol GrainReferenceAttribute { get; } public INamedTypeSymbol IAddressable { get; } public INamedTypeSymbol ICopyContext { get; } public INamedTypeSymbol IGrainContext { get; } public INamedTypeSymbol IDeserializationContext { get; } public INamedTypeSymbol IFieldUtils { get; } public INamedTypeSymbol IGrain { get; } public INamedTypeSymbol IGrainExtension { get; } public INamedTypeSymbol IGrainExtensionMethodInvoker { get; } public INamedTypeSymbol GrainClassFeature { get; } public INamedTypeSymbol SerializerFeature { get; } public INamedTypeSymbol IGrainMethodInvoker { get; } public INamedTypeSymbol IGrainObserver { get; } public INamedTypeSymbol IGrainWithGuidCompoundKey { get; } public INamedTypeSymbol IGrainWithGuidKey { get; } public INamedTypeSymbol IGrainWithIntegerCompoundKey { get; } public INamedTypeSymbol IGrainWithIntegerKey { get; } public INamedTypeSymbol IGrainWithStringKey { get; } public INamedTypeSymbol Immutable_1 { get; } public INamedTypeSymbol ImmutableAttribute { get; } public INamedTypeSymbol Int32 { get; } public INamedTypeSymbol InvokeMethodOptions { get; } public INamedTypeSymbol InvokeMethodRequest { get; } public INamedTypeSymbol IOnDeserialized { get; } public INamedTypeSymbol ISerializationContext { get; } public INamedTypeSymbol ISystemTarget { get; } public INamedTypeSymbol MarshalByRefObject { get; } public INamedTypeSymbol MethodInvokerAttribute { get; } public INamedTypeSymbol NonSerializedAttribute { get; } public INamedTypeSymbol NotImplementedException { get; } public INamedTypeSymbol Object { get; } public INamedTypeSymbol ObsoleteAttribute { get; } public INamedTypeSymbol OneWayAttribute { get; } public INamedTypeSymbol ReadOnlyAttribute { get; } public INamedTypeSymbol SerializableAttribute { get; } public INamedTypeSymbol SerializerAttribute { get; } public INamedTypeSymbol SerializerMethodAttribute { get; } public INamedTypeSymbol String { get; } public INamedTypeSymbol Task { get; } public INamedTypeSymbol Task_1 { get; } public OptionalType ValueTask { get; } public INamedTypeSymbol TransactionAttribute { get; } public INamedTypeSymbol TransactionOption { get; } public INamedTypeSymbol Type { get; } public INamedTypeSymbol TypeCodeOverrideAttribute { get; } public INamedTypeSymbol MethodIdAttribute { get; } public INamedTypeSymbol UInt16 { get; } public INamedTypeSymbol UnorderedAttribute { get; } public INamedTypeSymbol ValueTypeSetter_2 { get; } public INamedTypeSymbol VersionAttribute { get; } public INamedTypeSymbol Void { get; } public INamedTypeSymbol KnownAssemblyAttribute { get; } public INamedTypeSymbol KnownBaseTypeAttribute { get; } public INamedTypeSymbol ConsiderForCodeGenerationAttribute { get; } public INamedTypeSymbol OrleansCodeGenerationTargetAttribute { get; } public abstract class OptionalType { } public sealed class None : OptionalType { public static None Instance { get; } = new None(); } public sealed class Some : OptionalType { public Some(INamedTypeSymbol value) { Value = value; } public INamedTypeSymbol Value { get; } } } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using System; using System.Collections; using System.Collections.Generic; namespace Fungus { public struct PortraitState { public bool onScreen; public bool dimmed; public DisplayType display; public Sprite portrait; public RectTransform position; public FacingDirection facing; public Image portraitImage; } public enum DisplayType { None, Show, Hide, Replace, MoveToFront } public enum FacingDirection { None, Left, Right } public enum PositionOffset { None, OffsetLeft, OffsetRight } [CommandInfo("Narrative", "Portrait", "Controls a character portrait. ")] public class Portrait : Command { [Tooltip("Stage to display portrait on")] public Stage stage; [Tooltip("Display type")] public DisplayType display; [Tooltip("Character to display")] public Character character; [Tooltip("Character to swap with")] public Character replacedCharacter; [Tooltip("Portrait to display")] public Sprite portrait; [Tooltip("Move the portrait from/to this offset position")] public PositionOffset offset; [Tooltip("Move the portrait from this position")] public RectTransform fromPosition; [Tooltip("Move the portrait to this positoin")] public RectTransform toPosition; [Tooltip("Direction character is facing")] public FacingDirection facing; [Tooltip("Use Default Settings")] public bool useDefaultSettings = true; [Tooltip("Fade Duration")] public float fadeDuration = 0.5f; [Tooltip("Movement Duration")] public float moveDuration = 1f; [Tooltip("Shift Offset")] public Vector2 shiftOffset; [Tooltip("Move")] public bool move; [Tooltip("Start from offset")] public bool shiftIntoPlace; [Tooltip("Wait until the tween has finished before executing the next command")] public bool waitUntilFinished = false; // Timer for waitUntilFinished functionality protected float waitTimer; public override void OnEnter() { // If no display specified, do nothing if (display == DisplayType.None) { Continue(); return; } // If no character specified, do nothing if (character == null) { Continue(); return; } // If Replace and no replaced character specified, do nothing if (display == DisplayType.Replace && replacedCharacter == null) { Continue(); return; } // Selected "use default Portrait Stage" if (stage == null) // Default portrait stage selected { if (stage == null) // If no default specified, try to get any portrait stage in the scene { stage = GameObject.FindObjectOfType<Stage>(); } } // If portrait stage does not exist, do nothing if (stage == null) { Continue(); return; } // Use default settings if (useDefaultSettings) { fadeDuration = stage.fadeDuration; moveDuration = stage.moveDuration; shiftOffset = stage.shiftOffset; } if (character.state.portraitImage == null) { CreatePortraitObject(character, stage); } // if no previous portrait, use default portrait if (character.state.portrait == null) { character.state.portrait = character.profileSprite; } // Selected "use previous portrait" if (portrait == null) { portrait = character.state.portrait; } // if no previous position, use default position if (character.state.position == null) { character.state.position = stage.defaultPosition.rectTransform; } // Selected "use previous position" if (toPosition == null) { toPosition = character.state.position; } if (replacedCharacter != null) { // if no previous position, use default position if (replacedCharacter.state.position == null) { replacedCharacter.state.position = stage.defaultPosition.rectTransform; } } // If swapping, use replaced character's position if (display == DisplayType.Replace) { toPosition = replacedCharacter.state.position; } // Selected "use previous position" if (fromPosition == null) { fromPosition = character.state.position; } // if portrait not moving, use from position is same as to position if (!move) { fromPosition = toPosition; } if (display == DisplayType.Hide) { fromPosition = character.state.position; } // if no previous facing direction, use default facing direction if (character.state.facing == FacingDirection.None) { character.state.facing = character.portraitsFace; } // Selected "use previous facing direction" if (facing == FacingDirection.None) { facing = character.state.facing; } switch(display) { case (DisplayType.Show): Show(character, fromPosition, toPosition); character.state.onScreen = true; if (!stage.charactersOnStage.Contains(character)) { stage.charactersOnStage.Add(character); } break; case (DisplayType.Hide): Hide(character, fromPosition, toPosition); character.state.onScreen = false; stage.charactersOnStage.Remove(character); break; case (DisplayType.Replace): Show(character, fromPosition, toPosition); Hide(replacedCharacter, replacedCharacter.state.position, replacedCharacter.state.position); character.state.onScreen = true; replacedCharacter.state.onScreen = false; stage.charactersOnStage.Add(character); stage.charactersOnStage.Remove(replacedCharacter); break; case (DisplayType.MoveToFront): MoveToFront(character); break; } if (display == DisplayType.Replace) { character.state.display = DisplayType.Show; replacedCharacter.state.display = DisplayType.Hide; } else { character.state.display = display; } character.state.portrait = portrait; character.state.facing = facing; character.state.position = toPosition; waitTimer = 0f; if (!waitUntilFinished) { Continue(); } else { StartCoroutine(WaitUntilFinished(fadeDuration)); } } protected virtual IEnumerator WaitUntilFinished(float duration) { // Wait until the timer has expired // Any method can modify this timer variable to delay continuing. waitTimer = duration; while (waitTimer > 0f) { waitTimer -= Time.deltaTime; yield return null; } Continue(); } protected virtual void CreatePortraitObject(Character character, Stage stage) { // Create a new portrait object GameObject portraitObj = new GameObject(character.name, typeof(RectTransform), typeof(CanvasRenderer), typeof(Image)); // Set it to be a child of the stage portraitObj.transform.SetParent(stage.portraitCanvas.transform, true); // Configure the portrait image Image portraitImage = portraitObj.GetComponent<Image>(); portraitImage.preserveAspect = true; portraitImage.sprite = character.profileSprite; portraitImage.color = new Color(1f, 1f, 1f, 0f); // LeanTween doesn't handle 0 duration properly float duration = (fadeDuration > 0f) ? fadeDuration : float.Epsilon; // Fade in character image (first time) LeanTween.alpha(portraitImage.transform as RectTransform, 1f, duration).setEase(stage.fadeEaseType); // Tell character about portrait image character.state.portraitImage = portraitImage; } protected void SetupPortrait(Character character, RectTransform fromPosition) { SetRectTransform(character.state.portraitImage.rectTransform, fromPosition); if (character.state.facing != character.portraitsFace) { character.state.portraitImage.rectTransform.localScale = new Vector3(-1f, 1f, 1f); } else { character.state.portraitImage.rectTransform.localScale = new Vector3(1f, 1f, 1f); } if (facing != character.portraitsFace) { character.state.portraitImage.rectTransform.localScale = new Vector3(-1f, 1f, 1f); } else { character.state.portraitImage.rectTransform.localScale = new Vector3(1f, 1f, 1f); } } public static void SetRectTransform(RectTransform oldRectTransform, RectTransform newRectTransform) { oldRectTransform.eulerAngles = newRectTransform.eulerAngles; oldRectTransform.position = newRectTransform.position; oldRectTransform.rotation = newRectTransform.rotation; oldRectTransform.anchoredPosition = newRectTransform.anchoredPosition; oldRectTransform.sizeDelta = newRectTransform.sizeDelta; oldRectTransform.anchorMax = newRectTransform.anchorMax; oldRectTransform.anchorMin = newRectTransform.anchorMin; oldRectTransform.pivot = newRectTransform.pivot; oldRectTransform.localScale = newRectTransform.localScale; } protected void Show(Character character, RectTransform fromPosition, RectTransform toPosition) { if (shiftIntoPlace) { fromPosition = Instantiate(toPosition) as RectTransform; if (offset == PositionOffset.OffsetLeft) { fromPosition.anchoredPosition = new Vector2(fromPosition.anchoredPosition.x - Mathf.Abs(shiftOffset.x), fromPosition.anchoredPosition.y - Mathf.Abs(shiftOffset.y)); } else if (offset == PositionOffset.OffsetRight) { fromPosition.anchoredPosition = new Vector2(fromPosition.anchoredPosition.x + Mathf.Abs(shiftOffset.x), fromPosition.anchoredPosition.y + Mathf.Abs(shiftOffset.y)); } else { fromPosition.anchoredPosition = new Vector2(fromPosition.anchoredPosition.x, fromPosition.anchoredPosition.y); } } SetupPortrait(character, fromPosition); // LeanTween doesn't handle 0 duration properly float duration = (fadeDuration > 0f) ? fadeDuration : float.Epsilon; // Fade out a duplicate of the existing portrait image if (character.state.portraitImage != null) { GameObject tempGO = GameObject.Instantiate(character.state.portraitImage.gameObject); tempGO.transform.SetParent(character.state.portraitImage.transform, false); tempGO.transform.localPosition = Vector3.zero; tempGO.transform.localScale = character.state.position.localScale; Image tempImage = tempGO.GetComponent<Image>(); tempImage.sprite = character.state.portraitImage.sprite; tempImage.preserveAspect = true; tempImage.color = character.state.portraitImage.color; LeanTween.alpha(tempImage.rectTransform, 0f, duration).setEase(stage.fadeEaseType).setOnComplete(() => { Destroy(tempGO); }); } // Fade in the new sprite image character.state.portraitImage.sprite = portrait; character.state.portraitImage.color = new Color(1f, 1f, 1f, 0f); LeanTween.alpha(character.state.portraitImage.rectTransform, 1f, duration).setEase(stage.fadeEaseType); DoMoveTween(character, fromPosition, toPosition); } protected void Hide(Character character, RectTransform fromPosition, RectTransform toPosition) { if (character.state.display == DisplayType.None) { return; } SetupPortrait(character, fromPosition); // LeanTween doesn't handle 0 duration properly float duration = (fadeDuration > 0f) ? fadeDuration : float.Epsilon; LeanTween.alpha(character.state.portraitImage.rectTransform, 0f, duration).setEase(stage.fadeEaseType); DoMoveTween(character, fromPosition, toPosition); } protected void MoveToFront(Character character) { character.state.portraitImage.transform.SetSiblingIndex(character.state.portraitImage.transform.parent.childCount); } protected void DoMoveTween(Character character, RectTransform fromPosition, RectTransform toPosition) { // LeanTween doesn't handle 0 duration properly float duration = (moveDuration > 0f) ? moveDuration : float.Epsilon; // LeanTween.move uses the anchoredPosition, so all position images must have the same anchor position LeanTween.move(character.state.portraitImage.gameObject, toPosition.position, duration).setEase(stage.fadeEaseType); if (waitUntilFinished) { waitTimer = duration; } } public static void SetDimmed(Character character, Stage stage, bool dimmedState) { if (character.state.dimmed == dimmedState) { return; } character.state.dimmed = dimmedState; Color targetColor = dimmedState ? new Color(0.5f, 0.5f, 0.5f, 1f) : Color.white; // LeanTween doesn't handle 0 duration properly float duration = (stage.fadeDuration > 0f) ? stage.fadeDuration : float.Epsilon; LeanTween.color(character.state.portraitImage.rectTransform, targetColor, duration).setEase(stage.fadeEaseType); } public override string GetSummary() { if (display == DisplayType.None && character == null) { return "Error: No character or display selected"; } else if (display == DisplayType.None) { return "Error: No display selected"; } else if (character == null) { return "Error: No character selected"; } string displaySummary = ""; string characterSummary = ""; string fromPositionSummary = ""; string toPositionSummary = ""; string stageSummary = ""; string portraitSummary = ""; string facingSummary = ""; displaySummary = StringFormatter.SplitCamelCase(display.ToString()); if (display == DisplayType.Replace) { if (replacedCharacter != null) { displaySummary += " \"" + replacedCharacter.name + "\" with"; } } characterSummary = character.name; if (stage != null) { stageSummary = " on \"" + stage.name + "\""; } if (portrait != null) { portraitSummary = " " + portrait.name; } if (shiftIntoPlace) { if (offset != 0) { fromPositionSummary = offset.ToString(); fromPositionSummary = " from " + "\"" + fromPositionSummary + "\""; } } else if (fromPosition != null) { fromPositionSummary = " from " + "\"" + fromPosition.name + "\""; } if (toPosition != null) { string toPositionPrefixSummary = ""; if (move) { toPositionPrefixSummary = " to "; } else { toPositionPrefixSummary = " at "; } toPositionSummary = toPositionPrefixSummary + "\"" + toPosition.name + "\""; } if (facing != FacingDirection.None) { if (facing == FacingDirection.Left) { facingSummary = "<--"; } if (facing == FacingDirection.Right) { facingSummary = "-->"; } facingSummary = " facing \"" + facingSummary + "\""; } return displaySummary + " \"" + characterSummary + portraitSummary + "\"" + stageSummary + facingSummary + fromPositionSummary + toPositionSummary; } public override Color GetButtonColor() { return new Color32(230, 200, 250, 255); } public override void OnCommandAdded(Block parentBlock) { //Default to display type: show display = DisplayType.Show; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>TensorboardRun</c> resource.</summary> public sealed partial class TensorboardRunName : gax::IResourceName, sys::IEquatable<TensorboardRunName> { /// <summary>The possible contents of <see cref="TensorboardRunName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c> /// projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}</c> /// . /// </summary> ProjectLocationTensorboardExperimentRun = 1, } private static gax::PathTemplate s_projectLocationTensorboardExperimentRun = new gax::PathTemplate("projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}"); /// <summary>Creates a <see cref="TensorboardRunName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TensorboardRunName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static TensorboardRunName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TensorboardRunName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TensorboardRunName"/> with the pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorboardId">The <c>Tensorboard</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="experimentId">The <c>Experiment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="runId">The <c>Run</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TensorboardRunName"/> constructed from the provided ids.</returns> public static TensorboardRunName FromProjectLocationTensorboardExperimentRun(string projectId, string locationId, string tensorboardId, string experimentId, string runId) => new TensorboardRunName(ResourceNameType.ProjectLocationTensorboardExperimentRun, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tensorboardId: gax::GaxPreconditions.CheckNotNullOrEmpty(tensorboardId, nameof(tensorboardId)), experimentId: gax::GaxPreconditions.CheckNotNullOrEmpty(experimentId, nameof(experimentId)), runId: gax::GaxPreconditions.CheckNotNullOrEmpty(runId, nameof(runId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TensorboardRunName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorboardId">The <c>Tensorboard</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="experimentId">The <c>Experiment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="runId">The <c>Run</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TensorboardRunName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}</c> /// . /// </returns> public static string Format(string projectId, string locationId, string tensorboardId, string experimentId, string runId) => FormatProjectLocationTensorboardExperimentRun(projectId, locationId, tensorboardId, experimentId, runId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TensorboardRunName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorboardId">The <c>Tensorboard</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="experimentId">The <c>Experiment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="runId">The <c>Run</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TensorboardRunName"/> with pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}</c> /// . /// </returns> public static string FormatProjectLocationTensorboardExperimentRun(string projectId, string locationId, string tensorboardId, string experimentId, string runId) => s_projectLocationTensorboardExperimentRun.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tensorboardId, nameof(tensorboardId)), gax::GaxPreconditions.CheckNotNullOrEmpty(experimentId, nameof(experimentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(runId, nameof(runId))); /// <summary> /// Parses the given resource name string into a new <see cref="TensorboardRunName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="tensorboardRunName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TensorboardRunName"/> if successful.</returns> public static TensorboardRunName Parse(string tensorboardRunName) => Parse(tensorboardRunName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TensorboardRunName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tensorboardRunName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TensorboardRunName"/> if successful.</returns> public static TensorboardRunName Parse(string tensorboardRunName, bool allowUnparsed) => TryParse(tensorboardRunName, allowUnparsed, out TensorboardRunName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TensorboardRunName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="tensorboardRunName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TensorboardRunName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string tensorboardRunName, out TensorboardRunName result) => TryParse(tensorboardRunName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TensorboardRunName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tensorboardRunName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TensorboardRunName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string tensorboardRunName, bool allowUnparsed, out TensorboardRunName result) { gax::GaxPreconditions.CheckNotNull(tensorboardRunName, nameof(tensorboardRunName)); gax::TemplatedResourceName resourceName; if (s_projectLocationTensorboardExperimentRun.TryParseName(tensorboardRunName, out resourceName)) { result = FromProjectLocationTensorboardExperimentRun(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(tensorboardRunName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TensorboardRunName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string experimentId = null, string locationId = null, string projectId = null, string runId = null, string tensorboardId = null) { Type = type; UnparsedResource = unparsedResourceName; ExperimentId = experimentId; LocationId = locationId; ProjectId = projectId; RunId = runId; TensorboardId = tensorboardId; } /// <summary> /// Constructs a new instance of a <see cref="TensorboardRunName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tensorboardId">The <c>Tensorboard</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="experimentId">The <c>Experiment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="runId">The <c>Run</c> ID. Must not be <c>null</c> or empty.</param> public TensorboardRunName(string projectId, string locationId, string tensorboardId, string experimentId, string runId) : this(ResourceNameType.ProjectLocationTensorboardExperimentRun, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tensorboardId: gax::GaxPreconditions.CheckNotNullOrEmpty(tensorboardId, nameof(tensorboardId)), experimentId: gax::GaxPreconditions.CheckNotNullOrEmpty(experimentId, nameof(experimentId)), runId: gax::GaxPreconditions.CheckNotNullOrEmpty(runId, nameof(runId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Experiment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ExperimentId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Run</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string RunId { get; } /// <summary> /// The <c>Tensorboard</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TensorboardId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationTensorboardExperimentRun: return s_projectLocationTensorboardExperimentRun.Expand(ProjectId, LocationId, TensorboardId, ExperimentId, RunId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TensorboardRunName); /// <inheritdoc/> public bool Equals(TensorboardRunName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TensorboardRunName a, TensorboardRunName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TensorboardRunName a, TensorboardRunName b) => !(a == b); } public partial class TensorboardRun { /// <summary> /// <see cref="gcav::TensorboardRunName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::TensorboardRunName TensorboardRunName { get => string.IsNullOrEmpty(Name) ? null : gcav::TensorboardRunName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Linq.Expressions; namespace Python.Runtime { /// <summary> /// Represents a generic Python object. The methods of this class are /// generally equivalent to the Python "abstract object API". See /// PY2: https://docs.python.org/2/c-api/object.html /// PY3: https://docs.python.org/3/c-api/object.html /// for details. /// </summary> [Serializable] public partial class PyObject : DynamicObject, IEnumerable<PyObject>, IDisposable { #if TRACE_ALLOC /// <summary> /// Trace stack for PyObject's construction /// </summary> public StackTrace Traceback { get; private set; } #endif protected internal IntPtr obj = IntPtr.Zero; internal BorrowedReference Reference => new BorrowedReference(obj); /// <summary> /// PyObject Constructor /// </summary> /// <remarks> /// Creates a new PyObject from an IntPtr object reference. Note that /// the PyObject instance assumes ownership of the object reference /// and the reference will be DECREFed when the PyObject is garbage /// collected or explicitly disposed. /// </remarks> public PyObject(IntPtr ptr) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); obj = ptr; Finalizer.Instance.ThrottledCollect(); #if TRACE_ALLOC Traceback = new StackTrace(1); #endif } [Obsolete("for testing purposes only")] internal PyObject(IntPtr ptr, bool skipCollect) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); obj = ptr; if (!skipCollect) Finalizer.Instance.ThrottledCollect(); #if TRACE_ALLOC Traceback = new StackTrace(1); #endif } /// <summary> /// Creates new <see cref="PyObject"/> pointing to the same object as /// the <paramref name="reference"/>. Increments refcount, allowing <see cref="PyObject"/> /// to have ownership over its own reference. /// </summary> internal PyObject(BorrowedReference reference) { if (reference.IsNull) throw new ArgumentNullException(nameof(reference)); obj = Runtime.SelfIncRef(reference.DangerousGetAddress()); Finalizer.Instance.ThrottledCollect(); #if TRACE_ALLOC Traceback = new StackTrace(1); #endif } // Ensure that encapsulated Python object is decref'ed appropriately // when the managed wrapper is garbage-collected. ~PyObject() { if (obj == IntPtr.Zero) { return; } Finalizer.Instance.AddFinalizedObject(ref obj); } /// <summary> /// Handle Property /// </summary> /// <remarks> /// Gets the native handle of the underlying Python object. This /// value is generally for internal use by the PythonNet runtime. /// </remarks> public IntPtr Handle { get { return obj; } } /// <summary> /// Gets raw Python proxy for this object (bypasses all conversions, /// except <c>null</c> &lt;==&gt; <c>None</c>) /// </summary> /// <remarks> /// Given an arbitrary managed object, return a Python instance that /// reflects the managed object. /// </remarks> public static PyObject FromManagedObject(object ob) { // Special case: if ob is null, we return None. if (ob == null) { Runtime.XIncref(Runtime.PyNone); return new PyObject(Runtime.PyNone); } IntPtr op = CLRObject.GetInstHandle(ob); return new PyObject(op); } /// <summary> /// AsManagedObject Method /// </summary> /// <remarks> /// Return a managed object of the given type, based on the /// value of the Python object. /// </remarks> public object AsManagedObject(Type t) { object result; if (!Converter.ToManaged(obj, t, out result, true)) { throw new InvalidCastException("cannot convert object to target type", new PythonException()); } return result; } /// <summary> /// As Method /// </summary> /// <remarks> /// Return a managed object of the given type, based on the /// value of the Python object. /// </remarks> public T As<T>() { if (typeof(T) == typeof(PyObject) || typeof(T) == typeof(object)) { return (T)(this as object); } return (T)AsManagedObject(typeof(T)); } internal bool IsDisposed => obj == IntPtr.Zero; /// <summary> /// Dispose Method /// </summary> /// <remarks> /// The Dispose method provides a way to explicitly release the /// Python object represented by a PyObject instance. It is a good /// idea to call Dispose on PyObjects that wrap resources that are /// limited or need strict lifetime control. Otherwise, references /// to Python objects will not be released until a managed garbage /// collection occurs. /// </remarks> protected virtual void Dispose(bool disposing) { if (this.obj == IntPtr.Zero) { return; } if (Runtime.Py_IsInitialized() == 0) throw new InvalidOperationException("Python runtime must be initialized"); if (!Runtime.IsFinalizing) { long refcount = Runtime.Refcount(this.obj); Debug.Assert(refcount > 0, "Object refcount is 0 or less"); if (refcount == 1) { Runtime.PyErr_Fetch(out var errType, out var errVal, out var traceback); try { Runtime.XDecref(this.obj); Runtime.CheckExceptionOccurred(); } finally { // Python requires finalizers to preserve exception: // https://docs.python.org/3/extending/newtypes.html#finalization-and-de-allocation Runtime.PyErr_Restore(errType, errVal, traceback); } } else { Runtime.XDecref(this.obj); } } else { throw new InvalidOperationException("Runtime is already finalizing"); } this.obj = IntPtr.Zero; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// GetPythonType Method /// </summary> /// <remarks> /// Returns the Python type of the object. This method is equivalent /// to the Python expression: type(object). /// </remarks> public PyObject GetPythonType() { IntPtr tp = Runtime.PyObject_Type(obj); return new PyObject(tp); } /// <summary> /// TypeCheck Method /// </summary> /// <remarks> /// Returns true if the object o is of type typeOrClass or a subtype /// of typeOrClass. /// </remarks> public bool TypeCheck(PyObject typeOrClass) { if (typeOrClass == null) throw new ArgumentNullException(nameof(typeOrClass)); return Runtime.PyObject_TypeCheck(obj, typeOrClass.obj); } /// <summary> /// HasAttr Method /// </summary> /// <remarks> /// Returns true if the object has an attribute with the given name. /// </remarks> public bool HasAttr(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); return Runtime.PyObject_HasAttrString(Reference, name) != 0; } /// <summary> /// HasAttr Method /// </summary> /// <remarks> /// Returns true if the object has an attribute with the given name, /// where name is a PyObject wrapping a string or unicode object. /// </remarks> public bool HasAttr(PyObject name) { if (name == null) throw new ArgumentNullException(nameof(name)); return Runtime.PyObject_HasAttr(Reference, name.Reference) != 0; } /// <summary> /// GetAttr Method /// </summary> /// <remarks> /// Returns the named attribute of the Python object, or raises a /// PythonException if the attribute access fails. /// </remarks> public PyObject GetAttr(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); IntPtr op = Runtime.PyObject_GetAttrString(obj, name); if (op == IntPtr.Zero) { throw new PythonException(); } return new PyObject(op); } /// <summary> /// GetAttr Method. Returns fallback value if getting attribute fails for any reason. /// </summary> /// <remarks> /// Returns the named attribute of the Python object, or the given /// default object if the attribute access fails. /// </remarks> public PyObject GetAttr(string name, PyObject _default) { if (name == null) throw new ArgumentNullException(nameof(name)); IntPtr op = Runtime.PyObject_GetAttrString(obj, name); if (op == IntPtr.Zero) { Runtime.PyErr_Clear(); return _default; } return new PyObject(op); } /// <summary> /// GetAttr Method /// </summary> /// <remarks> /// Returns the named attribute of the Python object or raises a /// PythonException if the attribute access fails. The name argument /// is a PyObject wrapping a Python string or unicode object. /// </remarks> public PyObject GetAttr(PyObject name) { if (name == null) throw new ArgumentNullException(nameof(name)); IntPtr op = Runtime.PyObject_GetAttr(obj, name.obj); if (op == IntPtr.Zero) { throw new PythonException(); } return new PyObject(op); } /// <summary> /// GetAttr Method /// </summary> /// <remarks> /// Returns the named attribute of the Python object, or the given /// default object if the attribute access fails. The name argument /// is a PyObject wrapping a Python string or unicode object. /// </remarks> public PyObject GetAttr(PyObject name, PyObject _default) { if (name == null) throw new ArgumentNullException(nameof(name)); IntPtr op = Runtime.PyObject_GetAttr(obj, name.obj); if (op == IntPtr.Zero) { Runtime.PyErr_Clear(); return _default; } return new PyObject(op); } /// <summary> /// SetAttr Method /// </summary> /// <remarks> /// Set an attribute of the object with the given name and value. This /// method throws a PythonException if the attribute set fails. /// </remarks> public void SetAttr(string name, PyObject value) { if (name == null) throw new ArgumentNullException(nameof(name)); if (value == null) throw new ArgumentNullException(nameof(value)); int r = Runtime.PyObject_SetAttrString(obj, name, value.obj); if (r < 0) { throw new PythonException(); } } /// <summary> /// SetAttr Method /// </summary> /// <remarks> /// Set an attribute of the object with the given name and value, /// where the name is a Python string or unicode object. This method /// throws a PythonException if the attribute set fails. /// </remarks> public void SetAttr(PyObject name, PyObject value) { if (name == null) throw new ArgumentNullException(nameof(name)); if (value == null) throw new ArgumentNullException(nameof(value)); int r = Runtime.PyObject_SetAttr(obj, name.obj, value.obj); if (r < 0) { throw new PythonException(); } } /// <summary> /// DelAttr Method /// </summary> /// <remarks> /// Delete the named attribute of the Python object. This method /// throws a PythonException if the attribute set fails. /// </remarks> public void DelAttr(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); int r = Runtime.PyObject_SetAttrString(obj, name, IntPtr.Zero); if (r < 0) { throw new PythonException(); } } /// <summary> /// DelAttr Method /// </summary> /// <remarks> /// Delete the named attribute of the Python object, where name is a /// PyObject wrapping a Python string or unicode object. This method /// throws a PythonException if the attribute set fails. /// </remarks> public void DelAttr(PyObject name) { if (name == null) throw new ArgumentNullException(nameof(name)); int r = Runtime.PyObject_SetAttr(obj, name.obj, IntPtr.Zero); if (r < 0) { throw new PythonException(); } } /// <summary> /// GetItem Method /// </summary> /// <remarks> /// For objects that support the Python sequence or mapping protocols, /// return the item at the given object index. This method raises a /// PythonException if the indexing operation fails. /// </remarks> public virtual PyObject GetItem(PyObject key) { if (key == null) throw new ArgumentNullException(nameof(key)); IntPtr op = Runtime.PyObject_GetItem(obj, key.obj); if (op == IntPtr.Zero) { throw new PythonException(); } return new PyObject(op); } /// <summary> /// GetItem Method /// </summary> /// <remarks> /// For objects that support the Python sequence or mapping protocols, /// return the item at the given string index. This method raises a /// PythonException if the indexing operation fails. /// </remarks> public virtual PyObject GetItem(string key) { if (key == null) throw new ArgumentNullException(nameof(key)); using (var pyKey = new PyString(key)) { return GetItem(pyKey); } } /// <summary> /// GetItem Method /// </summary> /// <remarks> /// For objects that support the Python sequence or mapping protocols, /// return the item at the given numeric index. This method raises a /// PythonException if the indexing operation fails. /// </remarks> public virtual PyObject GetItem(int index) { using (var key = new PyInt(index)) { return GetItem(key); } } /// <summary> /// SetItem Method /// </summary> /// <remarks> /// For objects that support the Python sequence or mapping protocols, /// set the item at the given object index to the given value. This /// method raises a PythonException if the set operation fails. /// </remarks> public virtual void SetItem(PyObject key, PyObject value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null) throw new ArgumentNullException(nameof(value)); int r = Runtime.PyObject_SetItem(obj, key.obj, value.obj); if (r < 0) { throw new PythonException(); } } /// <summary> /// SetItem Method /// </summary> /// <remarks> /// For objects that support the Python sequence or mapping protocols, /// set the item at the given string index to the given value. This /// method raises a PythonException if the set operation fails. /// </remarks> public virtual void SetItem(string key, PyObject value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null) throw new ArgumentNullException(nameof(value)); using (var pyKey = new PyString(key)) { SetItem(pyKey, value); } } /// <summary> /// SetItem Method /// </summary> /// <remarks> /// For objects that support the Python sequence or mapping protocols, /// set the item at the given numeric index to the given value. This /// method raises a PythonException if the set operation fails. /// </remarks> public virtual void SetItem(int index, PyObject value) { if (value == null) throw new ArgumentNullException(nameof(value)); using (var pyindex = new PyInt(index)) { SetItem(pyindex, value); } } /// <summary> /// DelItem Method /// </summary> /// <remarks> /// For objects that support the Python sequence or mapping protocols, /// delete the item at the given object index. This method raises a /// PythonException if the delete operation fails. /// </remarks> public virtual void DelItem(PyObject key) { if (key == null) throw new ArgumentNullException(nameof(key)); int r = Runtime.PyObject_DelItem(obj, key.obj); if (r < 0) { throw new PythonException(); } } /// <summary> /// DelItem Method /// </summary> /// <remarks> /// For objects that support the Python sequence or mapping protocols, /// delete the item at the given string index. This method raises a /// PythonException if the delete operation fails. /// </remarks> public virtual void DelItem(string key) { if (key == null) throw new ArgumentNullException(nameof(key)); using (var pyKey = new PyString(key)) { DelItem(pyKey); } } /// <summary> /// DelItem Method /// </summary> /// <remarks> /// For objects that support the Python sequence or mapping protocols, /// delete the item at the given numeric index. This method raises a /// PythonException if the delete operation fails. /// </remarks> public virtual void DelItem(int index) { using (var pyindex = new PyInt(index)) { DelItem(pyindex); } } /// <summary> /// Length Method /// </summary> /// <remarks> /// Returns the length for objects that support the Python sequence /// protocol, or 0 if the object does not support the protocol. /// </remarks> public virtual long Length() { var s = Runtime.PyObject_Size(obj); if (s < 0) { Runtime.PyErr_Clear(); return 0; } return s; } /// <summary> /// String Indexer /// </summary> /// <remarks> /// Provides a shorthand for the string versions of the GetItem and /// SetItem methods. /// </remarks> public virtual PyObject this[string key] { get { return GetItem(key); } set { SetItem(key, value); } } /// <summary> /// PyObject Indexer /// </summary> /// <remarks> /// Provides a shorthand for the object versions of the GetItem and /// SetItem methods. /// </remarks> public virtual PyObject this[PyObject key] { get { return GetItem(key); } set { SetItem(key, value); } } /// <summary> /// Numeric Indexer /// </summary> /// <remarks> /// Provides a shorthand for the numeric versions of the GetItem and /// SetItem methods. /// </remarks> public virtual PyObject this[int index] { get { return GetItem(index); } set { SetItem(index, value); } } /// <summary> /// GetIterator Method /// </summary> /// <remarks> /// Return a new (Python) iterator for the object. This is equivalent /// to the Python expression "iter(object)". A PythonException will be /// raised if the object cannot be iterated. /// </remarks> public PyObject GetIterator() { IntPtr r = Runtime.PyObject_GetIter(obj); if (r == IntPtr.Zero) { throw new PythonException(); } return new PyObject(r); } /// <summary> /// GetEnumerator Method /// </summary> /// <remarks> /// Return a new PyIter object for the object. This allows any iterable /// python object to be iterated over in C#. A PythonException will be /// raised if the object is not iterable. /// </remarks> public IEnumerator<PyObject> GetEnumerator() { return PyIter.GetIter(this); } IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); /// <summary> /// Invoke Method /// </summary> /// <remarks> /// Invoke the callable object with the given arguments, passed as a /// PyObject[]. A PythonException is raised if the invocation fails. /// </remarks> public PyObject Invoke(params PyObject[] args) { if (args == null) throw new ArgumentNullException(nameof(args)); if (args.Contains(null)) throw new ArgumentNullException(); var t = new PyTuple(args); IntPtr r = Runtime.PyObject_Call(obj, t.obj, IntPtr.Zero); t.Dispose(); if (r == IntPtr.Zero) { throw new PythonException(); } return new PyObject(r); } /// <summary> /// Invoke Method /// </summary> /// <remarks> /// Invoke the callable object with the given arguments, passed as a /// Python tuple. A PythonException is raised if the invocation fails. /// </remarks> public PyObject Invoke(PyTuple args) { if (args == null) throw new ArgumentNullException(nameof(args)); IntPtr r = Runtime.PyObject_Call(obj, args.obj, IntPtr.Zero); if (r == IntPtr.Zero) { throw new PythonException(); } return new PyObject(r); } /// <summary> /// Invoke Method /// </summary> /// <remarks> /// Invoke the callable object with the given positional and keyword /// arguments. A PythonException is raised if the invocation fails. /// </remarks> public PyObject Invoke(PyObject[] args, PyDict kw) { if (args == null) throw new ArgumentNullException(nameof(args)); if (args.Contains(null)) throw new ArgumentNullException(); var t = new PyTuple(args); IntPtr r = Runtime.PyObject_Call(obj, t.obj, kw?.obj ?? IntPtr.Zero); t.Dispose(); if (r == IntPtr.Zero) { throw new PythonException(); } return new PyObject(r); } /// <summary> /// Invoke Method /// </summary> /// <remarks> /// Invoke the callable object with the given positional and keyword /// arguments. A PythonException is raised if the invocation fails. /// </remarks> public PyObject Invoke(PyTuple args, PyDict kw) { if (args == null) throw new ArgumentNullException(nameof(args)); IntPtr r = Runtime.PyObject_Call(obj, args.obj, kw?.obj ?? IntPtr.Zero); if (r == IntPtr.Zero) { throw new PythonException(); } return new PyObject(r); } /// <summary> /// InvokeMethod Method /// </summary> /// <remarks> /// Invoke the named method of the object with the given arguments. /// A PythonException is raised if the invocation is unsuccessful. /// </remarks> public PyObject InvokeMethod(string name, params PyObject[] args) { if (name == null) throw new ArgumentNullException(nameof(name)); if (args == null) throw new ArgumentNullException(nameof(args)); if (args.Contains(null)) throw new ArgumentNullException(); PyObject method = GetAttr(name); PyObject result = method.Invoke(args); method.Dispose(); return result; } /// <summary> /// InvokeMethod Method /// </summary> /// <remarks> /// Invoke the named method of the object with the given arguments. /// A PythonException is raised if the invocation is unsuccessful. /// </remarks> public PyObject InvokeMethod(string name, PyTuple args) { if (name == null) throw new ArgumentNullException(nameof(name)); if (args == null) throw new ArgumentNullException(nameof(args)); PyObject method = GetAttr(name); PyObject result = method.Invoke(args); method.Dispose(); return result; } /// <summary> /// InvokeMethod Method /// </summary> /// <remarks> /// Invoke the named method of the object with the given arguments. /// A PythonException is raised if the invocation is unsuccessful. /// </remarks> public PyObject InvokeMethod(PyObject name, params PyObject[] args) { if (name == null) throw new ArgumentNullException(nameof(name)); if (args == null) throw new ArgumentNullException(nameof(args)); if (args.Contains(null)) throw new ArgumentNullException(); PyObject method = GetAttr(name); PyObject result = method.Invoke(args); method.Dispose(); return result; } /// <summary> /// InvokeMethod Method /// </summary> /// <remarks> /// Invoke the named method of the object with the given arguments. /// A PythonException is raised if the invocation is unsuccessful. /// </remarks> public PyObject InvokeMethod(PyObject name, PyTuple args) { if (name == null) throw new ArgumentNullException(nameof(name)); if (args == null) throw new ArgumentNullException(nameof(args)); PyObject method = GetAttr(name); PyObject result = method.Invoke(args); method.Dispose(); return result; } /// <summary> /// InvokeMethod Method /// </summary> /// <remarks> /// Invoke the named method of the object with the given arguments /// and keyword arguments. Keyword args are passed as a PyDict object. /// A PythonException is raised if the invocation is unsuccessful. /// </remarks> public PyObject InvokeMethod(string name, PyObject[] args, PyDict kw) { if (name == null) throw new ArgumentNullException(nameof(name)); if (args == null) throw new ArgumentNullException(nameof(args)); if (args.Contains(null)) throw new ArgumentNullException(); PyObject method = GetAttr(name); PyObject result = method.Invoke(args, kw); method.Dispose(); return result; } /// <summary> /// InvokeMethod Method /// </summary> /// <remarks> /// Invoke the named method of the object with the given arguments /// and keyword arguments. Keyword args are passed as a PyDict object. /// A PythonException is raised if the invocation is unsuccessful. /// </remarks> public PyObject InvokeMethod(string name, PyTuple args, PyDict kw) { if (name == null) throw new ArgumentNullException(nameof(name)); if (args == null) throw new ArgumentNullException(nameof(args)); PyObject method = GetAttr(name); PyObject result = method.Invoke(args, kw); method.Dispose(); return result; } /// <summary> /// IsInstance Method /// </summary> /// <remarks> /// Return true if the object is an instance of the given Python type /// or class. This method always succeeds. /// </remarks> public bool IsInstance(PyObject typeOrClass) { if (typeOrClass == null) throw new ArgumentNullException(nameof(typeOrClass)); int r = Runtime.PyObject_IsInstance(obj, typeOrClass.obj); if (r < 0) { Runtime.PyErr_Clear(); return false; } return r != 0; } /// <summary> /// IsSubclass Method /// </summary> /// <remarks> /// Return true if the object is identical to or derived from the /// given Python type or class. This method always succeeds. /// </remarks> public bool IsSubclass(PyObject typeOrClass) { if (typeOrClass == null) throw new ArgumentNullException(nameof(typeOrClass)); int r = Runtime.PyObject_IsSubclass(obj, typeOrClass.obj); if (r < 0) { Runtime.PyErr_Clear(); return false; } return r != 0; } /// <summary> /// IsCallable Method /// </summary> /// <remarks> /// Returns true if the object is a callable object. This method /// always succeeds. /// </remarks> public bool IsCallable() { return Runtime.PyCallable_Check(obj) != 0; } /// <summary> /// IsIterable Method /// </summary> /// <remarks> /// Returns true if the object is iterable object. This method /// always succeeds. /// </remarks> public bool IsIterable() { return Runtime.PyObject_IsIterable(obj); } /// <summary> /// IsTrue Method /// </summary> /// <remarks> /// Return true if the object is true according to Python semantics. /// This method always succeeds. /// </remarks> public bool IsTrue() { return Runtime.PyObject_IsTrue(obj) != 0; } /// <summary> /// Return true if the object is None /// </summary> public bool IsNone() => CheckNone(this) == null; /// <summary> /// Dir Method /// </summary> /// <remarks> /// Return a list of the names of the attributes of the object. This /// is equivalent to the Python expression "dir(object)". /// </remarks> public PyList Dir() { IntPtr r = Runtime.PyObject_Dir(obj); if (r == IntPtr.Zero) { throw new PythonException(); } return new PyList(r); } /// <summary> /// Repr Method /// </summary> /// <remarks> /// Return a string representation of the object. This method is /// the managed equivalent of the Python expression "repr(object)". /// </remarks> public string Repr() { IntPtr strval = Runtime.PyObject_Repr(obj); string result = Runtime.GetManagedString(strval); Runtime.XDecref(strval); return result; } /// <summary> /// ToString Method /// </summary> /// <remarks> /// Return the string representation of the object. This method is /// the managed equivalent of the Python expression "str(object)". /// </remarks> public override string ToString() { IntPtr strval = Runtime.PyObject_Unicode(obj); string result = Runtime.GetManagedString(strval); Runtime.XDecref(strval); return result; } /// <summary> /// Equals Method /// </summary> /// <remarks> /// Return true if this object is equal to the given object. This /// method is based on Python equality semantics. /// </remarks> public override bool Equals(object o) { if (!(o is PyObject)) { return false; } if (obj == ((PyObject)o).obj) { return true; } int r = Runtime.PyObject_Compare(obj, ((PyObject)o).obj); if (Exceptions.ErrorOccurred()) { throw new PythonException(); } return r == 0; } /// <summary> /// GetHashCode Method /// </summary> /// <remarks> /// Return a hashcode based on the Python object. This returns the /// hash as computed by Python, equivalent to the Python expression /// "hash(obj)". /// </remarks> public override int GetHashCode() { return ((ulong)Runtime.PyObject_Hash(obj)).GetHashCode(); } /// <summary> /// GetBuffer Method. This Method only works for objects that have a buffer (like "bytes", "bytearray" or "array.array") /// </summary> /// <remarks> /// Send a request to the PyObject to fill in view as specified by flags. If the PyObject cannot provide a buffer of the exact type, it MUST raise PyExc_BufferError, set view->obj to NULL and return -1. /// On success, fill in view, set view->obj to a new reference to exporter and return 0. In the case of chained buffer providers that redirect requests to a single object, view->obj MAY refer to this object instead of exporter(See Buffer Object Structures). /// Successful calls to <see cref="PyObject.GetBuffer"/> must be paired with calls to <see cref="PyBuffer.Dispose()"/>, similar to malloc() and free(). Thus, after the consumer is done with the buffer, <see cref="PyBuffer.Dispose()"/> must be called exactly once. /// </remarks> public PyBuffer GetBuffer(PyBUF flags = PyBUF.SIMPLE) { return new PyBuffer(this, flags); } public long Refcount { get { return Runtime.Refcount(obj); } } public override bool TryGetMember(GetMemberBinder binder, out object result) { result = CheckNone(this.GetAttr(binder.Name)); return true; } public override bool TrySetMember(SetMemberBinder binder, object value) { IntPtr ptr = Converter.ToPython(value, value?.GetType()); int r = Runtime.PyObject_SetAttrString(obj, binder.Name, ptr); if (r < 0) { throw new PythonException(); } Runtime.XDecref(ptr); return true; } private void GetArgs(object[] inargs, CallInfo callInfo, out PyTuple args, out PyDict kwargs) { if (callInfo == null || callInfo.ArgumentNames.Count == 0) { GetArgs(inargs, out args, out kwargs); return; } // Support for .net named arguments var namedArgumentCount = callInfo.ArgumentNames.Count; var regularArgumentCount = callInfo.ArgumentCount - namedArgumentCount; var argTuple = Runtime.PyTuple_New(regularArgumentCount); for (int i = 0; i < regularArgumentCount; ++i) { AddArgument(argTuple, i, inargs[i]); } args = new PyTuple(argTuple); var namedArgs = new object[namedArgumentCount * 2]; for (int i = 0; i < namedArgumentCount; ++i) { namedArgs[i * 2] = callInfo.ArgumentNames[i]; namedArgs[i * 2 + 1] = inargs[regularArgumentCount + i]; } kwargs = Py.kw(namedArgs); } private void GetArgs(object[] inargs, out PyTuple args, out PyDict kwargs) { int arg_count; for (arg_count = 0; arg_count < inargs.Length && !(inargs[arg_count] is Py.KeywordArguments); ++arg_count) { ; } IntPtr argtuple = Runtime.PyTuple_New(arg_count); for (var i = 0; i < arg_count; i++) { AddArgument(argtuple, i, inargs[i]); } args = new PyTuple(argtuple); kwargs = null; for (int i = arg_count; i < inargs.Length; i++) { if (!(inargs[i] is Py.KeywordArguments)) { throw new ArgumentException("Keyword arguments must come after normal arguments."); } if (kwargs == null) { kwargs = (Py.KeywordArguments)inargs[i]; } else { kwargs.Update((Py.KeywordArguments)inargs[i]); } } } private static void AddArgument(IntPtr argtuple, int i, object target) { IntPtr ptr = GetPythonObject(target); if (Runtime.PyTuple_SetItem(argtuple, i, ptr) < 0) { throw new PythonException(); } } private static IntPtr GetPythonObject(object target) { IntPtr ptr; if (target is PyObject) { ptr = ((PyObject)target).Handle; Runtime.XIncref(ptr); } else { ptr = Converter.ToPython(target, target?.GetType()); } return ptr; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (this.HasAttr(binder.Name) && this.GetAttr(binder.Name).IsCallable()) { PyTuple pyargs = null; PyDict kwargs = null; try { GetArgs(args, binder.CallInfo, out pyargs, out kwargs); result = CheckNone(InvokeMethod(binder.Name, pyargs, kwargs)); } finally { if (null != pyargs) { pyargs.Dispose(); } if (null != kwargs) { kwargs.Dispose(); } } return true; } else { return base.TryInvokeMember(binder, args, out result); } } public override bool TryInvoke(InvokeBinder binder, object[] args, out object result) { if (this.IsCallable()) { PyTuple pyargs = null; PyDict kwargs = null; try { GetArgs(args, binder.CallInfo, out pyargs, out kwargs); result = CheckNone(Invoke(pyargs, kwargs)); } finally { if (null != pyargs) { pyargs.Dispose(); } if (null != kwargs) { kwargs.Dispose(); } } return true; } else { return base.TryInvoke(binder, args, out result); } } public override bool TryConvert(ConvertBinder binder, out object result) { return Converter.ToManaged(this.obj, binder.Type, out result, false); } public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result) { IntPtr res; if (!(arg is PyObject)) { arg = arg.ToPython(); } switch (binder.Operation) { case ExpressionType.Add: res = Runtime.PyNumber_Add(this.obj, ((PyObject)arg).obj); break; case ExpressionType.AddAssign: res = Runtime.PyNumber_InPlaceAdd(this.obj, ((PyObject)arg).obj); break; case ExpressionType.Subtract: res = Runtime.PyNumber_Subtract(this.obj, ((PyObject)arg).obj); break; case ExpressionType.SubtractAssign: res = Runtime.PyNumber_InPlaceSubtract(this.obj, ((PyObject)arg).obj); break; case ExpressionType.Multiply: res = Runtime.PyNumber_Multiply(this.obj, ((PyObject)arg).obj); break; case ExpressionType.MultiplyAssign: res = Runtime.PyNumber_InPlaceMultiply(this.obj, ((PyObject)arg).obj); break; case ExpressionType.Divide: res = Runtime.PyNumber_TrueDivide(this.obj, ((PyObject)arg).obj); break; case ExpressionType.DivideAssign: res = Runtime.PyNumber_InPlaceTrueDivide(this.obj, ((PyObject)arg).obj); break; case ExpressionType.And: res = Runtime.PyNumber_And(this.obj, ((PyObject)arg).obj); break; case ExpressionType.AndAssign: res = Runtime.PyNumber_InPlaceAnd(this.obj, ((PyObject)arg).obj); break; case ExpressionType.ExclusiveOr: res = Runtime.PyNumber_Xor(this.obj, ((PyObject)arg).obj); break; case ExpressionType.ExclusiveOrAssign: res = Runtime.PyNumber_InPlaceXor(this.obj, ((PyObject)arg).obj); break; case ExpressionType.GreaterThan: result = Runtime.PyObject_Compare(this.obj, ((PyObject)arg).obj) > 0; return true; case ExpressionType.GreaterThanOrEqual: result = Runtime.PyObject_Compare(this.obj, ((PyObject)arg).obj) >= 0; return true; case ExpressionType.LeftShift: res = Runtime.PyNumber_Lshift(this.obj, ((PyObject)arg).obj); break; case ExpressionType.LeftShiftAssign: res = Runtime.PyNumber_InPlaceLshift(this.obj, ((PyObject)arg).obj); break; case ExpressionType.LessThan: result = Runtime.PyObject_Compare(this.obj, ((PyObject)arg).obj) < 0; return true; case ExpressionType.LessThanOrEqual: result = Runtime.PyObject_Compare(this.obj, ((PyObject)arg).obj) <= 0; return true; case ExpressionType.Modulo: res = Runtime.PyNumber_Remainder(this.obj, ((PyObject)arg).obj); break; case ExpressionType.ModuloAssign: res = Runtime.PyNumber_InPlaceRemainder(this.obj, ((PyObject)arg).obj); break; case ExpressionType.NotEqual: result = Runtime.PyObject_Compare(this.obj, ((PyObject)arg).obj) != 0; return true; case ExpressionType.Or: res = Runtime.PyNumber_Or(this.obj, ((PyObject)arg).obj); break; case ExpressionType.OrAssign: res = Runtime.PyNumber_InPlaceOr(this.obj, ((PyObject)arg).obj); break; case ExpressionType.Power: res = Runtime.PyNumber_Power(this.obj, ((PyObject)arg).obj); break; case ExpressionType.RightShift: res = Runtime.PyNumber_Rshift(this.obj, ((PyObject)arg).obj); break; case ExpressionType.RightShiftAssign: res = Runtime.PyNumber_InPlaceRshift(this.obj, ((PyObject)arg).obj); break; default: result = null; return false; } result = CheckNone(new PyObject(res)); return true; } // Workaround for https://bugzilla.xamarin.com/show_bug.cgi?id=41509 // See https://github.com/pythonnet/pythonnet/pull/219 private static object CheckNone(PyObject pyObj) { if (pyObj != null) { if (pyObj.obj == Runtime.PyNone) { return null; } } return pyObj; } public override bool TryUnaryOperation(UnaryOperationBinder binder, out object result) { int r; IntPtr res; switch (binder.Operation) { case ExpressionType.Negate: res = Runtime.PyNumber_Negative(this.obj); break; case ExpressionType.UnaryPlus: res = Runtime.PyNumber_Positive(this.obj); break; case ExpressionType.OnesComplement: res = Runtime.PyNumber_Invert(this.obj); break; case ExpressionType.Not: r = Runtime.PyObject_Not(this.obj); result = r == 1; return r != -1; case ExpressionType.IsFalse: r = Runtime.PyObject_IsTrue(this.obj); result = r == 0; return r != -1; case ExpressionType.IsTrue: r = Runtime.PyObject_IsTrue(this.obj); result = r == 1; return r != -1; case ExpressionType.Decrement: case ExpressionType.Increment: default: result = null; return false; } result = CheckNone(new PyObject(res)); return true; } /// <summary> /// Returns the enumeration of all dynamic member names. /// </summary> /// <remarks> /// This method exists for debugging purposes only. /// </remarks> /// <returns>A sequence that contains dynamic member names.</returns> public override IEnumerable<string> GetDynamicMemberNames() { foreach (PyObject pyObj in Dir()) { yield return pyObj.ToString(); } } } }
//------------------------------------------------------------------------------ // <copyright file="DefaultPropertiesToSend.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Messaging { using System.Diagnostics; using System; using System.ComponentModel; /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend"]/*' /> /// <devdoc> /// <para> /// Specifies the default property values that will be used when /// sending objects using the message queue. /// </para> /// </devdoc> [TypeConverter(typeof(ExpandableObjectConverter))] public class DefaultPropertiesToSend { private Message cachedMessage = new Message(); private bool designMode; private MessageQueue cachedAdminQueue; private MessageQueue cachedResponseQueue; private MessageQueue cachedTransactionStatusQueue; /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.DefaultPropertiesToSend"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Messaging.DefaultPropertiesToSend'/> /// class. /// </para> /// </devdoc> public DefaultPropertiesToSend() { } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.DefaultPropertiesToSend1"]/*' /> /// <internalonly/> internal DefaultPropertiesToSend(bool designMode) { this.designMode = designMode; } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.AcknowledgeTypes"]/*' /> /// <devdoc> /// <para> /// Gets /// or sets the type of acknowledgement message to be returned to the sending /// application. /// </para> /// </devdoc> [DefaultValueAttribute(AcknowledgeTypes.None), MessagingDescription(Res.MsgAcknowledgeType)] public AcknowledgeTypes AcknowledgeType { get { return this.cachedMessage.AcknowledgeType; } set { this.cachedMessage.AcknowledgeType = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.AdministrationQueue"]/*' /> /// <devdoc> /// <para> /// Gets or sets the queue used for acknowledgement messages /// generated by the application. This is the queue that /// will receive the acknowledgment message for the message you are about to /// send. /// </para> /// </devdoc> [DefaultValueAttribute(null), MessagingDescription(Res.MsgAdministrationQueue)] public MessageQueue AdministrationQueue { get { if (this.designMode) { if (this.cachedAdminQueue != null && this.cachedAdminQueue.Site == null) this.cachedAdminQueue = null; return this.cachedAdminQueue; } return this.cachedMessage.AdministrationQueue; } set { //The format name of this queue shouldn't be //resolved at desgin time, but it should at runtime. if (this.designMode) this.cachedAdminQueue = value; else this.cachedMessage.AdministrationQueue = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.AppSpecific"]/*' /> /// <devdoc> /// <para> /// Gets or sets application-generated information. /// /// </para> /// </devdoc> [DefaultValueAttribute(0), MessagingDescription(Res.MsgAppSpecific)] public int AppSpecific { get { return this.cachedMessage.AppSpecific; } set { this.cachedMessage.AppSpecific = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.AttachSenderId"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating if the sender ID is to be attached to the /// message. /// /// </para> /// </devdoc> [DefaultValueAttribute(true), MessagingDescription(Res.MsgAttachSenderId)] public bool AttachSenderId { get { return this.cachedMessage.AttachSenderId; } set { this.cachedMessage.AttachSenderId = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.CachedMessage"]/*' /> /// <internalonly/> internal Message CachedMessage { get { return this.cachedMessage; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.EncryptionAlgorithm"]/*' /> /// <devdoc> /// <para> /// Gets or sets the encryption algorithm used to encrypt the body of a /// private message. /// /// </para> /// </devdoc> [DefaultValueAttribute(EncryptionAlgorithm.Rc2), MessagingDescription(Res.MsgEncryptionAlgorithm)] public EncryptionAlgorithm EncryptionAlgorithm { get { return this.cachedMessage.EncryptionAlgorithm; } set { this.cachedMessage.EncryptionAlgorithm = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.Extension"]/*' /> /// <devdoc> /// <para> /// Gets or sets additional information associated with the message. /// /// </para> /// </devdoc> [Editor("System.ComponentModel.Design.ArrayEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), MessagingDescription(Res.MsgExtension)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public byte[] Extension { get { return this.cachedMessage.Extension; } set { this.cachedMessage.Extension = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.HashAlgorithm"]/*' /> /// <devdoc> /// <para> /// Gets or sets the hashing algorithm used when /// authenticating /// messages. /// /// </para> /// </devdoc> [DefaultValueAttribute(HashAlgorithm.Md5), MessagingDescription(Res.MsgHashAlgorithm)] public HashAlgorithm HashAlgorithm { get { return this.cachedMessage.HashAlgorithm; } set { this.cachedMessage.HashAlgorithm = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.Label"]/*' /> /// <devdoc> /// <para> /// Gets or sets the message label. /// /// </para> /// </devdoc> [DefaultValueAttribute(""), MessagingDescription(Res.MsgLabel)] public string Label { get { return this.cachedMessage.Label; } set { this.cachedMessage.Label = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.Priority"]/*' /> /// <devdoc> /// <para> /// Gets or sets the message priority. /// </para> /// </devdoc> [DefaultValueAttribute(MessagePriority.Normal), MessagingDescription(Res.MsgPriority)] public MessagePriority Priority { get { return this.cachedMessage.Priority; } set { this.cachedMessage.Priority = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.Recoverable"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the message is /// guaranteed to be delivered in the event /// of a computer failure or network problem. /// /// </para> /// </devdoc> [DefaultValueAttribute(false), MessagingDescription(Res.MsgRecoverable)] public bool Recoverable { get { return this.cachedMessage.Recoverable; } set { this.cachedMessage.Recoverable = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.ResponseQueue"]/*' /> /// <devdoc> /// <para> /// Gets or sets the queue which receives application-generated response /// messages. /// /// </para> /// </devdoc> [DefaultValueAttribute(null), MessagingDescription(Res.MsgResponseQueue)] public MessageQueue ResponseQueue { get { if (this.designMode) return this.cachedResponseQueue; return this.cachedMessage.ResponseQueue; } set { //The format name of this queue shouldn't be //resolved at desgin time, but it should at runtime. if (this.designMode) this.cachedResponseQueue = value; else this.cachedMessage.ResponseQueue = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.TimeToBeReceived"]/*' /> /// <devdoc> /// <para> /// Gets or sets the time limit for the message to be /// retrieved from /// the target queue. /// </para> /// </devdoc> [TypeConverter(typeof(System.Messaging.Design.TimeoutConverter)), MessagingDescription(Res.MsgTimeToBeReceived)] public TimeSpan TimeToBeReceived { get { return this.cachedMessage.TimeToBeReceived; } set { this.cachedMessage.TimeToBeReceived = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.TimeToReachQueue"]/*' /> /// <devdoc> /// <para> /// Gets or sets the time limit for the message to /// reach the queue. /// /// </para> /// </devdoc> [TypeConverter(typeof(System.Messaging.Design.TimeoutConverter)), MessagingDescription(Res.MsgTimeToReachQueue)] public TimeSpan TimeToReachQueue { get { return this.cachedMessage.TimeToReachQueue; } set { this.cachedMessage.TimeToReachQueue = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.TransactionStatusQueue"]/*' /> /// <devdoc> /// <para> /// Gets the transaction status queue on the source computer. /// /// </para> /// </devdoc> [DefaultValueAttribute(null), MessagingDescription(Res.MsgTransactionStatusQueue)] public MessageQueue TransactionStatusQueue { get { if (this.designMode) return this.cachedTransactionStatusQueue; return this.cachedMessage.TransactionStatusQueue; } set { //The format name of this queue shouldn't be //resolved at desgin time, but it should at runtime. if (this.designMode) this.cachedTransactionStatusQueue = value; else this.cachedMessage.TransactionStatusQueue = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.UseAuthentication"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether the message must be authenticated. /// </para> /// </devdoc> [DefaultValueAttribute(false), MessagingDescription(Res.MsgUseAuthentication)] public bool UseAuthentication { get { return this.cachedMessage.UseAuthentication; } set { this.cachedMessage.UseAuthentication = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.UseDeadLetterQueue"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether a copy of the message that could not /// be delivered should be sent to a dead-letter queue. /// </para> /// </devdoc> [DefaultValueAttribute(false), MessagingDescription(Res.MsgUseDeadLetterQueue)] public bool UseDeadLetterQueue { get { return this.cachedMessage.UseDeadLetterQueue; } set { this.cachedMessage.UseDeadLetterQueue = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.UseEncryption"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether to encrypt private messages. /// </para> /// </devdoc> [DefaultValueAttribute(false), MessagingDescription(Res.MsgUseEncryption)] public bool UseEncryption { get { return this.cachedMessage.UseEncryption; } set { this.cachedMessage.UseEncryption = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.UseJournalQueue"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether a copy of the message should be kept /// in a machine journal on the originating computer. /// </para> /// </devdoc> [DefaultValueAttribute(false), MessagingDescription(Res.MsgUseJournalQueue)] public bool UseJournalQueue { get { return this.cachedMessage.UseJournalQueue; } set { this.cachedMessage.UseJournalQueue = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.UseTracing"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value indicating whether to trace a message as it moves toward /// its destination queue. /// </para> /// </devdoc> [DefaultValueAttribute(false), MessagingDescription(Res.MsgUseTracing)] public bool UseTracing { get { return this.cachedMessage.UseTracing; } set { this.cachedMessage.UseTracing = value; } } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.ShouldSerializeTimeToBeReceived"]/*' /> /// <internalonly/> private bool ShouldSerializeTimeToBeReceived() { if (TimeToBeReceived == Message.InfiniteTimeout) return false; return true; } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.ShouldSerializeTimeToReachQueue"]/*' /> /// <internalonly/> private bool ShouldSerializeTimeToReachQueue() { if (TimeToReachQueue == Message.InfiniteTimeout) return false; return true; } /// <include file='doc\DefaultPropertiesToSend.uex' path='docs/doc[@for="DefaultPropertiesToSend.ShouldSerializeExtension"]/*' /> /// <internalonly/> private bool ShouldSerializeExtension() { if (Extension != null && Extension.Length > 0) { return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; namespace System.Net { internal static partial class CertificateValidationPal { internal static SslPolicyErrors VerifyCertificateProperties( SafeDeleteContext securityContext, X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, string hostName) { SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; bool chainBuildResult = chain.Build(remoteCertificate); if (!chainBuildResult // Build failed on handle or on policy. && chain.SafeHandle.DangerousGetHandle() == IntPtr.Zero) // Build failed to generate a valid handle. { throw new CryptographicException(Marshal.GetLastWin32Error()); } if (checkCertName) { unsafe { uint status = 0; var eppStruct = new Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA() { cbSize = (uint)sizeof(Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA), // Authenticate the remote party: (e.g. when operating in server mode, authenticate the client). dwAuthType = isServer ? Interop.Crypt32.AuthType.AUTHTYPE_CLIENT : Interop.Crypt32.AuthType.AUTHTYPE_SERVER, fdwChecks = 0, pwszServerName = null }; var cppStruct = new Interop.Crypt32.CERT_CHAIN_POLICY_PARA() { cbSize = (uint)sizeof(Interop.Crypt32.CERT_CHAIN_POLICY_PARA), dwFlags = 0, pvExtraPolicyPara = &eppStruct }; fixed (char* namePtr = hostName) { eppStruct.pwszServerName = namePtr; cppStruct.dwFlags |= (Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_ALL & ~Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG); SafeX509ChainHandle chainContext = chain.SafeHandle; status = Verify(chainContext, ref cppStruct); if (status == Interop.Crypt32.CertChainPolicyErrors.CERT_E_CN_NO_MATCH) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch; } } } } if (!chainBuildResult) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors; } return sslPolicyErrors; } // // Extracts a remote certificate upon request. // internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext) => GetRemoteCertificate(securityContext, retrieveCollection: false, out _); internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext, out X509Certificate2Collection remoteCertificateCollection) => GetRemoteCertificate(securityContext, retrieveCollection: true, out remoteCertificateCollection); private static X509Certificate2 GetRemoteCertificate( SafeDeleteContext securityContext, bool retrieveCollection, out X509Certificate2Collection remoteCertificateCollection) { remoteCertificateCollection = null; if (securityContext == null) { return null; } if (NetEventSource.IsEnabled) NetEventSource.Enter(securityContext); X509Certificate2 result = null; SafeFreeCertContext remoteContext = null; try { remoteContext = SSPIWrapper.QueryContextAttributes_SECPKG_ATTR_REMOTE_CERT_CONTEXT(GlobalSSPI.SSPISecureChannel, securityContext); if (remoteContext != null && !remoteContext.IsInvalid) { result = new X509Certificate2(remoteContext.DangerousGetHandle()); } } finally { if (remoteContext != null && !remoteContext.IsInvalid) { if (retrieveCollection) { remoteCertificateCollection = UnmanagedCertificateContext.GetRemoteCertificatesFromStoreContext(remoteContext); } remoteContext.Dispose(); } } if (NetEventSource.IsEnabled) { NetEventSource.Log.RemoteCertificate(result); NetEventSource.Exit(null, result, securityContext); } return result; } // // Used only by client SSL code, never returns null. // internal static string[] GetRequestCertificateAuthorities(SafeDeleteContext securityContext) { Interop.SspiCli.SecPkgContext_IssuerListInfoEx issuerList = default; bool success = SSPIWrapper.QueryContextAttributes_SECPKG_ATTR_ISSUER_LIST_EX(GlobalSSPI.SSPISecureChannel, securityContext, ref issuerList, out SafeHandle sspiHandle); string[] issuers = Array.Empty<string>(); try { if (success && issuerList.cIssuers > 0) { unsafe { issuers = new string[issuerList.cIssuers]; var elements = new Span<Interop.SspiCli.CERT_CHAIN_ELEMENT>((void*)sspiHandle.DangerousGetHandle(), issuers.Length); for (int i = 0; i < elements.Length; ++i) { if (elements[i].cbSize <= 0) { NetEventSource.Fail(securityContext, $"Interop.SspiCli._CERT_CHAIN_ELEMENT size is not positive: {elements[i].cbSize}"); } if (elements[i].cbSize > 0) { byte[] x = new Span<byte>((byte*)elements[i].pCertContext, checked((int)elements[i].cbSize)).ToArray(); var x500DistinguishedName = new X500DistinguishedName(x); issuers[i] = x500DistinguishedName.Name; if (NetEventSource.IsEnabled) NetEventSource.Info(securityContext, $"IssuerListEx[{issuers[i]}]"); } } } } } finally { sspiHandle?.Dispose(); } return issuers; } // // Security: We temporarily reset thread token to open the cert store under process account. // internal static X509Store OpenStore(StoreLocation storeLocation) { X509Store store = new X509Store(StoreName.My, storeLocation); // For app-compat We want to ensure the store is opened under the **process** account. try { WindowsIdentity.RunImpersonated(SafeAccessTokenHandle.InvalidHandle, () => { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); }); } catch { throw; } return store; } private static unsafe uint Verify(SafeX509ChainHandle chainContext, ref Interop.Crypt32.CERT_CHAIN_POLICY_PARA cpp) { if (NetEventSource.IsEnabled) NetEventSource.Enter(chainContext, cpp.dwFlags); var status = new Interop.Crypt32.CERT_CHAIN_POLICY_STATUS(); status.cbSize = (uint)sizeof(Interop.Crypt32.CERT_CHAIN_POLICY_STATUS); bool errorCode = Interop.Crypt32.CertVerifyCertificateChainPolicy( (IntPtr)Interop.Crypt32.CertChainPolicy.CERT_CHAIN_POLICY_SSL, chainContext, ref cpp, ref status); if (NetEventSource.IsEnabled) NetEventSource.Info(chainContext, $"CertVerifyCertificateChainPolicy returned: {errorCode}. Status: {status.dwError}"); return status.dwError; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using OpenTK.Graphics; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.Sprites; using OpenTK; namespace osu.Game.Graphics.UserInterface { public class OsuDropdown<T> : Dropdown<T>, IHasAccentColour { private Color4 accentColour; public Color4 AccentColour { get { return accentColour; } set { accentColour = value; updateAccentColour(); } } [BackgroundDependencyLoader] private void load(OsuColour colours) { if (accentColour == default(Color4)) accentColour = colours.PinkDarker; updateAccentColour(); } private void updateAccentColour() { var header = Header as IHasAccentColour; if (header != null) header.AccentColour = accentColour; var menu = Menu as IHasAccentColour; if (menu != null) menu.AccentColour = accentColour; } protected override DropdownHeader CreateHeader() => new OsuDropdownHeader(); protected override DropdownMenu CreateMenu() => new OsuDropdownMenu(); #region OsuDropdownMenu protected class OsuDropdownMenu : DropdownMenu, IHasAccentColour { // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring public OsuDropdownMenu() { CornerRadius = 4; BackgroundColour = Color4.Black.Opacity(0.5f); // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring ItemsContainer.Padding = new MarginPadding(5); } // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring protected override void AnimateOpen() => this.FadeIn(300, Easing.OutQuint); protected override void AnimateClose() => this.FadeOut(300, Easing.OutQuint); // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring protected override void UpdateSize(Vector2 newSize) { if (Direction == Direction.Vertical) { Width = newSize.X; this.ResizeHeightTo(newSize.Y, 300, Easing.OutQuint); } else { Height = newSize.Y; this.ResizeWidthTo(newSize.X, 300, Easing.OutQuint); } } private Color4 accentColour; public Color4 AccentColour { get { return accentColour; } set { accentColour = value; foreach (var c in Children.OfType<IHasAccentColour>()) c.AccentColour = value; } } protected override DrawableMenuItem CreateDrawableMenuItem(MenuItem item) => new DrawableOsuDropdownMenuItem(item) { AccentColour = accentColour }; #region DrawableOsuDropdownMenuItem protected class DrawableOsuDropdownMenuItem : DrawableDropdownMenuItem, IHasAccentColour { private Color4? accentColour; public Color4 AccentColour { get { return accentColour ?? nonAccentSelectedColour; } set { accentColour = value; updateColours(); } } private void updateColours() { BackgroundColourHover = accentColour ?? nonAccentHoverColour; BackgroundColourSelected = accentColour ?? nonAccentSelectedColour; UpdateBackgroundColour(); UpdateForegroundColour(); } private Color4 nonAccentHoverColour; private Color4 nonAccentSelectedColour; public DrawableOsuDropdownMenuItem(MenuItem item) : base(item) { Foreground.Padding = new MarginPadding(2); Masking = true; CornerRadius = 6; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = Color4.Transparent; nonAccentHoverColour = colours.PinkDarker; nonAccentSelectedColour = Color4.Black.Opacity(0.5f); updateColours(); } protected override void UpdateForegroundColour() { base.UpdateForegroundColour(); var content = Foreground.Children.FirstOrDefault() as Content; if (content != null) content.Chevron.Alpha = IsHovered ? 1 : 0; } protected override Drawable CreateContent() => new Content(); protected new class Content : FillFlowContainer, IHasText { public string Text { get { return Label.Text; } set { Label.Text = value; } } public readonly OsuSpriteText Label; public readonly SpriteIcon Chevron; public Content() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Direction = FillDirection.Horizontal; Children = new Drawable[] { Chevron = new SpriteIcon { AlwaysPresent = true, Icon = FontAwesome.fa_chevron_right, Colour = Color4.Black, Alpha = 0.5f, Size = new Vector2(8), Margin = new MarginPadding { Left = 3, Right = 3 }, Origin = Anchor.CentreLeft, Anchor = Anchor.CentreLeft, }, Label = new OsuSpriteText { Origin = Anchor.CentreLeft, Anchor = Anchor.CentreLeft, } }; } } } #endregion } #endregion public class OsuDropdownHeader : DropdownHeader, IHasAccentColour { protected readonly SpriteText Text; protected override string Label { get { return Text.Text; } set { Text.Text = value; } } protected readonly SpriteIcon Icon; private Color4 accentColour; public virtual Color4 AccentColour { get { return accentColour; } set { accentColour = value; BackgroundColourHover = accentColour; } } public OsuDropdownHeader() { Foreground.Padding = new MarginPadding(4); AutoSizeAxes = Axes.None; Margin = new MarginPadding { Bottom = 4 }; CornerRadius = 4; Height = 40; Foreground.Children = new Drawable[] { Text = new OsuSpriteText { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, }, Icon = new SpriteIcon { Icon = FontAwesome.fa_chevron_down, Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Margin = new MarginPadding { Right = 4 }, Size = new Vector2(20), } }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = Color4.Black.Opacity(0.5f); BackgroundColourHover = colours.PinkDarker; } } } }
/* * CP709.cs - Arabic - ASMO 449+, BCON V4 code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "iso-9036.ucm". namespace I18N.Rare { using System; using I18N.Common; public class CP709 : ByteEncoding { public CP709() : base(709, ToChars, "Arabic - ASMO 449+, BCON V4", "windows-709", "windows-709", "windows-709", false, false, false, false, 1256) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023', '\u00A4', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u060C', '\u002D', '\u002E', '\u002F', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u061B', '\u003C', '\u003D', '\u003E', '\u061F', '\u0040', '\u0621', '\u0622', '\u0623', '\u0624', '\u0625', '\u0626', '\u0627', '\u0628', '\u0629', '\u062A', '\u062B', '\u062C', '\u062D', '\u062E', '\u062F', '\u0630', '\u0631', '\u0632', '\u0633', '\u0634', '\u0635', '\u0636', '\u0637', '\u0638', '\u0639', '\u063A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F', '\u0640', '\u0641', '\u0642', '\u0643', '\u0644', '\u0645', '\u0646', '\u0647', '\u0648', '\u0649', '\u064A', '\u064B', '\u064C', '\u064D', '\u064E', '\u064F', '\u0650', '\u0651', '\u0652', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u007B', '\u007C', '\u007D', '\u203E', '\u007F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', '\u003F', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 36) switch(ch) { case 0x0025: case 0x0026: case 0x0027: case 0x0028: case 0x0029: case 0x002A: case 0x002B: case 0x002D: case 0x002E: case 0x002F: case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: case 0x003A: case 0x003C: case 0x003D: case 0x003E: case 0x0040: case 0x005B: case 0x005C: case 0x005D: case 0x005E: case 0x005F: case 0x007B: case 0x007C: case 0x007D: case 0x007F: break; case 0x00A4: ch = 0x24; break; case 0x060C: ch = 0x2C; break; case 0x061B: ch = 0x3B; break; case 0x061F: ch = 0x3F; break; case 0x0621: case 0x0622: case 0x0623: case 0x0624: case 0x0625: case 0x0626: case 0x0627: case 0x0628: case 0x0629: case 0x062A: case 0x062B: case 0x062C: case 0x062D: case 0x062E: case 0x062F: case 0x0630: case 0x0631: case 0x0632: case 0x0633: case 0x0634: case 0x0635: case 0x0636: case 0x0637: case 0x0638: case 0x0639: case 0x063A: ch -= 0x05E0; break; case 0x0640: case 0x0641: case 0x0642: case 0x0643: case 0x0644: case 0x0645: case 0x0646: case 0x0647: case 0x0648: case 0x0649: case 0x064A: case 0x064B: case 0x064C: case 0x064D: case 0x064E: case 0x064F: case 0x0650: case 0x0651: case 0x0652: ch -= 0x05E0; break; case 0x203E: ch = 0x7E; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 36) switch(ch) { case 0x0025: case 0x0026: case 0x0027: case 0x0028: case 0x0029: case 0x002A: case 0x002B: case 0x002D: case 0x002E: case 0x002F: case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: case 0x003A: case 0x003C: case 0x003D: case 0x003E: case 0x0040: case 0x005B: case 0x005C: case 0x005D: case 0x005E: case 0x005F: case 0x007B: case 0x007C: case 0x007D: case 0x007F: break; case 0x00A4: ch = 0x24; break; case 0x060C: ch = 0x2C; break; case 0x061B: ch = 0x3B; break; case 0x061F: ch = 0x3F; break; case 0x0621: case 0x0622: case 0x0623: case 0x0624: case 0x0625: case 0x0626: case 0x0627: case 0x0628: case 0x0629: case 0x062A: case 0x062B: case 0x062C: case 0x062D: case 0x062E: case 0x062F: case 0x0630: case 0x0631: case 0x0632: case 0x0633: case 0x0634: case 0x0635: case 0x0636: case 0x0637: case 0x0638: case 0x0639: case 0x063A: ch -= 0x05E0; break; case 0x0640: case 0x0641: case 0x0642: case 0x0643: case 0x0644: case 0x0645: case 0x0646: case 0x0647: case 0x0648: case 0x0649: case 0x064A: case 0x064B: case 0x064C: case 0x064D: case 0x064E: case 0x064F: case 0x0650: case 0x0651: case 0x0652: ch -= 0x05E0; break; case 0x203E: ch = 0x7E; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP709 public class ENCwindows_709 : CP709 { public ENCwindows_709() : base() {} }; // class ENCwindows_709 }; // namespace I18N.Rare
/* * 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 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.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.CoreModules.Framework.EventQueue; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps = OpenSim.Framework.Communications.Capabilities.Caps; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; namespace OpenSim.Region.CoreModules.Avatar.Groups { public class LocalGroupsModule : IRegionModule, IGroupsModule { /// <summary> /// To use this module, you must specify the following in your OpenSim.ini /// [Groups] /// Enabled = true; /// Module = LocalGroups; /// /// This module is a fast and loose implementation of groups, that uses /// local generic collections to store all group information in memory. /// /// This does not implement Group Messaging /// /// </summary> // SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_SceneList = new List<Scene>(); private Dictionary<UUID, osGroup> m_Groups = new Dictionary<UUID, osGroup>(); // There is one GroupMemberInfo entry for each group the Agent is a member of // AgentID -> (GroupID -> MembershipInfo) private Dictionary<UUID, Dictionary<UUID, osGroupMemberInfo>> m_GroupMemberInfo = new Dictionary<UUID, Dictionary<UUID, osGroupMemberInfo>>(); // Each agent has one group that they currently have set to Active, this determines // somethings like permissions in-world (using group objects for example) and what // tag is displayed private Dictionary<UUID, UUID> m_AgentActiveGroup = new Dictionary<UUID, UUID>(); private Dictionary<UUID, IClientAPI> m_ActiveClients = new Dictionary<UUID, IClientAPI>(); #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { if (!groupsConfig.GetBoolean("Enabled", false)) { m_log.Info("[GROUPS]: Groups disabled in configuration"); return; } if (groupsConfig.GetString("Module", "Default") != "LocalGroups") return; } lock (m_SceneList) { if (!m_SceneList.Contains(scene)) { m_SceneList.Add(scene); } } scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnClientClosed += OnClientClosed; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; scene.RegisterModuleInterface<IGroupsModule>(this); } public void PostInitialise() { } public void Close() { m_log.Debug("[GROUPS]: Shutting down group module."); } public string Name { get { return "GroupsModule"; } } public bool IsSharedModule { get { return true; } } #endregion private void UpdateClientWithGroupInfo(IClientAPI client) { OnAgentDataUpdateRequest(client, client.AgentId, UUID.Zero); // Need to send a group membership update to the client // UDP version doesn't seem to behave nicely // client.SendGroupMembership(GetMembershipData(client.AgentId)); GroupMembershipData[] membershipData = GetMembershipData(client.AgentId); foreach (GroupMembershipData membership in membershipData) { osGroupMemberInfo memberInfo = m_GroupMemberInfo[client.AgentId][membership.GroupID]; osgRole roleInfo = memberInfo.Roles[membership.ActiveRole]; m_log.InfoFormat("[Groups] {0} member of {1} title active (2)", client.FirstName, membership.GroupName, roleInfo.Name, membership.Active); } SendGroupMembershipInfoViaCaps(client, membershipData); client.SendAvatarGroupsReply(client.AgentId, membershipData); } #region EventHandlers private void OnNewClient(IClientAPI client) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Subscribe to instant messages // client.OnInstantMessage += OnInstantMessage; lock (m_ActiveClients) { if (!m_ActiveClients.ContainsKey(client.AgentId)) { client.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnDirFindQuery += OnDirFindQuery; m_ActiveClients.Add(client.AgentId, client); } } UpdateClientWithGroupInfo(client); } void OnDirFindQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { if (((DirFindFlags)queryFlags & DirFindFlags.Groups) == DirFindFlags.Groups) { m_log.InfoFormat("[Groups] {0} called with queryText({1}) queryFlags({2}) queryStart({3})", System.Reflection.MethodBase.GetCurrentMethod().Name, queryText, (DirFindFlags)queryFlags, queryStart); List<DirGroupsReplyData> ReplyData = new List<DirGroupsReplyData>(); int order = 0; foreach (osGroup group in m_Groups.Values) { if (group.Name.ToLower().Contains(queryText.ToLower())) { if (queryStart <= order) { DirGroupsReplyData data = new DirGroupsReplyData(); data.groupID = group.GroupID; data.groupName = group.Name; data.members = group.GroupMembershipCount; data.searchOrder = order; ReplyData.Add(data); } order += 1; } } remoteClient.SendDirGroupsReply(queryID, ReplyData.ToArray()); } } private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID AgentID, UUID SessionID) { m_log.InfoFormat("[Groups] {0} called with SessionID :: {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, SessionID); UUID ActiveGroupID; string ActiveGroupTitle = string.Empty; string ActiveGroupName = string.Empty; ulong ActiveGroupPowers = (ulong)GroupPowers.None; if( m_AgentActiveGroup.TryGetValue(AgentID, out ActiveGroupID) ) { if ((ActiveGroupID != null) && (ActiveGroupID != UUID.Zero)) { osGroup group = m_Groups[ActiveGroupID]; osGroupMemberInfo membership = m_GroupMemberInfo[AgentID][ActiveGroupID]; ActiveGroupName = group.Name; if (membership.SelectedTitleRole != UUID.Zero) { ActiveGroupTitle = membership.Roles[membership.SelectedTitleRole].Title; } // Gather up all the powers from agent's roles, then mask them with group mask foreach (osgRole role in membership.Roles.Values) { ActiveGroupPowers |= (ulong)role.Powers; } ActiveGroupPowers &= (ulong)group.PowersMask; } else { ActiveGroupID = UUID.Zero; } } else { // I think this is needed bcasue the TryGetValue() will set this to null ActiveGroupID = UUID.Zero; } string firstname, lastname; IClientAPI agent; if( m_ActiveClients.TryGetValue(AgentID, out agent) ) { firstname = agent.FirstName; lastname = agent.LastName; } else { firstname = "Unknown"; lastname = "Unknown"; } m_log.InfoFormat("[Groups] Active Powers {0}, Group {1}, Title {2}", ActiveGroupPowers, ActiveGroupName, ActiveGroupTitle); remoteClient.SendAgentDataUpdate(AgentID, ActiveGroupID, firstname, lastname, ActiveGroupPowers, ActiveGroupName, ActiveGroupTitle); } private void OnInstantMessage(IClientAPI client, GridInstantMessage im) { m_log.WarnFormat("[Groups] {0} is not implemented", System.Reflection.MethodBase.GetCurrentMethod().Name); // Probably for monitoring and dealing with group instant messages } private void OnGridInstantMessage(GridInstantMessage msg) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Trigger the above event handler OnInstantMessage(null, msg); } private void HandleUUIDGroupNameRequest(UUID GroupID,IClientAPI remote_client) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string GroupName; osGroup group; if (m_Groups.TryGetValue(GroupID, out group)) { GroupName = group.Name; } else { GroupName = "Unknown"; } remote_client.SendGroupNameReply(GroupID, GroupName); } private void OnClientClosed(UUID AgentId) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); lock (m_ActiveClients) { if (m_ActiveClients.ContainsKey(AgentId)) { IClientAPI client = m_ActiveClients[AgentId]; client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; client.OnDirFindQuery -= OnDirFindQuery; m_ActiveClients.Remove(AgentId); } } } #endregion public const GroupPowers AllGroupPowers = GroupPowers.Accountable | GroupPowers.AllowEditLand | GroupPowers.AllowFly | GroupPowers.AllowLandmark | GroupPowers.AllowRez | GroupPowers.AllowSetHome | GroupPowers.AllowVoiceChat | GroupPowers.AssignMember | GroupPowers.AssignMemberLimited | GroupPowers.ChangeActions | GroupPowers.ChangeIdentity | GroupPowers.ChangeMedia | GroupPowers.ChangeOptions | GroupPowers.CreateRole | GroupPowers.DeedObject | GroupPowers.DeleteRole | GroupPowers.Eject | GroupPowers.FindPlaces | GroupPowers.Invite | GroupPowers.JoinChat | GroupPowers.LandChangeIdentity | GroupPowers.LandDeed | GroupPowers.LandDivideJoin | GroupPowers.LandEdit | GroupPowers.LandEjectAndFreeze | GroupPowers.LandGardening | GroupPowers.LandManageAllowed | GroupPowers.LandManageBanned | GroupPowers.LandManagePasses | GroupPowers.LandOptions | GroupPowers.LandRelease | GroupPowers.LandSetSale | GroupPowers.ModerateChat | GroupPowers.ObjectManipulate | GroupPowers.ObjectSetForSale | GroupPowers.ReceiveNotices | GroupPowers.RemoveMember | GroupPowers.ReturnGroupOwned | GroupPowers.ReturnGroupSet | GroupPowers.ReturnNonGroup | GroupPowers.RoleProperties | GroupPowers.SendNotices | GroupPowers.SetLandingPoint | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome | GroupPowers.Accountable | GroupPowers.JoinChat | GroupPowers.AllowVoiceChat | GroupPowers.ReceiveNotices | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; class osGroup { public UUID GroupID = UUID.Zero; public string Name = string.Empty; public string Charter = string.Empty; public string MemberTitle = "Everyone"; public GroupPowers PowersMask = AllGroupPowers; public UUID InsigniaID = UUID.Zero; public UUID FounderID = UUID.Zero; public int MembershipFee = 0; public bool OpenEnrollment = true; public bool ShowInList = true; public int Money = 0; public bool AllowPublish = true; public bool MaturePublish = true; public UUID OwnerRoleID = UUID.Zero; public Dictionary<UUID, osgRole> Roles = new Dictionary<UUID, osgRole>(); public Dictionary<UUID, osGroupMemberInfo> Members = new Dictionary<UUID, osGroupMemberInfo>(); // Should be calculated public int GroupMembershipCount { get { return Members.Count; } } public int GroupRolesCount { get { return Roles.Count; } } } class osgRole { public osGroup Group = null; public UUID RoleID = UUID.Zero; public string Name = string.Empty; public string Title = string.Empty; public string Description = string.Empty; public GroupPowers Powers = AllGroupPowers; public Dictionary<UUID, osGroupMemberInfo> RoleMembers = new Dictionary<UUID, osGroupMemberInfo>(); // Should be calculated public int Members { get { return RoleMembers.Count; } } } class osGroupMemberInfo { public Dictionary<UUID, osgRole> Roles = new Dictionary<UUID,osgRole>(); public UUID AgentID = UUID.Zero; public UUID SelectedTitleRole = UUID.Zero; // FixMe: This is wrong, the contribution should be per group not per role public int Contribution = 0; public bool ListInProfile = true; public bool AcceptNotices = true; // Should be looked up public string Title { get { if (Roles.ContainsKey(SelectedTitleRole)) { return Roles[SelectedTitleRole].Name; } else { return string.Empty; } } } } private void UpdateScenePresenceWithTitle(UUID AgentID, string Title) { ScenePresence presence = null; lock (m_SceneList) { foreach (Scene scene in m_SceneList) { presence = scene.GetScenePresence(AgentID); if (presence != null) { presence.Grouptitle = Title; // FixMe: Ter suggests a "Schedule" method that I can't find. presence.SendFullUpdateToAllClients(); break; } } } } #region IGroupsModule Members public event NewGroupNotice OnNewGroupNotice; public void ActivateGroup(IClientAPI remoteClient, UUID groupID) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string Title = ""; if (groupID == UUID.Zero) { // Setting to no group active, "None" m_AgentActiveGroup[remoteClient.AgentId] = groupID; } else if (m_Groups.ContainsKey(groupID)) { osGroup group = m_Groups[groupID]; if (group.Members.ContainsKey(remoteClient.AgentId)) { m_AgentActiveGroup[remoteClient.AgentId] = groupID; osGroupMemberInfo member = group.Members[remoteClient.AgentId]; Title = group.Roles[member.SelectedTitleRole].Title; } } UpdateScenePresenceWithTitle(remoteClient.AgentId, Title); UpdateClientWithGroupInfo(remoteClient); } public List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupTitlesData> groupTitles = new List<GroupTitlesData>(); Dictionary<UUID, osGroupMemberInfo> memberships; if (m_GroupMemberInfo.TryGetValue(remoteClient.AgentId, out memberships)) { if( memberships.ContainsKey(groupID) ) { osGroupMemberInfo member = memberships[groupID]; foreach (osgRole role in member.Roles.Values) { GroupTitlesData data; data.Name = role.Title; data.UUID = role.RoleID; if (role.RoleID == member.SelectedTitleRole) { data.Selected = true; } else { data.Selected = false; } groupTitles.Add(data); } } } return groupTitles; } public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupMembersData> groupMembers = new List<GroupMembersData>(); osGroup group; if (m_Groups.TryGetValue(groupID, out group)) { foreach (osGroupMemberInfo member in group.Members.Values) { GroupMembersData data = new GroupMembersData(); data.AcceptNotices = member.AcceptNotices; data.AgentID = member.AgentID; data.Contribution = member.Contribution; data.IsOwner = member.Roles.ContainsKey(group.OwnerRoleID); data.ListInProfile = member.ListInProfile; data.AgentPowers = 0; foreach (osgRole role in member.Roles.Values) { data.AgentPowers |= (ulong)role.Powers; if (role.RoleID == member.SelectedTitleRole) { data.Title = role.Title; } } // FIXME: need to look this up. // data.OnlineStatus groupMembers.Add(data); } } return groupMembers; } public List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> rolesData = new List<GroupRolesData>(); osGroup group; if (m_Groups.TryGetValue(groupID, out group)) { foreach (osgRole role in group.Roles.Values) { GroupRolesData data = new GroupRolesData(); data.Description = role.Description; data.Members = role.Members; data.Name = role.Name; data.Powers = (ulong)role.Powers; data.RoleID = role.RoleID; data.Title = role.Title; m_log.DebugFormat("[Groups] Role {0} :: Powers {1}", role.Name, data.Powers); rolesData.Add(data); } } return rolesData; } public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRoleMembersData> roleMemberData = new List<GroupRoleMembersData>(); osGroup group; if (m_Groups.TryGetValue(groupID, out group)) { foreach (osgRole role in group.Roles.Values) { foreach (osGroupMemberInfo member in role.RoleMembers.Values) { GroupRoleMembersData data = new GroupRoleMembersData(); data.RoleID = role.RoleID; data.MemberID = member.AgentID; m_log.DebugFormat("[Groups] Role {0} :: Member {1}", role.Name, member.AgentID); roleMemberData.Add(data); } } } return roleMemberData; } public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupProfileData profile = new GroupProfileData(); osGroup group; if (m_Groups.TryGetValue(groupID, out group)) { profile.AllowPublish = group.AllowPublish; profile.Charter = group.Charter; profile.FounderID = group.FounderID; profile.GroupID = group.GroupID; profile.GroupMembershipCount = group.GroupMembershipCount; profile.GroupRolesCount = group.GroupRolesCount; profile.InsigniaID = group.InsigniaID; profile.MaturePublish = group.MaturePublish; profile.MembershipFee = group.MembershipFee; profile.MemberTitle = group.MemberTitle; profile.Money = group.Money; profile.Name = group.Name; profile.OpenEnrollment = group.OpenEnrollment; profile.OwnerRole = group.OwnerRoleID; profile.PowersMask = (ulong)group.PowersMask; profile.ShowInList = group.ShowInList; } return profile; } public GroupMembershipData[] GetMembershipData(UUID UserID) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupMembershipData> membershipData = new List<GroupMembershipData>(); foreach ( UUID GroupID in m_Groups.Keys) { GroupMembershipData membership = GetMembershipData(GroupID, UserID); if (membership != null) { membershipData.Add(membership); } } return membershipData.ToArray(); } public GroupMembershipData GetMembershipData(UUID GroupID, UUID UserID) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); osGroup group; if (m_Groups.TryGetValue(GroupID, out group)) { osGroupMemberInfo member; if (group.Members.TryGetValue(UserID, out member)) { GroupMembershipData data = new GroupMembershipData(); data.AcceptNotices = member.AcceptNotices; data.Contribution = member.Contribution; data.ListInProfile = member.ListInProfile; data.ActiveRole = member.SelectedTitleRole; data.GroupTitle = member.Roles[member.SelectedTitleRole].Title; foreach (osgRole role in member.Roles.Values) { data.GroupPowers |= (ulong)role.Powers; if (m_AgentActiveGroup.ContainsKey(UserID) && (m_AgentActiveGroup[UserID] == role.RoleID)) { data.Active = true; } } data.AllowPublish = group.AllowPublish; data.Charter = group.Charter; data.FounderID = group.FounderID; data.GroupID = group.GroupID; data.GroupName = group.Name; data.GroupPicture = group.InsigniaID; data.MaturePublish = group.MaturePublish; data.MembershipFee = group.MembershipFee; data.OpenEnrollment = group.OpenEnrollment; data.ShowInList = group.ShowInList; return data; } } return null; } public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: Security Check? osGroup group; if (m_Groups.TryGetValue(groupID, out group)) { group.Charter = charter; group.ShowInList = showInList; group.InsigniaID = insigniaID; group.MembershipFee = membershipFee; group.OpenEnrollment = openEnrollment; group.AllowPublish = allowPublish; group.MaturePublish = maturePublish; } } public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile) { // TODO: Security Check? m_log.WarnFormat("[Groups] {0} is not implemented", System.Reflection.MethodBase.GetCurrentMethod().Name); } private osGroupMemberInfo AddAgentToGroup(UUID AgentID, osGroup existingGroup) { if (existingGroup.Members.ContainsKey(AgentID)) { return existingGroup.Members[AgentID]; } osGroupMemberInfo newMembership = new osGroupMemberInfo(); newMembership.AgentID = AgentID; newMembership.AcceptNotices = true; newMembership.Contribution = 0; newMembership.ListInProfile = true; newMembership.SelectedTitleRole = UUID.Zero; // Everyone Role newMembership.Roles.Add(UUID.Zero, existingGroup.Roles[UUID.Zero]); existingGroup.Roles[UUID.Zero].RoleMembers.Add(AgentID, newMembership); // Make sure the member is in the big Group Membership lookup dictionary if (!m_GroupMemberInfo.ContainsKey(AgentID)) { m_GroupMemberInfo.Add(AgentID, new Dictionary<UUID, osGroupMemberInfo>()); } // Add this particular membership to the lookup m_GroupMemberInfo[AgentID].Add(existingGroup.GroupID, newMembership); // Add member to group's local list of members existingGroup.Members.Add(AgentID, newMembership); return newMembership; } private osGroupMemberInfo AddAgentToGroup(UUID AgentID, UUID GroupID) { osGroup group; if (m_Groups.TryGetValue(GroupID, out group)) { return AddAgentToGroup(AgentID, group); } // FixMe: Need to do something here if group doesn't exist return null; } private osgRole AddRole2Group(osGroup group, string name, string description, string title, GroupPowers powers) { return AddRole2Group(group, name, description, title, powers, UUID.Random()); } private osgRole AddRole2Group(osGroup group, string name, string description, string title, GroupPowers powers, UUID roleid) { osgRole newRole = new osgRole(); // everyoneRole.RoleID = UUID.Random(); newRole.RoleID = roleid; newRole.Name = name; newRole.Description = description; newRole.Powers = (GroupPowers)powers & group.PowersMask; newRole.Title = title; newRole.Group = group; group.Roles.Add(newRole.RoleID, newRole); return newRole; } public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); foreach (osGroup existingGroup in m_Groups.Values) { if (existingGroup.Name.ToLower().Trim().Equals(name.ToLower().Trim())) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists."); return UUID.Zero; } } osGroup newGroup = new osGroup(); newGroup.GroupID = UUID.Random(); newGroup.Name = name; newGroup.Charter = charter; newGroup.ShowInList = showInList; newGroup.InsigniaID = insigniaID; newGroup.MembershipFee = membershipFee; newGroup.OpenEnrollment = openEnrollment; newGroup.AllowPublish = allowPublish; newGroup.MaturePublish = maturePublish; newGroup.PowersMask = AllGroupPowers; newGroup.FounderID = remoteClient.AgentId; // Setup members role osgRole everyoneRole = AddRole2Group(newGroup, "Everyone", "Everyone in the group is in the everyone role.", "Everyone Title", m_DefaultEveryonePowers, UUID.Zero); // Setup owners role osgRole ownerRole = AddRole2Group(newGroup, "Owners", "Owners of " + newGroup.Name, "Owner of " + newGroup.Name, AllGroupPowers); osGroupMemberInfo Member = AddAgentToGroup(remoteClient.AgentId, newGroup); // Put the founder in the owner and everyone role Member.Roles.Add(ownerRole.RoleID, ownerRole); // Add founder to owner & everyone's local lists of members ownerRole.RoleMembers.Add(Member.AgentID, Member); // Add group to module m_Groups.Add(newGroup.GroupID, newGroup); remoteClient.SendCreateGroupReply(newGroup.GroupID, true, "Group created successfullly"); // Set this as the founder's active group ActivateGroup(remoteClient, newGroup.GroupID); // The above sends this out too as of 4/3/09 // UpdateClientWithGroupInfo(remoteClient); return newGroup.GroupID; } public GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID GroupID) { m_log.WarnFormat("[Groups] {0} is not implemented", System.Reflection.MethodBase.GetCurrentMethod().Name); return new GroupNoticeData[0]; } /// <summary> /// Get the title of the agent's current role. /// </summary> public string GetGroupTitle(UUID avatarID) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); UUID activeGroupID; // Check if they have an active group listing if (m_AgentActiveGroup.TryGetValue(avatarID, out activeGroupID)) { // See if they have any group memberships if( m_GroupMemberInfo.ContainsKey(avatarID) ) { // See if the have a group membership for the group they have marked active if( m_GroupMemberInfo[avatarID].ContainsKey(activeGroupID) ) { osGroupMemberInfo membership = m_GroupMemberInfo[avatarID][activeGroupID]; // Return the title of the role they currently have marked as their selected active role/title return membership.Roles[membership.SelectedTitleRole].Title; } } } return string.Empty; } /// <summary> /// Change the current Active Group Role for Agent /// </summary> public void GroupTitleUpdate(IClientAPI remoteClient, UUID GroupID, UUID TitleRoleID) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // See if they have any group memberships if (m_GroupMemberInfo.ContainsKey(remoteClient.AgentId)) { // See if the have a group membership for the group whose title they want to change if (m_GroupMemberInfo[remoteClient.AgentId].ContainsKey(GroupID)) { osGroupMemberInfo membership = m_GroupMemberInfo[remoteClient.AgentId][GroupID]; // make sure they're a member of the role they're trying to mark active if (membership.Roles.ContainsKey(TitleRoleID)) { membership.SelectedTitleRole = TitleRoleID; UpdateClientWithGroupInfo(remoteClient); } } } } public void GroupRoleUpdate(IClientAPI remoteClient, UUID GroupID, UUID RoleID, string name, string description, string title, ulong powers, byte updateType) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: Security Check? osGroup group; if (m_Groups.TryGetValue(GroupID, out group)) { osgRole role; switch ((OpenMetaverse.GroupRoleUpdate)updateType) { case OpenMetaverse.GroupRoleUpdate.Create: role = AddRole2Group(group, name, description, title, (GroupPowers)powers, RoleID == UUID.Zero ? UUID.Random() : RoleID); break; case OpenMetaverse.GroupRoleUpdate.Delete: if (group.Roles.TryGetValue(RoleID, out role)) { List<UUID> Members2Remove = new List<UUID>(); // Remove link from membership to this role foreach(osGroupMemberInfo membership in role.RoleMembers.Values) { membership.Roles.Remove(role.RoleID); Members2Remove.Add(membership.AgentID); if (membership.SelectedTitleRole == role.RoleID) { membership.SelectedTitleRole = UUID.Zero; } } // Remove link from this role to the membership foreach (UUID member in Members2Remove) { role.RoleMembers.Remove(member); } // Remove the role from the group group.Roles.Remove(RoleID); } break; case OpenMetaverse.GroupRoleUpdate.UpdateAll: case OpenMetaverse.GroupRoleUpdate.UpdateData: case OpenMetaverse.GroupRoleUpdate.UpdatePowers: if (group.Roles.TryGetValue(RoleID, out role)) { role.Name = name; role.Description = description; role.Title = title; role.Powers = (GroupPowers)powers; } break; case OpenMetaverse.GroupRoleUpdate.NoUpdate: default: // No Op break; } UpdateClientWithGroupInfo(remoteClient); } } public void GroupRoleChanges(IClientAPI remoteClient, UUID GroupID, UUID RoleID, UUID MemberID, uint changes) { // Todo: Security check osGroup group; if (m_Groups.TryGetValue(GroupID, out group)) { // Must already be a member osGroupMemberInfo membership; if (m_GroupMemberInfo.ContainsKey(MemberID) && m_GroupMemberInfo[MemberID].ContainsKey(GroupID)) { membership = m_GroupMemberInfo[MemberID][GroupID]; osgRole role; if (group.Roles.TryGetValue(RoleID, out role)) { switch (changes) { case 0: // Add membership.Roles[RoleID] = role; role.RoleMembers[MemberID] = membership; break; case 1: // Remove if (membership.Roles.ContainsKey(RoleID)) { membership.Roles.Remove(RoleID); } if (role.RoleMembers.ContainsKey(MemberID)) { role.RoleMembers.Remove(MemberID); } break; default: m_log.ErrorFormat("[Groups] {0} does not understand changes == {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, changes); break; } UpdateClientWithGroupInfo(remoteClient); } } } } public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID) { m_log.WarnFormat("[Groups] {0} is not implemented", System.Reflection.MethodBase.GetCurrentMethod().Name); } public GridInstantMessage CreateGroupNoticeIM(UUID agentID, UUID groupNoticeID, byte dialog) { m_log.WarnFormat("[Groups] {0} is not properly implemented", System.Reflection.MethodBase.GetCurrentMethod().Name); IClientAPI agent = m_ActiveClients[agentID]; return new GridInstantMessage(agent.Scene, agentID, agent.Name, UUID.Zero, dialog, string.Empty, false, Vector3.Zero); } public void SendAgentGroupDataUpdate(IClientAPI remoteClient) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); UpdateClientWithGroupInfo(remoteClient); } public void JoinGroupRequest(IClientAPI remoteClient, UUID GroupID) { // Should check to see if OpenEnrollment, or if there's an outstanding invitation if (AddAgentToGroup(remoteClient.AgentId, GroupID) != null) { remoteClient.SendJoinGroupReply(GroupID, true); UpdateClientWithGroupInfo(remoteClient); } remoteClient.SendJoinGroupReply(GroupID, false); } public void LeaveGroupRequest(IClientAPI remoteClient, UUID GroupID) { osGroup group; if (m_Groups.TryGetValue(GroupID, out group)) { if (group.Members.ContainsKey(remoteClient.AgentId)) { osGroupMemberInfo member = group.Members[remoteClient.AgentId]; // Remove out of each role in group foreach (osgRole role in member.Roles.Values) { role.RoleMembers.Remove(member.AgentID); } // Remove member from Group's list of members group.Members.Remove(member.AgentID); // Make sure this group isn't the user's current active group if (m_AgentActiveGroup.ContainsKey(member.AgentID) && (m_AgentActiveGroup[member.AgentID] == group.GroupID)) { ActivateGroup(remoteClient, UUID.Zero); } // Remove from global lookup index if (m_GroupMemberInfo.ContainsKey(member.AgentID)) { m_GroupMemberInfo[member.AgentID].Remove(group.GroupID); } UpdateClientWithGroupInfo(remoteClient); remoteClient.SendLeaveGroupReply(GroupID, true); } } remoteClient.SendLeaveGroupReply(GroupID, false); } public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID GroupID, UUID EjecteeID) { // Todo: Security check? m_log.WarnFormat("[Groups] {0} is not implemented", System.Reflection.MethodBase.GetCurrentMethod().Name); // SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success) } public void InviteGroupRequest(IClientAPI remoteClient, UUID GroupID, UUID InviteeID, UUID RoleID) { m_log.WarnFormat("[Groups] {0} is not implemented", System.Reflection.MethodBase.GetCurrentMethod().Name); } #endregion void SendGroupMembershipInfoViaCaps(IClientAPI remoteClient, GroupMembershipData[] data) { m_log.InfoFormat("[Groups] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDArray AgentData = new OSDArray(1); OSDMap AgentDataMap = new OSDMap(1); AgentDataMap.Add("AgentID", OSD.FromUUID(remoteClient.AgentId)); AgentData.Add(AgentDataMap); OSDArray GroupData = new OSDArray(data.Length); OSDArray NewGroupData = new OSDArray(data.Length); foreach (GroupMembershipData membership in data) { OSDMap GroupDataMap = new OSDMap(6); OSDMap NewGroupDataMap = new OSDMap(1); GroupDataMap.Add("GroupID", OSD.FromUUID(membership.GroupID)); GroupDataMap.Add("GroupPowers", OSD.FromBinary(membership.GroupPowers)); GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(membership.AcceptNotices)); GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(membership.GroupPicture)); GroupDataMap.Add("Contribution", OSD.FromInteger(membership.Contribution)); GroupDataMap.Add("GroupName", OSD.FromString(membership.GroupName)); NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(membership.ListInProfile)); GroupData.Add(GroupDataMap); NewGroupData.Add(NewGroupDataMap); } OSDMap llDataStruct = new OSDMap(3); llDataStruct.Add("AgentData", AgentData); llDataStruct.Add("GroupData", GroupData); llDataStruct.Add("NewGroupData", NewGroupData); IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); if (queue != null) { queue.Enqueue(EventQueueHelper.buildEvent("AgentGroupDataUpdate", llDataStruct), remoteClient.AgentId); } } } }
/* Copyright (c) 2006-2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Change history * Oct 13 2008 Joe Feser joseph.feser@gmail.com * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ #define USE_TRACING #define DEBUG using System; using System.IO; using System.Xml; using System.Collections; using System.Configuration; using System.Net; using NUnit.Framework; using Google.GData.Client; using Google.GData.Client.UnitTests; using Google.GData.Extensions; using Google.GData.Photos; using Google.GData.Extensions.Exif; using Google.GData.Extensions.Location; using Google.GData.Extensions.MediaRss; namespace Google.GData.Client.LiveTests { [TestFixture] [Category("LiveTest")] public class PhotosTestSuite : BaseLiveTestClass { /// <summary> /// test Uri for google calendarURI /// </summary> protected string defaultPhotosUri; ////////////////////////////////////////////////////////////////////// /// <summary>default empty constructor</summary> ////////////////////////////////////////////////////////////////////// public PhotosTestSuite() { } public override string ServiceName { get { return PicasaService.GPicasaService; } } ////////////////////////////////////////////////////////////////////// /// <summary>private void ReadConfigFile()</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// protected override void ReadConfigFile() { base.ReadConfigFile(); if (unitTestConfiguration.Contains("photosUri")) { this.defaultPhotosUri = (string) unitTestConfiguration["photosUri"]; Tracing.TraceInfo("Read photosUri value: " + this.defaultPhotosUri); } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test</summary> ////////////////////////////////////////////////////////////////////// [Test] public void PhotosAuthenticationTest() { Tracing.TraceMsg("Entering PhotosAuthenticationTest"); PicasaQuery query = new PicasaQuery(); PicasaService service = new PicasaService("unittests"); query.KindParameter = "album,tag"; if (this.defaultPhotosUri != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } query.Uri = new Uri(this.defaultPhotosUri); AtomFeed feed = service.Query(query); ObjectModelHelper.DumpAtomObject(feed,CreateDumpFileName("PhotoAuthTest")); if (feed != null && feed.Entries.Count > 0) { Tracing.TraceMsg("Found a Feed " + feed.ToString()); DisplayExtensions(feed); foreach (AtomEntry entry in feed.Entries) { Tracing.TraceMsg("Found an entry " + entry.ToString()); DisplayExtensions(entry); } } } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test, iterates all entries</summary> ////////////////////////////////////////////////////////////////////// [Test] public void QueryPhotosTest() { Tracing.TraceMsg("Entering PhotosQueryPhotosTest"); PhotoQuery query = new PhotoQuery(); PicasaService service = new PicasaService("unittests"); if (this.defaultPhotosUri != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } GDataLoggingRequestFactory factory = (GDataLoggingRequestFactory) this.factory; factory.MethodOverride = true; service.RequestFactory = this.factory; query.Uri = new Uri(this.defaultPhotosUri); PicasaFeed feed = service.Query(query); ObjectModelHelper.DumpAtomObject(feed,CreateDumpFileName("PhotoAuthTest")); if (feed != null && feed.Entries.Count > 0) { Tracing.TraceMsg("Found a Feed " + feed.ToString()); DisplayExtensions(feed); foreach (PicasaEntry entry in feed.Entries) { Tracing.TraceMsg("Found an entry " + entry.ToString()); DisplayExtensions(entry); GeoRssWhere w = entry.Location; if (w != null) { Tracing.TraceMsg("Found an location " + w.Latitude + w.Longitude); } ExifTags tags = entry.Exif; if (tags != null) { Tracing.TraceMsg("Found an exif block "); } MediaGroup group = entry.Media; if (group != null) { Tracing.TraceMsg("Found a media Group"); if (group.Title != null) { Tracing.TraceMsg(group.Title.Value); } if (group.Keywords != null) { Tracing.TraceMsg(group.Keywords.Value); } if (group.Credit != null) { Tracing.TraceMsg(group.Credit.Value); } if (group.Description != null) { Tracing.TraceMsg(group.Description.Value); } } PhotoAccessor photo = new PhotoAccessor(entry); Assert.IsTrue(entry.IsPhoto, "this is a photo entry, it should have the kind set"); Assert.IsTrue(photo != null, "this is a photo entry, it should convert to PhotoEntry"); Assert.IsTrue(photo.AlbumId != null); Assert.IsTrue(photo.Height > 0); Assert.IsTrue(photo.Width > 0); } } factory.MethodOverride = false; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test, inserts a new photo</summary> ////////////////////////////////////////////////////////////////////// [Test] public void InsertPhotoTest() { Tracing.TraceMsg("Entering InsertPhotoTest"); AlbumQuery query = new AlbumQuery(); PicasaService service = new PicasaService("unittests"); if (this.defaultPhotosUri != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } query.Uri = new Uri(this.defaultPhotosUri); PicasaFeed feed = service.Query(query); if (feed != null) { Assert.IsTrue(feed.Entries != null, "the albumfeed needs entries"); Assert.IsTrue(feed.Entries[0] != null, "the albumfeed needs at least ONE entry"); PicasaEntry album = feed.Entries[0] as PicasaEntry; Assert.IsTrue(album != null, "should be an album there"); Assert.IsTrue(album.FeedUri != null, "the albumfeed needs a feed URI, no photo post on that one"); Uri postUri = new Uri(album.FeedUri.ToString()); FileStream fs = File.OpenRead(this.resourcePath + "testnet.jpg"); PicasaEntry entry = service.Insert(postUri, fs, "image/jpeg", "testnet.jpg") as PicasaEntry; Assert.IsTrue(entry.IsPhoto, "the new entry should be a photo entry"); entry.Title.Text = "This is a new Title"; entry.Summary.Text = "A lovely shot in the shade"; PicasaEntry updatedEntry = entry.Update() as PicasaEntry; Assert.IsTrue(updatedEntry.IsPhoto, "the new entry should be a photo entry"); Assert.IsTrue(updatedEntry.Title.Text == "This is a new Title", "The titles should be identical"); Assert.IsTrue(updatedEntry.Summary.Text == "A lovely shot in the shade", "The summariesa should be identical"); } } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>tries to insert a photo using MIME multipart</summary> ////////////////////////////////////////////////////////////////////// [Test] public void InsertMimePhotoTest() { Tracing.TraceMsg("Entering InsertMimePhotoTest"); AlbumQuery query = new AlbumQuery(); PicasaService service = new PicasaService("unittests"); if (this.defaultPhotosUri != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } query.Uri = new Uri(this.defaultPhotosUri); PicasaFeed feed = service.Query(query); if (feed != null) { Assert.IsTrue(feed.Entries != null, "the albumfeed needs entries"); Assert.IsTrue(feed.Entries[0] != null, "the albumfeed needs at least ONE entry"); PicasaEntry album = feed.Entries[0] as PicasaEntry; PhotoEntry newPhoto = new PhotoEntry(); newPhoto.Title.Text = "this is a title"; newPhoto.Summary.Text = "A lovely shot in the ocean"; newPhoto.MediaSource = new MediaFileSource(this.resourcePath + "testnet.jpg", "image/jpeg"); Uri postUri = new Uri(album.FeedUri.ToString()); PicasaEntry entry = service.Insert(postUri, newPhoto) as PicasaEntry; Assert.IsTrue(entry.IsPhoto, "the new entry should be a photo entry"); entry.Title.Text = "This is a new Title"; entry.Summary.Text = "A lovely shot in the shade"; entry.MediaSource = new MediaFileSource(this.resourcePath + "testnet.jpg", "image/jpeg"); PicasaEntry updatedEntry = entry.Update() as PicasaEntry; Assert.IsTrue(updatedEntry.IsPhoto, "the new entry should be a photo entry"); Assert.IsTrue(updatedEntry.Title.Text == "This is a new Title", "The titles should be identical"); Assert.IsTrue(updatedEntry.Summary.Text == "A lovely shot in the shade", "The summariesa should be identical"); } } } ///////////////////////////////////////////////////////////////////////////// protected void DisplayExtensions(AtomBase obj) { foreach (Object o in obj.ExtensionElements) { IExtensionElementFactory e = o as IExtensionElementFactory; SimpleElement s = o as SimpleElement; XmlElement x = o as XmlElement; if (s != null) { DumpSimpleElement(s); SimpleContainer sc = o as SimpleContainer; if (sc != null) { foreach (SimpleElement se in sc.ExtensionElements) { DumpSimpleElement(se); } } } else if (e != null) { Tracing.TraceMsg("Found an extension Element " + e.ToString()); } else if (x != null) { Tracing.TraceMsg("Found an XmlElement " + x.ToString() + " " + x.LocalName + " " + x.NamespaceURI); } else { Tracing.TraceMsg("Found an object " + o.ToString()); } } } protected void DumpSimpleElement(SimpleElement s) { Tracing.TraceMsg("Found a simple Element " + s.ToString() + " " + s.Value); if (s.Attributes.Count > 0) { for (int i=0; i < s.Attributes.Count; i++) { string name = s.Attributes.GetKey(i) as string; string value = s.Attributes.GetByIndex(i) as string; Tracing.TraceMsg("--- Attributes on element: " + name + ":" + value); } } } } ///////////////////////////////////////////////////////////////////////////// }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Streams; using Orleans.Configuration; namespace Orleans.Providers { /// <summary> /// Adapter factory for in memory stream provider. /// This factory acts as the adapter and the adapter factory. The events are stored in an in-memory grain that /// behaves as an event queue, this provider adapter is primarily used for testing /// </summary> public class MemoryAdapterFactory<TSerializer> : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache where TSerializer : class, IMemoryMessageBodySerializer { private readonly StreamCacheEvictionOptions cacheOptions; private readonly StreamStatisticOptions statisticOptions; private readonly HashRingStreamQueueMapperOptions queueMapperOptions; private readonly IGrainFactory grainFactory; private readonly ITelemetryProducer telemetryProducer; private readonly ILoggerFactory loggerFactory; private readonly ILogger logger; private readonly TSerializer serializer; private IStreamQueueMapper streamQueueMapper; private ConcurrentDictionary<QueueId, IMemoryStreamQueueGrain> queueGrains; private IObjectPool<FixedSizeBuffer> bufferPool; private BlockPoolMonitorDimensions blockPoolMonitorDimensions; private IStreamFailureHandler streamFailureHandler; private TimePurgePredicate purgePredicate; /// <summary> /// Name of the adapter. Primarily for logging purposes /// </summary> public string Name { get; } /// <summary> /// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time. /// </summary> /// <returns>True if this is a rewindable stream adapter, false otherwise.</returns> public bool IsRewindable => true; /// <summary> /// Direction of this queue adapter: Read, Write or ReadWrite. /// </summary> /// <returns>The direction in which this adapter provides data.</returns> public StreamProviderDirection Direction => StreamProviderDirection.ReadWrite; /// <summary> /// Creates a failure handler for a partition. /// </summary> protected Func<string, Task<IStreamFailureHandler>> StreamFailureHandlerFactory { get; set; } /// <summary> /// Create a cache monitor to report cache related metrics /// Return a ICacheMonitor /// </summary> protected Func<CacheMonitorDimensions, ITelemetryProducer, ICacheMonitor> CacheMonitorFactory; /// <summary> /// Create a block pool monitor to monitor block pool related metrics /// Return a IBlockPoolMonitor /// </summary> protected Func<BlockPoolMonitorDimensions, ITelemetryProducer, IBlockPoolMonitor> BlockPoolMonitorFactory; /// <summary> /// Create a monitor to monitor QueueAdapterReceiver related metrics /// Return a IQueueAdapterReceiverMonitor /// </summary> protected Func<ReceiverMonitorDimensions, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory; public MemoryAdapterFactory(string providerName, StreamCacheEvictionOptions cacheOptions, StreamStatisticOptions statisticOptions, HashRingStreamQueueMapperOptions queueMapperOptions, IServiceProvider serviceProvider, IGrainFactory grainFactory, ITelemetryProducer telemetryProducer, ILoggerFactory loggerFactory) { this.Name = providerName; this.queueMapperOptions = queueMapperOptions ?? throw new ArgumentNullException(nameof(queueMapperOptions)); this.cacheOptions = cacheOptions ?? throw new ArgumentNullException(nameof(cacheOptions)); this.statisticOptions = statisticOptions ?? throw new ArgumentException(nameof(statisticOptions)); this.grainFactory = grainFactory ?? throw new ArgumentNullException(nameof(grainFactory)); this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer)); this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); this.logger = loggerFactory.CreateLogger<ILogger<MemoryAdapterFactory<TSerializer>>>(); this.serializer = MemoryMessageBodySerializerFactory<TSerializer>.GetOrCreateSerializer(serviceProvider); } /// <summary> /// Factory initialization. /// </summary> public void Init() { this.queueGrains = new ConcurrentDictionary<QueueId, IMemoryStreamQueueGrain>(); if (CacheMonitorFactory == null) this.CacheMonitorFactory = (dimensions, telemetryProducer) => new DefaultCacheMonitor(dimensions, telemetryProducer); if (this.BlockPoolMonitorFactory == null) this.BlockPoolMonitorFactory = (dimensions, telemetryProducer) => new DefaultBlockPoolMonitor(dimensions, telemetryProducer); if (this.ReceiverMonitorFactory == null) this.ReceiverMonitorFactory = (dimensions, telemetryProducer) => new DefaultQueueAdapterReceiverMonitor(dimensions, telemetryProducer); this.purgePredicate = new TimePurgePredicate(this.cacheOptions.DataMinTimeInCache, this.cacheOptions.DataMaxAgeInCache); this.streamQueueMapper = new HashRingBasedStreamQueueMapper(this.queueMapperOptions, this.Name); } private void CreateBufferPoolIfNotCreatedYet() { if (this.bufferPool == null) { // 1 meg block size pool this.blockPoolMonitorDimensions = new BlockPoolMonitorDimensions($"BlockPool-{Guid.NewGuid()}"); var oneMb = 1 << 20; var objectPoolMonitor = new ObjectPoolMonitorBridge(this.BlockPoolMonitorFactory(blockPoolMonitorDimensions, this.telemetryProducer), oneMb); this.bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(oneMb), objectPoolMonitor, this.statisticOptions.StatisticMonitorWriteInterval); } } /// <summary> /// Create queue adapter. /// </summary> /// <returns></returns> public Task<IQueueAdapter> CreateAdapter() { return Task.FromResult<IQueueAdapter>(this); } /// <summary> /// Create queue message cache adapter /// </summary> /// <returns></returns> public IQueueAdapterCache GetQueueAdapterCache() { return this; } /// <summary> /// Create queue mapper /// </summary> /// <returns></returns> public IStreamQueueMapper GetStreamQueueMapper() { return streamQueueMapper; } /// <summary> /// Creates a queue receiver for the specified queueId /// </summary> /// <param name="queueId"></param> /// <returns></returns> public IQueueAdapterReceiver CreateReceiver(QueueId queueId) { var dimensions = new ReceiverMonitorDimensions(queueId.ToString()); var receiverLogger = this.loggerFactory.CreateLogger($"{typeof(MemoryAdapterReceiver<TSerializer>).FullName}.{this.Name}.{queueId}"); var receiverMonitor = this.ReceiverMonitorFactory(dimensions, this.telemetryProducer); IQueueAdapterReceiver receiver = new MemoryAdapterReceiver<TSerializer>(GetQueueGrain(queueId), receiverLogger, this.serializer, receiverMonitor); return receiver; } /// <summary> /// Writes a set of events to the queue as a single batch associated with the provided streamId. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="streamGuid"></param> /// <param name="streamNamespace"></param> /// <param name="events"></param> /// <param name="token"></param> /// <param name="requestContext"></param> /// <returns></returns> public async Task QueueMessageBatchAsync<T>(Guid streamGuid, string streamNamespace, IEnumerable<T> events, StreamSequenceToken token, Dictionary<string, object> requestContext) { try { var queueId = streamQueueMapper.GetQueueForStream(streamGuid, streamNamespace); ArraySegment<byte> bodyBytes = serializer.Serialize(new MemoryMessageBody(events.Cast<object>(), requestContext)); var messageData = MemoryMessageData.Create(streamGuid, streamNamespace, bodyBytes); IMemoryStreamQueueGrain queueGrain = GetQueueGrain(queueId); await queueGrain.Enqueue(messageData); } catch (Exception exc) { logger.LogError((int)ProviderErrorCode.MemoryStreamProviderBase_QueueMessageBatchAsync, exc, "Exception thrown in MemoryAdapterFactory.QueueMessageBatchAsync."); throw; } } /// <summary> /// Create a cache for a given queue id /// </summary> /// <param name="queueId"></param> public IQueueCache CreateQueueCache(QueueId queueId) { //move block pool creation from init method to here, to avoid unnecessary block pool creation when stream provider is initialized in client side. CreateBufferPoolIfNotCreatedYet(); var logger = this.loggerFactory.CreateLogger($"{typeof(MemoryPooledCache<TSerializer>).FullName}.{this.Name}.{queueId}"); var monitor = this.CacheMonitorFactory(new CacheMonitorDimensions(queueId.ToString(), this.blockPoolMonitorDimensions.BlockPoolId), this.telemetryProducer); return new MemoryPooledCache<TSerializer>(bufferPool, purgePredicate, logger, this.serializer, monitor, this.statisticOptions.StatisticMonitorWriteInterval); } /// <summary> /// Acquire delivery failure handler for a queue /// </summary> /// <param name="queueId"></param> /// <returns></returns> public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId) { return Task.FromResult(streamFailureHandler ?? (streamFailureHandler = new NoOpStreamDeliveryFailureHandler())); } /// <summary> /// Generate a deterministic Guid from a queue Id. /// </summary> /// <param name="queueId"></param> /// <returns></returns> private Guid GenerateDeterministicGuid(QueueId queueId) { // provider name hash code int providerNameGuidHash = (int)JenkinsHash.ComputeHash(this.Name); // get queueId hash code uint queueIdHash = queueId.GetUniformHashCode(); byte[] queIdHashByes = BitConverter.GetBytes(queueIdHash); short s1 = BitConverter.ToInt16(queIdHashByes, 0); short s2 = BitConverter.ToInt16(queIdHashByes, 2); // build guid tailing 8 bytes from providerNameGuidHash and queIdHashByes. var tail = new List<byte>(); tail.AddRange(BitConverter.GetBytes(providerNameGuidHash)); tail.AddRange(queIdHashByes); // make guid. // - First int is provider name hash // - Two shorts from queue Id hash // - 8 byte tail from provider name hash and queue Id hash. return new Guid(providerNameGuidHash, s1, s2, tail.ToArray()); } /// <summary> /// Get a MemoryStreamQueueGrain instance by queue Id. /// </summary> /// <param name="queueId"></param> /// <returns></returns> private IMemoryStreamQueueGrain GetQueueGrain(QueueId queueId) { return queueGrains.GetOrAdd(queueId, id => grainFactory.GetGrain<IMemoryStreamQueueGrain>(GenerateDeterministicGuid(id))); } public static MemoryAdapterFactory<TSerializer> Create(IServiceProvider services, string name) { var cachePurgeOptions = services.GetOptionsByName<StreamCacheEvictionOptions>(name); var statisticOptions = services.GetOptionsByName<StreamStatisticOptions>(name); var queueMapperOptions = services.GetOptionsByName<HashRingStreamQueueMapperOptions>(name); var factory = ActivatorUtilities.CreateInstance<MemoryAdapterFactory<TSerializer>>(services, name, cachePurgeOptions, statisticOptions, queueMapperOptions); factory.Init(); return factory; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Plotter.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
//--------------------------------------------------------------------- // // Author: jachymko // // Description: The Ping-Host command. // // Creation date: Dec 14, 2006 // //--------------------------------------------------------------------- using System; using System.ComponentModel; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Net; namespace Pscx.Commands.Net { [OutputType(typeof(PingHostStatistics))] [Cmdlet(VerbsDiagnostic.Ping, PscxNouns.Host, SupportsShouldProcess = true)] [Description("Sends ICMP echo requests to nework hosts.")] [RelatedLink(typeof(ResolveHostCommand))] [Obsolete(@"The PSCX\Ping-Host cmdlet is obsolete and will be removed in the next version of PSCX. Use the built-in Microsoft.PowerShell.Management\Test-Connection cmdlet instead.")] public partial class PingHostCommand : PscxCmdlet { static readonly Random _random = new Random(); PingExecutor _executor; #region Parameters #region Parameter fields PSObject[] _hosts; int _ttl = 255; int _count = 4; byte[] _buffer = new byte[32]; TimeSpan _timeout = TimeSpan.FromMilliseconds(1000); SwitchParameter _async; SwitchParameter _allAddresses; SwitchParameter _quiet; #endregion #region Parameter properties [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] public PSObject[] HostName { get { return _hosts; } set { _hosts = value; } } [Parameter(Position = 1, HelpMessage = "Number of messages to send to each address.")] [ValidateRange(1, int.MaxValue)] public int Count { get { return _count; } set { _count = value; } } [Parameter(Position = 2, HelpMessage = "Size of the message in bytes.")] [ValidateRange(1, 65000)] public int BufferSize { get { return _buffer.Length; } set { _buffer = new byte[value]; _random.NextBytes(_buffer); } } [Parameter(Position = 3, HelpMessage = "Timeout in milliseconds to wait for each reply.")] [ValidateRange(1, int.MaxValue)] public int Timeout { get { return (int)_timeout.TotalMilliseconds; } set { _timeout = TimeSpan.FromMilliseconds(value); } } [Parameter(Position = 4, HelpMessage = "Time To Live.")] public int TTL { get { return _ttl; } set { _ttl = value; } } [Parameter(Position = 5, HelpMessage = "Pings the host on all IP addresses found.")] public SwitchParameter AllAddresses { get { return _allAddresses; } set { _allAddresses = value; } } [Parameter(Position = 6, HelpMessage = "Pings all hosts in parallel.")] public SwitchParameter Asynchronous { get { return _async; } set { _async = value; } } [Parameter(HelpMessage = "Suppresses all direct to host messages")] public SwitchParameter Quiet { get { return _quiet; } set { _quiet = value; } } [Parameter] public SwitchParameter NoDnsResolution { get; set; } #endregion #endregion public PingHostCommand() { _random.NextBytes(_buffer); } protected override void Dispose(bool disposing) { if (disposing) { if (_executor != null) { _executor.Dispose(); } } base.Dispose(disposing); } protected override void BeginProcessing() { base.BeginProcessing(); if (_async.IsPresent) { _executor = new PingExecutorAsync(this); } else { _executor = new PingExecutorSync(this); } _executor.BeginProcessing(); } protected override void ProcessRecord() { base.ProcessRecord(); foreach (PSObject target in _hosts) { if (ShouldProcess(target.ToString())) { IPAddress address = target.BaseObject as IPAddress; IPHostEntry hostEntry = target.BaseObject as IPHostEntry; if (hostEntry != null) { _executor.Send(hostEntry); } else if (address != null) { _executor.Send(address, !this.NoDnsResolution); } else if (target.BaseObject != null) { //IPAddress tmpAddress; string hostOrAddress = target.BaseObject.ToString(); //if (this.NoDnsResolution && !IPAddress.TryParse(hostOrAddress, out tmpAddress)) //{ // // If -NoDnsResolution specified, then HostName must specify a valid IPAddress. // this.ErrorHandler.WriteInvalidIPAddressError(hostOrAddress); // continue; //} _executor.Send(hostOrAddress, !this.NoDnsResolution); } } } } protected override void EndProcessing() { base.EndProcessing(); _executor.EndProcessing(); } protected override void StopProcessing() { base.StopProcessing(); if (_executor != null) { _executor.StopProcessing(); } } internal byte[] Buffer { get { return _buffer; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Snake.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Tests; using System.Security.Principal; using Xunit; namespace System.Security.Claims { public class ClaimsIdentityTests { [Fact] public void Ctor_Default() { var id = new ClaimsIdentity(); Assert.Null(id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(0, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_AuthenticationType_Blank() { var id = new ClaimsIdentity(""); Assert.Equal(string.Empty, id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(0, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_AuthenticationType_Null() { var id = new ClaimsIdentity((string)null); Assert.Null(id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(0, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_AuthenticationType() { var id = new ClaimsIdentity("auth_type"); Assert.Equal("auth_type", id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(0, id.Claims.Count()); Assert.True(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_EnumerableClaim_Null() { var id = new ClaimsIdentity((IEnumerable<Claim>)null); Assert.Null(id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(0, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_EnumerableClaim_Empty() { var id = new ClaimsIdentity(new Claim[0]); Assert.Null(id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(0, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_EnumerableClaim_WithName() { var id = new ClaimsIdentity( new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), }); Assert.Null(id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(2, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Equal("claim_name_value", id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_EnumerableClaim_WithoutName() { var id = new ClaimsIdentity( new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType + "_x", "claim_name_value"), }); Assert.Null(id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(2, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_EnumerableClaimAuthNameRoleType() { var id = new ClaimsIdentity(new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), new Claim ("claim_role_type", "claim_role_value"), }, "test_auth_type", "test_name_type", "claim_role_type"); Assert.Equal("test_auth_type", id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(3, id.Claims.Count()); Assert.True(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal("test_name_type", id.NameClaimType); Assert.Equal("claim_role_type", id.RoleClaimType); } [Fact] public void Ctor_EnumerableClaimAuthNameRoleType_AllNull() { var id = new ClaimsIdentity((IEnumerable<Claim>)null, (string)null, (string)null, (string)null); Assert.Null(id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(0, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_EnumerableClaimAuthNameRoleType_AllEmpty() { var id = new ClaimsIdentity(new Claim[0], "", "", ""); Assert.Equal(string.Empty, id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(0, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_EnumerableClaimAuthNameRoleType_TwoClaimsAndTypesEmpty() { var id = new ClaimsIdentity( new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), }, "", "", ""); Assert.Equal(string.Empty, id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(2, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Equal("claim_name_value", id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_EnumerableClaimAuthNameRoleType_TwoClaimsAndTypesNull() { var id = new ClaimsIdentity( new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), }, (string)null, (string)null, (string)null); Assert.Null(id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(2, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Equal("claim_name_value", id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_IdentityEnumerableClaimAuthNameRoleType() { var id = new ClaimsIdentity((IIdentity)null, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null); Assert.Null(id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(0, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_IdentityEnumerableClaimAuthNameRoleType_IdentityNullRestEmpty() { var id = new ClaimsIdentity(null, new Claim[0], "", "", ""); Assert.Equal(string.Empty, id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(0, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_IdentityEnumerableClaimAuthNameRoleType_ClaimsArrayEmptyTypes() { var id = new ClaimsIdentity( null, new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), }, "", "", ""); Assert.Equal(string.Empty, id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(2, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Equal("claim_name_value", id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_IdentityEnumerableClaimAuthNameRoleType_NullClaimsArrayNulls() { var id = new ClaimsIdentity( null, new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), }, (string)null, (string)null, (string)null); Assert.Null(id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(2, id.Claims.Count()); Assert.False(id.IsAuthenticated); Assert.Null(id.Label); Assert.Equal("claim_name_value", id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_IdentityEnumerableClaimAuthNameRoleType_NullIdentityRestFilled() { var id = new ClaimsIdentity( null, new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), new Claim ("claim_role_type", "claim_role_value"), }, "test_auth_type", "test_name_type", "claim_role_type"); Assert.Equal("test_auth_type", id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(3, id.Claims.Count()); Assert.True(id.IsAuthenticated); Assert.Null(id.Label); Assert.Null(id.Name); Assert.Equal("test_name_type", id.NameClaimType); Assert.Equal("claim_role_type", id.RoleClaimType); } [Fact] public void Ctor_IdentityEnumerableClaimAuthNameRoleType_ClaimsIdentityRestFilled() { var baseId = new ClaimsIdentity( new[] { new Claim("base_claim_type", "base_claim_value") }, "base_auth_type"); baseId.Actor = new ClaimsIdentity("base_actor"); baseId.BootstrapContext = "bootstrap_context"; baseId.Label = "base_label"; Assert.True(baseId.IsAuthenticated, "#0"); var id = new ClaimsIdentity( baseId, new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), new Claim ("claim_role_type", "claim_role_value"), }, "test_auth_type", "test_name_type", "claim_role_type"); Assert.Equal("test_auth_type", id.AuthenticationType); Assert.NotNull(id.Actor); Assert.Equal("base_actor", id.Actor.AuthenticationType); Assert.Equal("bootstrap_context", id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(4, id.Claims.Count()); Assert.Equal("base_claim_type", id.Claims.First().Type); Assert.True(id.IsAuthenticated); Assert.Equal("base_label", id.Label); Assert.Null(id.Name); Assert.Equal("test_name_type", id.NameClaimType); Assert.Equal("claim_role_type", id.RoleClaimType); } [Fact] public void Ctor_IdentityEnumerableClaimAuthNameRoleType_NonClaimsIdentityRestEmptyWorks() { var baseId = new NonClaimsIdentity { Name = "base_name", AuthenticationType = "TestId_AuthType" }; var id = new ClaimsIdentity( baseId, new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), new Claim ("claim_role_type", "claim_role_value"), }, "", "", ""); Assert.Equal("TestId_AuthType", id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(4, id.Claims.Count()); Assert.Equal(2, id.Claims.Count(_ => _.Type == ClaimsIdentity.DefaultNameClaimType)); Assert.True(id.IsAuthenticated); Assert.Null(id.Label); Assert.Equal("base_name", id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_IdentityEnumerableClaimAuthNameRoleType_ClaimsIdentityClaim() { var baseId = new ClaimsIdentity( new[] { new Claim("base_claim_type", "base_claim_value") }, "base_auth_type", "base_name_claim_type", null); baseId.Actor = new ClaimsIdentity("base_actor"); baseId.BootstrapContext = "bootstrap_context"; baseId.Label = "base_label"; Assert.True(baseId.IsAuthenticated); var id = new ClaimsIdentity( baseId, new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), new Claim ("claim_role_type", "claim_role_value"), }); Assert.Equal("base_auth_type", id.AuthenticationType); Assert.NotNull(id.Actor); Assert.Equal("base_actor", id.Actor.AuthenticationType); Assert.Equal("bootstrap_context", id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(4, id.Claims.Count()); Assert.Equal("base_claim_type", id.Claims.First().Type); Assert.True(id.IsAuthenticated); Assert.Equal("base_label", id.Label); Assert.Null(id.Name); Assert.Equal("base_name_claim_type", id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Ctor_IdentityEnumerableClaimAuthNameRoleType_NonClaimsIdentityClaims() { var baseId = new NonClaimsIdentity { Name = "base_name", AuthenticationType = "TestId_AuthType" }; var id = new ClaimsIdentity( baseId, new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), new Claim ("claim_role_type", "claim_role_value"), }); Assert.Equal("TestId_AuthType", id.AuthenticationType); Assert.Null(id.Actor); Assert.Null(id.BootstrapContext); Assert.NotNull(id.Claims); Assert.Equal(4, id.Claims.Count()); Assert.Equal(2, id.Claims.Count(_ => _.Type == ClaimsIdentity.DefaultNameClaimType)); Assert.True(id.IsAuthenticated); Assert.Null(id.Label); Assert.Equal("base_name", id.Name); Assert.Equal(ClaimsIdentity.DefaultNameClaimType, id.NameClaimType); Assert.Equal(ClaimsIdentity.DefaultRoleClaimType, id.RoleClaimType); } [Fact] public void Find_CaseInsensivity() { var claim_type = new Claim("TYpe", "value"); var id = new ClaimsIdentity( new[] { claim_type }, "base_auth_type", "base_name_claim_type", null); var f1 = id.FindFirst("tyPe"); Assert.Equal("value", f1.Value); var f2 = id.FindAll("tyPE").First(); Assert.Equal("value", f2.Value); } [Fact] public void HasClaim_TypeValue() { var id = new ClaimsIdentity( new[] { new Claim ("claim_type", "claim_value"), new Claim (ClaimsIdentity.DefaultNameClaimType, "claim_name_value"), new Claim ("claim_role_type", "claim_role_value"), }, "test_authority"); Assert.True(id.HasClaim("claim_type", "claim_value")); Assert.True(id.HasClaim("cLaIm_TyPe", "claim_value")); Assert.False(id.HasClaim("claim_type", "cLaIm_VaLuE")); Assert.False(id.HasClaim("Xclaim_type", "claim_value")); Assert.False(id.HasClaim("claim_type", "Xclaim_value")); } [Serializable] private sealed class CustomClaimsIdentity : ClaimsIdentity, ISerializable { public CustomClaimsIdentity(string authenticationType, string nameType, string roleType) : base(authenticationType, nameType, roleType) { } public CustomClaimsIdentity(SerializationInfo info, StreamingContext context) : base(info, context) { } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } } } internal class NonClaimsIdentity : IIdentity { public string AuthenticationType { get; set; } public bool IsAuthenticated { get { return true; } } public string Name { get; set; } } }
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; #if NET_2_0 using System.Collections.Generic; #endif namespace NUnit.Constraints.Constraints { #region ConstraintOperator Base Class /// <summary> /// The ConstraintOperator class is used internally by a /// ConstraintBuilder to represent an operator that /// modifies or combines constraints. /// /// Constraint operators use left and right precedence /// values to determine whether the top operator on the /// stack should be reduced before pushing a new operator. /// </summary> public abstract class ConstraintOperator { private object leftContext; private object rightContext; /// <summary> /// The precedence value used when the operator /// is about to be pushed to the stack. /// </summary> protected int left_precedence; /// <summary> /// The precedence value used when the operator /// is on the top of the stack. /// </summary> protected int right_precedence; /// <summary> /// The syntax element preceding this operator /// </summary> public object LeftContext { get { return leftContext; } set { leftContext = value; } } /// <summary> /// The syntax element folowing this operator /// </summary> public object RightContext { get { return rightContext; } set { rightContext = value; } } /// <summary> /// The precedence value used when the operator /// is about to be pushed to the stack. /// </summary> public virtual int LeftPrecedence { get { return left_precedence; } } /// <summary> /// The precedence value used when the operator /// is on the top of the stack. /// </summary> public virtual int RightPrecedence { get { return right_precedence; } } /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> /// <param name="stack"></param> public abstract void Reduce(ConstraintBuilder.ConstraintStack stack); } #endregion #region Prefix Operators #region PrefixOperator /// <summary> /// PrefixOperator takes a single constraint and modifies /// it's action in some way. /// </summary> public abstract class PrefixOperator : ConstraintOperator { /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> /// <param name="stack"></param> public override void Reduce(ConstraintBuilder.ConstraintStack stack) { stack.Push(ApplyPrefix(stack.Pop())); } /// <summary> /// Returns the constraint created by applying this /// prefix to another constraint. /// </summary> /// <param name="constraint"></param> /// <returns></returns> public abstract Constraint ApplyPrefix(Constraint constraint); } #endregion #region NotOperator /// <summary> /// Negates the test of the constraint it wraps. /// </summary> public class NotOperator : PrefixOperator { /// <summary> /// Constructs a new NotOperator /// </summary> public NotOperator() { // Not stacks on anything and only allows other // prefix ops to stack on top of it. this.left_precedence = this.right_precedence = 1; } /// <summary> /// Returns a NotConstraint applied to its argument. /// </summary> public override Constraint ApplyPrefix(Constraint constraint) { return new NotConstraint(constraint); } } #endregion #region Collection Operators /// <summary> /// Abstract base for operators that indicate how to /// apply a constraint to items in a collection. /// </summary> public abstract class CollectionOperator : PrefixOperator { /// <summary> /// Constructs a CollectionOperator /// </summary> public CollectionOperator() { // Collection Operators stack on everything // and allow all other ops to stack on them this.left_precedence = 1; this.right_precedence = 10; } } /// <summary> /// Represents a constraint that succeeds if all the /// members of a collection match a base constraint. /// </summary> public class AllOperator : CollectionOperator { /// <summary> /// Returns a constraint that will apply the argument /// to the members of a collection, succeeding if /// they all succeed. /// </summary> public override Constraint ApplyPrefix(Constraint constraint) { return new AllItemsConstraint(constraint); } } /// <summary> /// Represents a constraint that succeeds if any of the /// members of a collection match a base constraint. /// </summary> public class SomeOperator : CollectionOperator { /// <summary> /// Returns a constraint that will apply the argument /// to the members of a collection, succeeding if /// any of them succeed. /// </summary> public override Constraint ApplyPrefix(Constraint constraint) { return new SomeItemsConstraint(constraint); } } /// <summary> /// Represents a constraint that succeeds if none of the /// members of a collection match a base constraint. /// </summary> public class NoneOperator : CollectionOperator { /// <summary> /// Returns a constraint that will apply the argument /// to the members of a collection, succeeding if /// none of them succeed. /// </summary> public override Constraint ApplyPrefix(Constraint constraint) { return new NoItemConstraint(constraint); } } #endregion #region WithOperator /// <summary> /// Represents a constraint that simply wraps the /// constraint provided as an argument, without any /// further functionality, but which modifes the /// order of evaluation because of its precedence. /// </summary> public class WithOperator : PrefixOperator { /// <summary> /// Constructor for the WithOperator /// </summary> public WithOperator() { this.left_precedence = 1; this.right_precedence = 4; } /// <summary> /// Returns a constraint that wraps its argument /// </summary> public override Constraint ApplyPrefix(Constraint constraint) { return constraint; } } #endregion #region SelfResolving Operators #region SelfResolvingOperator /// <summary> /// Abstract base class for operators that are able to reduce to a /// constraint whether or not another syntactic element follows. /// </summary> public abstract class SelfResolvingOperator : ConstraintOperator { } #endregion #region PropOperator /// <summary> /// Operator used to test for the presence of a named Property /// on an object and optionally apply further tests to the /// value of that property. /// </summary> public class PropOperator : SelfResolvingOperator { private string name; /// <summary> /// Gets the name of the property to which the operator applies /// </summary> public string Name { get { return name; } } /// <summary> /// Constructs a PropOperator for a particular named property /// </summary> public PropOperator(string name) { this.name = name; // Prop stacks on anything and allows only // prefix operators to stack on it. this.left_precedence = this.right_precedence = 1; } /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> /// <param name="stack"></param> public override void Reduce(ConstraintBuilder.ConstraintStack stack) { if (RightContext == null || RightContext is BinaryOperator) stack.Push(new PropertyExistsConstraint(name)); else stack.Push(new PropertyConstraint(name, stack.Pop())); } } #endregion #region AttributeOperator /// <summary> /// Operator that tests for the presence of a particular attribute /// on a type and optionally applies further tests to the attribute. /// </summary> public class AttributeOperator : SelfResolvingOperator { private Type type; /// <summary> /// Construct an AttributeOperator for a particular Type /// </summary> /// <param name="type">The Type of attribute tested</param> public AttributeOperator(Type type) { this.type = type; // Attribute stacks on anything and allows only // prefix operators to stack on it. this.left_precedence = this.right_precedence = 1; } /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> public override void Reduce(ConstraintBuilder.ConstraintStack stack) { if (RightContext == null || RightContext is BinaryOperator) stack.Push(new AttributeExistsConstraint(type)); else stack.Push(new AttributeConstraint(type, stack.Pop())); } } #endregion #region ThrowsOperator /// <summary> /// Operator that tests that an exception is thrown and /// optionally applies further tests to the exception. /// </summary> public class ThrowsOperator : SelfResolvingOperator { /// <summary> /// Construct a ThrowsOperator /// </summary> public ThrowsOperator() { // ThrowsOperator stacks on everything but // it's always the first item on the stack // anyway. It is evaluated last of all ops. this.left_precedence = 1; this.right_precedence = 100; } /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> public override void Reduce(ConstraintBuilder.ConstraintStack stack) { if (RightContext == null || RightContext is BinaryOperator) stack.Push(new ThrowsConstraint(null)); else stack.Push(new ThrowsConstraint(stack.Pop())); } } #endregion #endregion #endregion #region Binary Operators #region BinaryOperator /// <summary> /// Abstract base class for all binary operators /// </summary> public abstract class BinaryOperator : ConstraintOperator { /// <summary> /// Reduce produces a constraint from the operator and /// any arguments. It takes the arguments from the constraint /// stack and pushes the resulting constraint on it. /// </summary> /// <param name="stack"></param> public override void Reduce(ConstraintBuilder.ConstraintStack stack) { Constraint right = stack.Pop(); Constraint left = stack.Pop(); stack.Push(ApplyOperator(left, right)); } /// <summary> /// Gets the left precedence of the operator /// </summary> public override int LeftPrecedence { get { return RightContext is CollectionOperator ? base.LeftPrecedence + 10 : base.LeftPrecedence; } } /// <summary> /// Gets the right precedence of the operator /// </summary> public override int RightPrecedence { get { return RightContext is CollectionOperator ? base.RightPrecedence + 10 : base.RightPrecedence; } } /// <summary> /// Abstract method that produces a constraint by applying /// the operator to its left and right constraint arguments. /// </summary> public abstract Constraint ApplyOperator(Constraint left, Constraint right); } #endregion #region AndOperator /// <summary> /// Operator that requires both it's arguments to succeed /// </summary> public class AndOperator : BinaryOperator { /// <summary> /// Construct an AndOperator /// </summary> public AndOperator() { this.left_precedence = this.right_precedence = 2; } /// <summary> /// Apply the operator to produce an AndConstraint /// </summary> public override Constraint ApplyOperator(Constraint left, Constraint right) { return new AndConstraint(left, right); } } #endregion #region OrOperator /// <summary> /// Operator that requires at least one of it's arguments to succeed /// </summary> public class OrOperator : BinaryOperator { /// <summary> /// Construct an OrOperator /// </summary> public OrOperator() { this.left_precedence = this.right_precedence = 3; } /// <summary> /// Apply the operator to produce an OrConstraint /// </summary> public override Constraint ApplyOperator(Constraint left, Constraint right) { return new OrConstraint(left, right); } } #endregion #endregion }
using System; using System.Threading; /* * Copyright 2012-2014 Stefan Thoolen (http://www.netmftoolbox.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Toolbox.NETMF.NET { /// <summary> /// IRC Client /// </summary> /// <remarks> /// This client contains the most basic features to stay connected to an IRC server. /// It can also reply to the CTCP commands VERSION, TIME and PING. /// To disable or change the CTCP replies, just create your own OnCtcpRequest method. /// </remarks> public class IRC_Client : IDisposable { #region "Core" /// <summary>Contains the socket wrapper</summary> private SimpleSocket _Socket; /// <summary>Main loop thread</summary> private Thread _LoopThread; /// <summary>The nickname of the client</summary> private string _Nickname; /// <summary>The username of the client</summary> private string _Username; /// <summary>The full name of the client</summary> private string _Fullname; /// <summary>Optional password</summary> private string _Password; /// <summary>Contains the clientversion</summary> private string _ClientVersion = ""; /// <summary>Returns the clientversion</summary> public string ClientVersion { get { return this._ClientVersion; } } /// <summary>True when the user is authenticated by the remote server</summary> private bool _Authenticated = false; /// <summary>True when the user is authenticated by the remote server</summary> public bool Authenticated { get { return this._Authenticated; } } /// <summary>Contains the name of the IRC server</summary> private string _ServerName = ""; /// <summary>Returns the name of the IRC server</summary> public string ServerName { get { return this._ServerName; } } /// <summary> /// Connects to an IRC server /// </summary> /// <param name="Socket">The socket to use</param> /// <param name="Nickname">Nickname</param> /// <param name="Username">Username (optional)</param> /// <param name="Fullname">Full name (optional)</param> /// <param name="Password">Password to connect to the server (optional)</param> public IRC_Client(SimpleSocket Socket, string Nickname, string Username = "", string Fullname = "", string Password = "") { // What kind of device do we run on? string[] SocketProvider = Socket.ToString().Split(new char[] { '.' }); string[] Client = this.ToString().Split(new char[] { '.' }); // Version this._ClientVersion = "NETMFToolbox/0.1 (" + Tools.HardwareProvider + "; " + SocketProvider[SocketProvider.Length - 1] + "; " + Client[Client.Length - 1] + ")"; // Stores all fields this._Socket = Socket; this._Nickname = Nickname; this._Username = (Username == "") ? Nickname : Username; this._Fullname = (Fullname == "") ? this._ClientVersion : Fullname; this._Password = Password; this._ServerName = Socket.Hostname; // Configures the socket this._Socket.LineEnding = "\n"; // Creates a new background thread this._LoopThread = new Thread(new ThreadStart(this._Loop)); } /// <summary> /// Disposes this object /// </summary> public void Dispose() { this.Disconnect(); } /// <summary> /// Connects to the IRC server /// </summary> public void Connect() { this._Socket.Connect(); if (this._Password != "") this.SendRaw("PASS " + this._Password); this.SendRaw("NICK " + this._Nickname); this.SendRaw("USER " + this._Username + " 0 " + this._Socket.Hostname + " :" + this._Fullname); this._LoopThread.Start(); } /// <summary> /// Closes the connection /// </summary> public void Disconnect() { if (this._Socket.IsConnected) { this.SendRaw("QUIT :Client disconnected"); this._Socket.Close(); } this._LoopThread.Abort(); } /// <summary> /// Main loop /// </summary> private void _Loop() { // Infinite loop, we keep trying to read data while (true) { string Data = this._Socket.Receive(); if (Data != "") this._DataReceived(Data.TrimEnd("\r\n".ToCharArray())); else // Give other threads some time as well Thread.Sleep(1); } } /// <summary> /// Gets or sets the nickname /// </summary> public string Nickname { get { return this._Nickname; } set { this.SendRaw("NICK :" + value); } } #endregion #region "Receive methods" /// <summary>Event triggered when string data is received</summary> /// <param name="Sender">The sender of the data</param> /// <param name="Target">The target of the data</param> /// <param name="Data">The data</param> /// <remarks>A very generic method, can be used for a lot of events</remarks> public delegate void OnStringReceived(string Sender, string Target, string Data); /// <summary>Event triggered when raw data is received from the remote server</summary> public event OnStringReceived OnRawReceived; /// <summary>Event triggered when a notice is received</summary> public event OnStringReceived OnNotice; /// <summary>Event triggered when a message is received</summary> public event OnStringReceived OnMessage; /// <summary>Event triggered when an action is received</summary> public event OnStringReceived OnAction; /// <summary>Event triggered when a CTCP-request is received</summary> public event OnStringReceived OnCtcpRequest; /// <summary>Event triggered when a CTCP-reply is received</summary> public event OnStringReceived OnCtcpReply; /// <summary>Event triggered when the user is fully logged in</summary> public event OnStringReceived OnAuthenticated; /// <summary>Event triggered when a user joins a channel</summary> public event OnStringReceived OnJoin; /// <summary>Event triggered when a user parts a channel</summary> public event OnStringReceived OnPart; /// <summary>Event triggered when a user quits the server</summary> public event OnStringReceived OnQuit; /// <summary>Event triggered when a user is kicked from a channel</summary> public event OnStringReceived OnKick; /// <summary>Event triggered when a user changes its name</summary> public event OnStringReceived OnNick; /// <summary>Triggered for every line of data received by the server</summary> /// <param name="Data">The received line of data</param> private void _DataReceived(string Data) { // Triggers the OnRawReceived event for all data if (this.OnRawReceived != null) this.OnRawReceived("", "", Data); // Splits on spaces to detect the command string[] DataSplit = SplitRawData(Data); // Default ping/pong, just send back the full response if (DataSplit[0] == "PING") { this.SendRaw("PONG " + Data.Substring(5)); return; } // There are two commands, commands directly from the server, // and commands from another party if (DataSplit[0].Substring(0, 1) == ":") { // We got a command from another party DataSplit[0] = DataSplit[0].Substring(1); } else { // We got data from the server, lets shift some stuff string[] NewSplit = new string[DataSplit.Length + 1]; DataSplit.CopyTo(NewSplit, 1); DataSplit = NewSplit; } // Now we can safely assume the 1st value is empty or the sender, // and the 2nd one is the command. switch (DataSplit[1]) { case "001": // Welcome message, confirms the current nickname this._ServerName = DataSplit[0]; this._Nickname = DataSplit[2]; this._Authenticated = true; if (this.OnAuthenticated != null) this.OnAuthenticated(DataSplit[0], DataSplit[2], DataSplit[3]); break; case "433": // Nickname already in use int Counter = 0; if (DataSplit[3] == this._Nickname) Counter = 1; else Counter = int.Parse(DataSplit[3].Substring(this._Nickname.Length)) + 1; this.SendRaw("NICK " + this._Nickname + Counter.ToString()); break; case "NICK": // Someone changes his name // Is it my own name? if (this._Nickname == SplitName(DataSplit[0])[0]) this._Nickname = DataSplit[2]; // Do we need to send back an event? if (this.OnNick != null) this.OnNick(DataSplit[0], DataSplit[2], ""); break; case "ACTION": if (this.OnAction != null) this.OnAction(DataSplit[0], DataSplit[2], DataSplit[3]); break; case "NOTICE": if (DataSplit[3].Substring(0, 1) == "\x01" && DataSplit[3].Substring(DataSplit[3].Length - 1, 1) == "\x01") { // CTCP Reply DataSplit[3] = DataSplit[3].Trim(new char[] { (char)1 }); if (this.OnCtcpReply != null) this.OnCtcpReply(DataSplit[0], DataSplit[2], DataSplit[3]); } else { // Notice if (this.OnNotice != null) this.OnNotice(DataSplit[0], DataSplit[2], DataSplit[3]); } break; case "PRIVMSG": if (DataSplit[3].Substring(0, 1) == "\x01" && DataSplit[3].Substring(DataSplit[3].Length - 1, 1) == "\x01") { // CTCP Request DataSplit[3] = DataSplit[3].Trim(new char[] { (char)1 }).ToUpper(); if (this.OnCtcpRequest == null) { // No CTCP Request event programmed, we're going to do it ourselves if (DataSplit[3] == "VERSION") this.CtcpResponse(SplitName(DataSplit[0])[0], "VERSION " + this.ClientVersion); if (DataSplit[3] == "TIME") this.CtcpResponse(SplitName(DataSplit[0])[0], "TIME " + IRC_Client.Time); if (DataSplit[3].Substring(0, 4) == "PING") this.CtcpResponse(SplitName(DataSplit[0])[0], "PING" + DataSplit[3].Substring(4)); } else { this.OnCtcpRequest(DataSplit[0], DataSplit[2], DataSplit[3]); } } else { // Message if (this.OnMessage != null) this.OnMessage(DataSplit[0], DataSplit[2], DataSplit[3]); } break; case "JOIN": // User joins a channel if (this.OnJoin != null) this.OnJoin(DataSplit[0], DataSplit[2], ""); break; case "PART": // User parts a channel if (this.OnPart != null) this.OnPart(DataSplit[0], DataSplit[2], DataSplit.Length > 3 ? DataSplit[3] : ""); break; case "KICK": // User has been kicked from a channel if (this.OnKick != null) this.OnKick(DataSplit[0], DataSplit[3], DataSplit[2] + " " + DataSplit[4]); break; case "QUIT": // User leaves the server if (this.OnQuit != null) this.OnQuit(DataSplit[0], DataSplit[2], DataSplit[3]); // Its us! Lets close the rest if (this._Username == IRC_Client.SplitName(DataSplit[0])[0]) this.Disconnect(); break; } } #endregion #region "Send methods" /// <summary>Sends a CTCP Response</summary> /// <param name="Recipient">The recipient (may be a user or a channel)</param> /// <param name="Data">Data to send</param> public void CtcpResponse(string Recipient, string Data) { this.Notice(Recipient, "\x01" + Data + "\x01"); } /// <summary>Sends a CTCP Request</summary> /// <param name="Recipient">The recipient (may be a user or a channel)</param> /// <param name="Data">Data to send</param> public void CtcpRequest(string Recipient, string Data) { this.Message(Recipient, "\x01" + Data + "\x01"); } /// <summary>Sends an action</summary> /// <param name="Recipient">The recipient (may be a user or a channel)</param> /// <param name="Data">Data to send</param> public void Action(string Recipient, string Data) { this.SendRaw("ACTION " + Recipient + " :" + Data); } /// <summary>Sends a notice</summary> /// <param name="Recipient">The recipient (may be a user or a channel)</param> /// <param name="Data">Data to send</param> public void Notice(string Recipient, string Data) { this.SendRaw("NOTICE " + Recipient + " :" + Data); } /// <summary>Sends a message</summary> /// <param name="Recipient">The recipient (may be a user or a channel)</param> /// <param name="Data">Data to send</param> public void Message(string Recipient, string Data) { this.SendRaw("PRIVMSG " + Recipient + " :" + Data); } /// <summary> /// Joins one or more channels /// </summary> /// <param name="Channels">The channel to join (multiple can be comma seperated)</param> /// <param name="Passwords">Optional, the password(s) to join the channel(s)</param> public void Join(string Channels, string Passwords = "") { this.SendRaw("JOIN " + Channels + (Passwords != "" ? " " + Passwords : "")); } /// <summary> /// Parts a channel /// </summary> /// <param name="Channel">The channel to leave</param> /// <param name="Reason">The reason to leave the channel (optional)</param> public void Part(string Channel, string Reason = "") { this.SendRaw("PART " + Channel + (Reason == "" ? "" : " :" + Reason)); } /// <summary> /// Sends raw data to the remote server /// </summary> /// <param name="Data">Data to send</param> public void SendRaw(string Data) { this._Socket.Send(Data + "\n"); } #endregion #region "Static string modifiers" /// <summary>Gets the current local time</summary> /// <returns>The local time as string</returns> public static string Time { get { string[] Days = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }; string[] Months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; DateTime Now = DateTime.Now; return Days[(int)Now.DayOfWeek - 1] + " " + Months[Now.Month - 1] + " " + Now.Day.ToString() + " " + Now.TimeOfDay.ToString().Substring(0, 8) + " " + Now.Year.ToString(); } } /// <summary> /// Splits data according to the IRC protocol /// </summary> /// <param name="Data">Input data</param> /// <returns>Output data</returns> public static string[] SplitRawData(string Data) { // Checks for longer string values int BreakPoint = Data.IndexOf(" :"); // No longer string values if (BreakPoint < 0) return Data.Split(new char[] { ' ' }); // Splits all regular values string[] Values = Data.Substring(0, BreakPoint).Split(new char[] { ' ' }); // Creates a new array and copies the regular values string[] RetValue = new string[Values.Length + 1]; Values.CopyTo(RetValue, 0); // Adds the longer string value RetValue[RetValue.Length - 1] = Data.Substring(BreakPoint + 2); return RetValue; } /// <summary> /// Returns the username splitted (many IRCds send "[nickname]![username]@[hostname]") /// </summary> /// <param name="Name">The full name</param> /// <returns>An array with 3 values: nickname, username, hostname</returns> public static string[] SplitName(string Name) { // First the nickname string[] Split1 = Name.Split(new char[] { '!' }, 2); if (Split1.Length == 1) return new string[3] { Name, "", "" }; // Now the username/host string[] Split2 = Split1[1].Split(new char[] { '@' }, 2); if (Split2.Length == 1) return new string[3] { Split1[0], Split1[1], "" }; // We return everything return new string[3] { Split1[0], Split2[0], Split2[1] }; } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal sealed partial class SolutionCrawlerRegistrationService { private sealed partial class WorkCoordinator { private sealed partial class IncrementalAnalyzerProcessor { private sealed class HighPriorityProcessor : IdleProcessor { private readonly IncrementalAnalyzerProcessor _processor; private readonly Lazy<ImmutableArray<IIncrementalAnalyzer>> _lazyAnalyzers; private readonly AsyncDocumentWorkItemQueue _workItemQueue; // whether this processor is running or not private Task _running; public HighPriorityProcessor( IAsynchronousOperationListener listener, IncrementalAnalyzerProcessor processor, Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers, int backOffTimeSpanInMs, CancellationToken shutdownToken) : base(listener, backOffTimeSpanInMs, shutdownToken) { _processor = processor; _lazyAnalyzers = lazyAnalyzers; _running = SpecializedTasks.EmptyTask; _workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter); Start(); } private ImmutableArray<IIncrementalAnalyzer> Analyzers { get { return _lazyAnalyzers.Value; } } public Task Running { get { return _running; } } public bool HasAnyWork { get { return _workItemQueue.HasAnyWork; } } public void Enqueue(WorkItem item) { Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item"); // we only put workitem in high priority queue if there is a text change. // this is to prevent things like opening a file, changing in other files keep enqueuing // expensive high priority work. if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged)) { return; } // check whether given item is for active document, otherwise, nothing to do here if (_processor._documentTracker == null || _processor._documentTracker.GetActiveDocument() != item.DocumentId) { return; } // we need to clone due to waiter EnqueueActiveFileItem(item.With(Listener.BeginAsyncOperation("ActiveFile"))); } private void EnqueueActiveFileItem(WorkItem item) { this.UpdateLastAccessTime(); var added = _workItemQueue.AddOrReplace(item); Logger.Log(FunctionId.WorkCoordinator_ActiveFileEnqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added); SolutionCrawlerLogger.LogActiveFileEnqueue(_processor._logAggregator); } protected override Task WaitAsync(CancellationToken cancellationToken) { return _workItemQueue.WaitAsync(cancellationToken); } protected override async Task ExecuteAsync() { if (this.CancellationToken.IsCancellationRequested) { return; } var source = new TaskCompletionSource<object>(); try { // mark it as running _running = source.Task; // okay, there must be at least one item in the map // see whether we have work item for the document WorkItem workItem; CancellationTokenSource documentCancellation; Contract.ThrowIfFalse(GetNextWorkItem(out workItem, out documentCancellation)); var solution = _processor.CurrentSolution; // okay now we have work to do await ProcessDocumentAsync(solution, this.Analyzers, workItem, documentCancellation).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } finally { // mark it as done running source.SetResult(null); } } private bool GetNextWorkItem(out WorkItem workItem, out CancellationTokenSource documentCancellation) { // GetNextWorkItem since it can't fail. we still return bool to confirm that this never fail. var documentId = _processor._documentTracker.GetActiveDocument(); if (documentId != null) { if (_workItemQueue.TryTake(documentId, out workItem, out documentCancellation)) { return true; } } return _workItemQueue.TryTakeAnyWork( preferableProjectId: null, dependencyGraph: _processor.DependencyGraph, workItem: out workItem, source: out documentCancellation); } private async Task ProcessDocumentAsync(Solution solution, ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source) { if (this.CancellationToken.IsCancellationRequested) { return; } var processedEverything = false; var documentId = workItem.DocumentId; try { using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token)) { var cancellationToken = source.Token; var document = solution.GetDocument(documentId); if (document != null) { await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false); } if (!cancellationToken.IsCancellationRequested) { processedEverything = true; } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } finally { // we got cancelled in the middle of processing the document. // let's make sure newly enqueued work item has all the flag needed. if (!processedEverything) { _workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem"))); } SolutionCrawlerLogger.LogProcessActiveFileDocument(_processor._logAggregator, documentId.Id, processedEverything); // remove one that is finished running _workItemQueue.RemoveCancellationSource(workItem.DocumentId); } } public void Shutdown() { _workItemQueue.Dispose(); } } } } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Collections; using System.Text.RegularExpressions; namespace NUnit.Framework.Constraints { /// <summary> /// ConstraintExpression represents a compound constraint in the /// process of being constructed from a series of syntactic elements. /// /// Individual elements are appended to the expression as they are /// reorganized. When a constraint is appended, it is returned as the /// value of the operation so that modifiers may be applied. However, /// any partially built expression is attached to the constraint for /// later resolution. When an operator is appended, the partial /// expression is returned. If it's a self-resolving operator, then /// a ResolvableConstraintExpression is returned. /// </summary> public class ConstraintExpression { #region Instance Fields /// <summary> /// The ConstraintBuilder holding the elements recognized so far /// </summary> #pragma warning disable IDE1006 // ReSharper disable once InconsistentNaming // Disregarding naming convention for back-compat protected readonly ConstraintBuilder builder; #pragma warning restore IDE1006 #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ConstraintExpression"/> class. /// </summary> public ConstraintExpression() : this(new ConstraintBuilder()) { } /// <summary> /// Initializes a new instance of the <see cref="ConstraintExpression"/> /// class passing in a ConstraintBuilder, which may be pre-populated. /// </summary> /// <param name="builder">The builder.</param> public ConstraintExpression(ConstraintBuilder builder) { Guard.ArgumentNotNull(builder, nameof(builder)); this.builder = builder; } #endregion #region ToString() /// <summary> /// Returns a string representation of the expression as it /// currently stands. This should only be used for testing, /// since it has the side-effect of resolving the expression. /// </summary> /// <returns></returns> public override string ToString() { return builder.Resolve().ToString(); } #endregion #region Append Methods /// <summary> /// Appends an operator to the expression and returns the /// resulting expression itself. /// </summary> public ConstraintExpression Append(ConstraintOperator op) { builder.Append(op); return this; } /// <summary> /// Appends a self-resolving operator to the expression and /// returns a new ResolvableConstraintExpression. /// </summary> public ResolvableConstraintExpression Append(SelfResolvingOperator op) { builder.Append(op); return new ResolvableConstraintExpression(builder); } /// <summary> /// Appends a constraint to the expression and returns that /// constraint, which is associated with the current state /// of the expression being built. Note that the constraint /// is not reduced at this time. For example, if there /// is a NotOperator on the stack we don't reduce and /// return a NotConstraint. The original constraint must /// be returned because it may support modifiers that /// are yet to be applied. /// </summary> public Constraint Append(Constraint constraint) { builder.Append(constraint); return constraint; } #endregion #region Not /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression Not { get { return this.Append(new NotOperator()); } } /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression No { get { return this.Append(new NotOperator()); } } #endregion #region All /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them succeed. /// </summary> public ConstraintExpression All { get { return this.Append(new AllOperator()); } } #endregion #region Some /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if at least one of them succeeds. /// </summary> public ConstraintExpression Some { get { return this.Append(new SomeOperator()); } } #endregion #region None /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them fail. /// </summary> public ConstraintExpression None { get { return this.Append(new NoneOperator()); } } #endregion #region Exactly(n) /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding only if a specified number of them succeed. /// </summary> public ItemsConstraintExpression Exactly(int expectedCount) { builder.Append(new ExactCountOperator(expectedCount)); return new ItemsConstraintExpression(builder); } #endregion #region One /// <summary> /// Returns a <see cref="ItemsConstraintExpression"/>, which will /// apply the following constraint to a collection of length one, succeeding /// only if exactly one of them succeeds. /// </summary> public ItemsConstraintExpression One { get { builder.Append(new ExactCountOperator(1)); return new ItemsConstraintExpression(builder); } } #endregion #region Property /// <summary> /// Returns a new PropertyConstraintExpression, which will either /// test for the existence of the named property on the object /// being tested or apply any following constraint to that property. /// </summary> public ResolvableConstraintExpression Property(string name) { return this.Append(new PropOperator(name)); } #endregion #region Length /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Length property of the object being tested. /// </summary> public ResolvableConstraintExpression Length { get { return Property("Length"); } } #endregion #region Count /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Count property of the object being tested. /// </summary> public ResolvableConstraintExpression Count { get { return Property("Count"); } } #endregion #region Message /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Message property of the object being tested. /// </summary> public ResolvableConstraintExpression Message { get { return Property("Message"); } } #endregion #region InnerException /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the InnerException property of the object being tested. /// </summary> public ResolvableConstraintExpression InnerException { get { return Property("InnerException"); } } #endregion #region Attribute /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute(Type expectedType) { return this.Append(new AttributeOperator(expectedType)); } /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute<TExpected>() { return Attribute(typeof(TExpected)); } #endregion #region With /// <summary> /// With is currently a NOP - reserved for future use. /// </summary> public ConstraintExpression With { get { return this.Append(new WithOperator()); } } #endregion #region Matches /// <summary> /// Returns the constraint provided as an argument - used to allow custom /// custom constraints to easily participate in the syntax. /// </summary> public Constraint Matches(IResolveConstraint constraint) { return this.Append((Constraint)constraint.Resolve()); } /// <summary> /// Returns the constraint provided as an argument - used to allow custom /// custom constraints to easily participate in the syntax. /// </summary> public Constraint Matches<TActual>(Predicate<TActual> predicate) { return this.Append(new PredicateConstraint<TActual>(predicate)); } #endregion #region Null /// <summary> /// Returns a constraint that tests for null /// </summary> public NullConstraint Null { get { return (NullConstraint)this.Append(new NullConstraint()); } } #endregion #region Null /// <summary> /// Returns a constraint that tests for default value /// </summary> public DefaultConstraint Default { get { return (DefaultConstraint)this.Append(new DefaultConstraint()); } } #endregion #region True /// <summary> /// Returns a constraint that tests for True /// </summary> public TrueConstraint True { get { return (TrueConstraint)this.Append(new TrueConstraint()); } } #endregion #region False /// <summary> /// Returns a constraint that tests for False /// </summary> public FalseConstraint False { get { return (FalseConstraint)this.Append(new FalseConstraint()); } } #endregion #region Positive /// <summary> /// Returns a constraint that tests for a positive value /// </summary> public GreaterThanConstraint Positive { get { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(0)); } } #endregion #region Negative /// <summary> /// Returns a constraint that tests for a negative value /// </summary> public LessThanConstraint Negative { get { return (LessThanConstraint)this.Append(new LessThanConstraint(0)); } } #endregion #region Zero /// <summary> /// Returns a constraint that tests if item is equal to zero /// </summary> public EqualConstraint Zero { get { return (EqualConstraint)this.Append(new EqualConstraint(0)); } } #endregion #region NaN /// <summary> /// Returns a constraint that tests for NaN /// </summary> public NaNConstraint NaN { get { return (NaNConstraint)this.Append(new NaNConstraint()); } } #endregion #region Empty /// <summary> /// Returns a constraint that tests for empty /// </summary> public EmptyConstraint Empty { get { return (EmptyConstraint)this.Append(new EmptyConstraint()); } } #endregion #region Unique /// <summary> /// Returns a constraint that tests whether a collection /// contains all unique items. /// </summary> public UniqueItemsConstraint Unique { get { return (UniqueItemsConstraint)this.Append(new UniqueItemsConstraint()); } } #endregion /// <summary> /// Returns a constraint that tests whether an object graph is serializable in binary format. /// </summary> public BinarySerializableConstraint BinarySerializable { get { return (BinarySerializableConstraint)this.Append(new BinarySerializableConstraint()); } } /// <summary> /// Returns a constraint that tests whether an object graph is serializable in XML format. /// </summary> public XmlSerializableConstraint XmlSerializable { get { return (XmlSerializableConstraint)this.Append(new XmlSerializableConstraint()); } } #region EqualTo /// <summary> /// Returns a constraint that tests two items for equality /// </summary> public EqualConstraint EqualTo(object expected) { return (EqualConstraint)this.Append(new EqualConstraint(expected)); } #endregion #region SameAs /// <summary> /// Returns a constraint that tests that two references are the same object /// </summary> public SameAsConstraint SameAs(object expected) { return (SameAsConstraint)this.Append(new SameAsConstraint(expected)); } #endregion #region GreaterThan /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than the supplied argument /// </summary> public GreaterThanConstraint GreaterThan(object expected) { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(expected)); } #endregion #region GreaterThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the supplied argument /// </summary> public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected) { return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected)); } /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the supplied argument /// </summary> public GreaterThanOrEqualConstraint AtLeast(object expected) { return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected)); } #endregion #region LessThan /// <summary> /// Returns a constraint that tests whether the /// actual value is less than the supplied argument /// </summary> public LessThanConstraint LessThan(object expected) { return (LessThanConstraint)this.Append(new LessThanConstraint(expected)); } #endregion #region LessThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the supplied argument /// </summary> public LessThanOrEqualConstraint LessThanOrEqualTo(object expected) { return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected)); } /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the supplied argument /// </summary> public LessThanOrEqualConstraint AtMost(object expected) { return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected)); } #endregion #region TypeOf /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf(Type expectedType) { return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf<TExpected>() { return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(typeof(TExpected))); } #endregion #region InstanceOf /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf(Type expectedType) { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf<TExpected>() { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(typeof(TExpected))); } #endregion #region AssignableFrom /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom(Type expectedType) { return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom<TExpected>() { return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(typeof(TExpected))); } #endregion #region AssignableTo /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo(Type expectedType) { return (AssignableToConstraint)this.Append(new AssignableToConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo<TExpected>() { return (AssignableToConstraint)this.Append(new AssignableToConstraint(typeof(TExpected))); } #endregion #region EquivalentTo /// <summary> /// Returns a constraint that tests whether the actual value /// is a collection containing the same elements as the /// collection supplied as an argument. /// </summary> public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected) { return (CollectionEquivalentConstraint)this.Append(new CollectionEquivalentConstraint(expected)); } #endregion #region SubsetOf /// <summary> /// Returns a constraint that tests whether the actual value /// is a subset of the collection supplied as an argument. /// </summary> public CollectionSubsetConstraint SubsetOf(IEnumerable expected) { return (CollectionSubsetConstraint)this.Append(new CollectionSubsetConstraint(expected)); } #endregion #region SupersetOf /// <summary> /// Returns a constraint that tests whether the actual value /// is a superset of the collection supplied as an argument. /// </summary> public CollectionSupersetConstraint SupersetOf(IEnumerable expected) { return (CollectionSupersetConstraint)this.Append(new CollectionSupersetConstraint(expected)); } #endregion #region Ordered /// <summary> /// Returns a constraint that tests whether a collection is ordered /// </summary> public CollectionOrderedConstraint Ordered { get { return (CollectionOrderedConstraint)this.Append(new CollectionOrderedConstraint()); } } #endregion #region Member /// <summary> /// Returns a new <see cref="SomeItemsConstraint"/> checking for the /// presence of a particular object in the collection. /// </summary> public SomeItemsConstraint Member(object expected) { return (SomeItemsConstraint)this.Append(new SomeItemsConstraint(new EqualConstraint(expected))); } #endregion #region Contains /// <summary> /// <para> /// Returns a new <see cref="SomeItemsConstraint"/> checking for the /// presence of a particular object in the collection. /// </para> /// <para> /// To search for a substring instead of a collection element, use the /// <see cref="Contains(string)"/> overload. /// </para> /// </summary> public SomeItemsConstraint Contains(object expected) { return (SomeItemsConstraint)this.Append(new SomeItemsConstraint(new EqualConstraint(expected))); } /// <summary> /// <para> /// Returns a new ContainsConstraint. This constraint /// will, in turn, make use of the appropriate second-level /// constraint, depending on the type of the actual argument. /// </para> /// <para> /// To search for a collection element instead of a substring, use the /// <see cref="Contains(object)"/> overload. /// </para> /// </summary> public ContainsConstraint Contains(string expected) { return (ContainsConstraint)this.Append(new ContainsConstraint(expected)); } /// <summary> /// Returns a new <see cref="SomeItemsConstraint"/> checking for the /// presence of a particular object in the collection. /// </summary> public SomeItemsConstraint Contain(object expected) { return Contains(expected); } /// <summary> /// Returns a new ContainsConstraint. This constraint /// will, in turn, make use of the appropriate second-level /// constraint, depending on the type of the actual argument. /// This overload is only used if the item sought is a string, /// since any other type implies that we are looking for a /// collection member. /// </summary> public ContainsConstraint Contain(string expected) { return Contains(expected); } #endregion #region DictionaryContains /// <summary> /// Returns a new DictionaryContainsKeyConstraint checking for the /// presence of a particular key in the Dictionary key collection. /// </summary> /// <param name="expected">The key to be matched in the Dictionary key collection</param> public DictionaryContainsKeyConstraint ContainKey(object expected) { return (DictionaryContainsKeyConstraint)this.Append(new DictionaryContainsKeyConstraint(expected)); } /// <summary> /// Returns a new DictionaryContainsValueConstraint checking for the /// presence of a particular value in the Dictionary value collection. /// </summary> /// <param name="expected">The value to be matched in the Dictionary value collection</param> public DictionaryContainsValueConstraint ContainValue(object expected) { return (DictionaryContainsValueConstraint)this.Append(new DictionaryContainsValueConstraint(expected)); } #endregion #region StartsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StartWith(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StartsWith(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } #endregion #region EndsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint EndWith(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint EndsWith(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } #endregion #region Matches /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint Match(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint Match(Regex regex) { return (RegexConstraint)this.Append(new RegexConstraint(regex)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint Matches(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint Matches(Regex regex) { return (RegexConstraint)this.Append(new RegexConstraint(regex)); } #endregion #region SamePath /// <summary> /// Returns a constraint that tests whether the path provided /// is the same as an expected path after canonicalization. /// </summary> public SamePathConstraint SamePath(string expected) { return (SamePathConstraint)this.Append(new SamePathConstraint(expected)); } #endregion #region SubPath /// <summary> /// Returns a constraint that tests whether the path provided /// is the a subpath of the expected path after canonicalization. /// </summary> public SubPathConstraint SubPathOf(string expected) { return (SubPathConstraint)this.Append(new SubPathConstraint(expected)); } #endregion #region SamePathOrUnder /// <summary> /// Returns a constraint that tests whether the path provided /// is the same path or under an expected path after canonicalization. /// </summary> public SamePathOrUnderConstraint SamePathOrUnder(string expected) { return (SamePathOrUnderConstraint)this.Append(new SamePathOrUnderConstraint(expected)); } #endregion #region InRange /// <summary> /// Returns a constraint that tests whether the actual value falls /// inclusively within a specified range. /// </summary> /// <param name="from">Inclusive beginning of the range.</param> /// <param name="to">Inclusive end of the range.</param> public RangeConstraint InRange(object from, object to) { return (RangeConstraint)this.Append(new RangeConstraint(from, to)); } #endregion #region Exist /// <summary> /// Returns a constraint that succeeds if the value /// is a file or directory and it exists. /// </summary> public Constraint Exist { get { return Append(new FileOrDirectoryExistsConstraint()); } } #endregion #region AnyOf /// <summary> /// Returns a constraint that tests if an item is equal to any of parameters /// </summary> /// <param name="expected">Expected values</param> public AnyOfConstraint AnyOf(params object[] expected) { if (expected == null) { expected = new object[] { null }; } return (AnyOfConstraint)this.Append(new AnyOfConstraint(expected)); } #endregion #region ItemAt /// <summary> /// Returns a new IndexerConstraintExpression, which will /// apply any following constraint to that indexer value. /// </summary> /// <param name="indexArgs">Index accessor values.</param> public ConstraintExpression ItemAt(params object[] indexArgs) { return this.Append(new IndexerOperator(indexArgs)); } #endregion } }
namespace Boxed.Mapping { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; /// <summary> /// <see cref="IMapper{TSource, TDestination}"/> extension methods. /// </summary> public static class MapperExtensions { /// <summary> /// Maps the specified source object to a new object with a type of <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source object.</typeparam> /// <typeparam name="TDestination">The type of the destination object.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source object.</param> /// <returns>The mapped object of type <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator" /> or <paramref name="source" /> is /// <c>null</c>.</exception> public static TDestination Map<TSource, TDestination>( this IMapper<TSource, TDestination> translator, TSource source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = Factory<TDestination>.CreateInstance(); translator.Map(source, destination); return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSourceCollection">The type of the source collection.</typeparam> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="sourceCollection">The source collection.</param> /// <param name="destinationCollection">The destination collection.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="sourceCollection"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSourceCollection, TSource, TDestination>( this IMapper<TSource, TDestination> translator, TSourceCollection sourceCollection, TDestination[] destinationCollection) where TSourceCollection : IEnumerable<TSource> where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (sourceCollection == null) { throw new ArgumentNullException(nameof(sourceCollection)); } if (destinationCollection == null) { throw new ArgumentNullException(nameof(destinationCollection)); } var i = 0; foreach (var item in sourceCollection) { var destination = Factory<TDestination>.CreateInstance(); translator.Map(item, destination); destinationCollection[i] = destination; ++i; } return destinationCollection; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> translator, List<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Count]; for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination[i] = destinationItem; } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> translator, Collection<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Count]; for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination[i] = destinationItem; } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> translator, TSource[] source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Length]; for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination[i] = destinationItem; } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static TDestination[] MapArray<TSource, TDestination>( this IMapper<TSource, TDestination> translator, IEnumerable<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new TDestination[source.Count()]; var i = 0; foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination[i] = destinationItem; ++i; } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource" /> into a collection of type /// <typeparamref name="TDestinationCollection" /> containing objects of type <typeparamref name="TDestination" />. /// </summary> /// <typeparam name="TSourceCollection">The type of the source collection.</typeparam> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestinationCollection">The type of the destination collection.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="sourceCollection">The source collection.</param> /// <param name="destinationCollection">The destination collection.</param> /// <returns>A collection of type <typeparamref name="TDestinationCollection"/> containing objects of type /// <typeparamref name="TDestination" />. /// </returns> /// <exception cref="ArgumentNullException">The <paramref name="translator" /> or <paramref name="sourceCollection" /> is /// <c>null</c>.</exception> public static TDestinationCollection MapCollection<TSourceCollection, TSource, TDestinationCollection, TDestination>( this IMapper<TSource, TDestination> translator, TSourceCollection sourceCollection, TDestinationCollection destinationCollection) where TSourceCollection : IEnumerable<TSource> where TDestinationCollection : ICollection<TDestination> where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (sourceCollection == null) { throw new ArgumentNullException(nameof(sourceCollection)); } foreach (var item in sourceCollection) { var destination = Factory<TDestination>.CreateInstance(); translator.Map(item, destination); destinationCollection.Add(destination); } return destinationCollection; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> translator, List<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> translator, Collection<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> translator, TSource[] source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static Collection<TDestination> MapCollection<TSource, TDestination>( this IMapper<TSource, TDestination> translator, IEnumerable<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new Collection<TDestination>(); foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Add(destinationItem); } return destination; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> translator, List<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Count); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> translator, Collection<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Count); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> translator, TSource[] source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Length); for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static List<TDestination> MapList<TSource, TDestination>( this IMapper<TSource, TDestination> translator, IEnumerable<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new List<TDestination>(source.Count()); foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Add(destinationItem); } return destination; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> translator, List<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> translator, Collection<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < source.Count; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> translator, TSource[] source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < source.Length; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Insert(i, destinationItem); } return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="translator">The translator.</param> /// <param name="source">The source objects.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="translator"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static ObservableCollection<TDestination> MapObservableCollection<TSource, TDestination>( this IMapper<TSource, TDestination> translator, IEnumerable<TSource> source) where TDestination : new() { if (translator == null) { throw new ArgumentNullException(nameof(translator)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } var destination = new ObservableCollection<TDestination>(); foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); translator.Map(sourceItem, destinationItem); destination.Add(destinationItem); } return destination; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Security; using System.Xml.Schema; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.Versioning; namespace System.Xml { internal partial class XmlTextReaderImpl { // // ParsingState // // Parsing state (aka. scanner data) - holds parsing buffer and entity input data information private struct ParsingState { // character buffer internal char[] chars; internal int charPos; internal int charsUsed; internal Encoding encoding; internal bool appendMode; // input stream & byte buffer internal Stream stream; internal Decoder decoder; internal byte[] bytes; internal int bytePos; internal int bytesUsed; // input text reader internal TextReader textReader; // current line number & position internal int lineNo; internal int lineStartPos; // base uri of the current entity internal string baseUriStr; internal Uri baseUri; // eof flag of the entity internal bool isEof; internal bool isStreamEof; // entity type & id internal IDtdEntityInfo entity; internal int entityId; // normalization internal bool eolNormalized; // EndEntity reporting internal bool entityResolvedManually; internal void Clear() { chars = null; charPos = 0; charsUsed = 0; encoding = null; stream = null; decoder = null; bytes = null; bytePos = 0; bytesUsed = 0; textReader = null; lineNo = 1; lineStartPos = -1; baseUriStr = string.Empty; baseUri = null; isEof = false; isStreamEof = false; eolNormalized = true; entityResolvedManually = false; } internal void Close(bool closeInput) { if (closeInput) { if (stream != null) { stream.Dispose(); } else if (textReader != null) { textReader.Dispose(); } } } internal int LineNo { get { return lineNo; } } internal int LinePos { get { return charPos - lineStartPos; } } } // // XmlContext // private class XmlContext { internal XmlSpace xmlSpace; internal string xmlLang; internal string defaultNamespace; internal XmlContext previousContext; internal XmlContext() { xmlSpace = XmlSpace.None; xmlLang = string.Empty; defaultNamespace = string.Empty; previousContext = null; } internal XmlContext(XmlContext previousContext) { this.xmlSpace = previousContext.xmlSpace; this.xmlLang = previousContext.xmlLang; this.defaultNamespace = previousContext.defaultNamespace; this.previousContext = previousContext; } } // // NoNamespaceManager // private class NoNamespaceManager : XmlNamespaceManager { public NoNamespaceManager() : base() { } public override string DefaultNamespace { get { return string.Empty; } } public override void PushScope() { } public override bool PopScope() { return false; } public override void AddNamespace(string prefix, string uri) { } public override void RemoveNamespace(string prefix, string uri) { } public override IEnumerator GetEnumerator() { return null; } public override IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { return null; } public override string LookupNamespace(string prefix) { return string.Empty; } public override string LookupPrefix(string uri) { return null; } public override bool HasNamespace(string prefix) { return false; } } // // DtdParserProxy: IDtdParserAdapter proxy for XmlTextReaderImpl // internal partial class DtdParserProxy : IDtdParserAdapterV1 { // Fields private XmlTextReaderImpl _reader; // Constructors internal DtdParserProxy(XmlTextReaderImpl reader) { _reader = reader; } // IDtdParserAdapter proxies XmlNameTable IDtdParserAdapter.NameTable { get { return _reader.DtdParserProxy_NameTable; } } IXmlNamespaceResolver IDtdParserAdapter.NamespaceResolver { get { return _reader.DtdParserProxy_NamespaceResolver; } } Uri IDtdParserAdapter.BaseUri { // SxS: DtdParserProxy_BaseUri property on the reader may expose machine scope resources. This property // is just returning the value of the other property, so it may expose machine scope resource as well. get { return _reader.DtdParserProxy_BaseUri; } } bool IDtdParserAdapter.IsEof { get { return _reader.DtdParserProxy_IsEof; } } char[] IDtdParserAdapter.ParsingBuffer { get { return _reader.DtdParserProxy_ParsingBuffer; } } int IDtdParserAdapter.ParsingBufferLength { get { return _reader.DtdParserProxy_ParsingBufferLength; } } int IDtdParserAdapter.CurrentPosition { get { return _reader.DtdParserProxy_CurrentPosition; } set { _reader.DtdParserProxy_CurrentPosition = value; } } int IDtdParserAdapter.EntityStackLength { get { return _reader.DtdParserProxy_EntityStackLength; } } bool IDtdParserAdapter.IsEntityEolNormalized { get { return _reader.DtdParserProxy_IsEntityEolNormalized; } } void IDtdParserAdapter.OnNewLine(int pos) { _reader.DtdParserProxy_OnNewLine(pos); } int IDtdParserAdapter.LineNo { get { return _reader.DtdParserProxy_LineNo; } } int IDtdParserAdapter.LineStartPosition { get { return _reader.DtdParserProxy_LineStartPosition; } } int IDtdParserAdapter.ReadData() { return _reader.DtdParserProxy_ReadData(); } int IDtdParserAdapter.ParseNumericCharRef(StringBuilder internalSubsetBuilder) { return _reader.DtdParserProxy_ParseNumericCharRef(internalSubsetBuilder); } int IDtdParserAdapter.ParseNamedCharRef(bool expand, StringBuilder internalSubsetBuilder) { return _reader.DtdParserProxy_ParseNamedCharRef(expand, internalSubsetBuilder); } void IDtdParserAdapter.ParsePI(StringBuilder sb) { _reader.DtdParserProxy_ParsePI(sb); } void IDtdParserAdapter.ParseComment(StringBuilder sb) { _reader.DtdParserProxy_ParseComment(sb); } bool IDtdParserAdapter.PushEntity(IDtdEntityInfo entity, out int entityId) { return _reader.DtdParserProxy_PushEntity(entity, out entityId); } bool IDtdParserAdapter.PopEntity(out IDtdEntityInfo oldEntity, out int newEntityId) { return _reader.DtdParserProxy_PopEntity(out oldEntity, out newEntityId); } bool IDtdParserAdapter.PushExternalSubset(string systemId, string publicId) { return _reader.DtdParserProxy_PushExternalSubset(systemId, publicId); } void IDtdParserAdapter.PushInternalDtd(string baseUri, string internalDtd) { Debug.Assert(internalDtd != null); _reader.DtdParserProxy_PushInternalDtd(baseUri, internalDtd); } void IDtdParserAdapter.Throw(Exception e) { _reader.DtdParserProxy_Throw(e); } void IDtdParserAdapter.OnSystemId(string systemId, LineInfo keywordLineInfo, LineInfo systemLiteralLineInfo) { _reader.DtdParserProxy_OnSystemId(systemId, keywordLineInfo, systemLiteralLineInfo); } void IDtdParserAdapter.OnPublicId(string publicId, LineInfo keywordLineInfo, LineInfo publicLiteralLineInfo) { _reader.DtdParserProxy_OnPublicId(publicId, keywordLineInfo, publicLiteralLineInfo); } bool IDtdParserAdapterWithValidation.DtdValidation { get { return _reader.DtdParserProxy_DtdValidation; } } IValidationEventHandling IDtdParserAdapterWithValidation.ValidationEventHandling { get { return _reader.DtdParserProxy_ValidationEventHandling; } } bool IDtdParserAdapterV1.Normalization { get { return _reader.DtdParserProxy_Normalization; } } bool IDtdParserAdapterV1.Namespaces { get { return _reader.DtdParserProxy_Namespaces; } } bool IDtdParserAdapterV1.V1CompatibilityMode { get { return _reader.DtdParserProxy_V1CompatibilityMode; } } } // // NodeData // private class NodeData : IComparable { // static instance with no data - is used when XmlTextReader is closed private static volatile NodeData s_None; // NOTE: Do not use this property for reference comparison. It may not be unique. internal static NodeData None { get { if (s_None == null) { // no locking; s_None is immutable so it's not a problem that it may get initialized more than once s_None = new NodeData(); } return s_None; } } // type internal XmlNodeType type; // name internal string localName; internal string prefix; internal string ns; internal string nameWPrefix; // value: // value == null -> the value is kept in the 'chars' buffer starting at valueStartPos and valueLength long private string _value; private char[] _chars; private int _valueStartPos; private int _valueLength; // main line info internal LineInfo lineInfo; // second line info internal LineInfo lineInfo2; // quote char for attributes internal char quoteChar; // depth internal int depth; // empty element / default attribute private bool _isEmptyOrDefault; // entity id internal int entityId; // helper members internal bool xmlContextPushed; // attribute value chunks internal NodeData nextAttrValueChunk; // type info internal object schemaType; internal object typedValue; internal NodeData() { Clear(XmlNodeType.None); xmlContextPushed = false; } internal int LineNo { get { return lineInfo.lineNo; } } internal int LinePos { get { return lineInfo.linePos; } } internal bool IsEmptyElement { get { return type == XmlNodeType.Element && _isEmptyOrDefault; } set { Debug.Assert(type == XmlNodeType.Element); _isEmptyOrDefault = value; } } internal bool IsDefaultAttribute { get { return type == XmlNodeType.Attribute && _isEmptyOrDefault; } set { Debug.Assert(type == XmlNodeType.Attribute); _isEmptyOrDefault = value; } } internal bool ValueBuffered { get { return _value == null; } } internal string StringValue { get { Debug.Assert(_valueStartPos >= 0 || _value != null, "Value not ready."); if (_value == null) { _value = new string(_chars, _valueStartPos, _valueLength); } return _value; } } internal void TrimSpacesInValue() { if (ValueBuffered) { XmlTextReaderImpl.StripSpaces(_chars, _valueStartPos, ref _valueLength); } else { _value = XmlTextReaderImpl.StripSpaces(_value); } } internal void Clear(XmlNodeType type) { this.type = type; ClearName(); _value = string.Empty; _valueStartPos = -1; nameWPrefix = string.Empty; schemaType = null; typedValue = null; } internal void ClearName() { localName = string.Empty; prefix = string.Empty; ns = string.Empty; nameWPrefix = string.Empty; } internal void SetLineInfo(int lineNo, int linePos) { lineInfo.Set(lineNo, linePos); } internal void SetLineInfo2(int lineNo, int linePos) { lineInfo2.Set(lineNo, linePos); } internal void SetValueNode(XmlNodeType type, string value) { Debug.Assert(value != null); this.type = type; ClearName(); _value = value; _valueStartPos = -1; } internal void SetValueNode(XmlNodeType type, char[] chars, int startPos, int len) { this.type = type; ClearName(); _value = null; _chars = chars; _valueStartPos = startPos; _valueLength = len; } internal void SetNamedNode(XmlNodeType type, string localName) { SetNamedNode(type, localName, string.Empty, localName); } internal void SetNamedNode(XmlNodeType type, string localName, string prefix, string nameWPrefix) { Debug.Assert(localName != null); Debug.Assert(localName.Length > 0); this.type = type; this.localName = localName; this.prefix = prefix; this.nameWPrefix = nameWPrefix; this.ns = string.Empty; _value = string.Empty; _valueStartPos = -1; } internal void SetValue(string value) { _valueStartPos = -1; _value = value; } internal void SetValue(char[] chars, int startPos, int len) { _value = null; _chars = chars; _valueStartPos = startPos; _valueLength = len; } internal void OnBufferInvalidated() { if (_value == null) { Debug.Assert(_valueStartPos != -1); Debug.Assert(_chars != null); _value = new string(_chars, _valueStartPos, _valueLength); } _valueStartPos = -1; } internal void CopyTo(int valueOffset, StringBuilder sb) { if (_value == null) { Debug.Assert(_valueStartPos != -1); Debug.Assert(_chars != null); sb.Append(_chars, _valueStartPos + valueOffset, _valueLength - valueOffset); } else { if (valueOffset <= 0) { sb.Append(_value); } else { sb.Append(_value, valueOffset, _value.Length - valueOffset); } } } internal int CopyTo(int valueOffset, char[] buffer, int offset, int length) { if (_value == null) { Debug.Assert(_valueStartPos != -1); Debug.Assert(_chars != null); int copyCount = _valueLength - valueOffset; if (copyCount > length) { copyCount = length; } XmlTextReaderImpl.BlockCopyChars(_chars, _valueStartPos + valueOffset, buffer, offset, copyCount); return copyCount; } else { int copyCount = _value.Length - valueOffset; if (copyCount > length) { copyCount = length; } _value.CopyTo(valueOffset, buffer, offset, copyCount); return copyCount; } } internal int CopyToBinary(IncrementalReadDecoder decoder, int valueOffset) { if (_value == null) { Debug.Assert(_valueStartPos != -1); Debug.Assert(_chars != null); return decoder.Decode(_chars, _valueStartPos + valueOffset, _valueLength - valueOffset); } else { return decoder.Decode(_value, valueOffset, _value.Length - valueOffset); } } internal void AdjustLineInfo(int valueOffset, bool isNormalized, ref LineInfo lineInfo) { if (valueOffset == 0) { return; } if (_valueStartPos != -1) { XmlTextReaderImpl.AdjustLineInfo(_chars, _valueStartPos, _valueStartPos + valueOffset, isNormalized, ref lineInfo); } else { XmlTextReaderImpl.AdjustLineInfo(_value, 0, valueOffset, isNormalized, ref lineInfo); } } // This should be inlined by JIT compiler internal string GetNameWPrefix(XmlNameTable nt) { if (nameWPrefix != null) { return nameWPrefix; } else { return CreateNameWPrefix(nt); } } internal string CreateNameWPrefix(XmlNameTable nt) { Debug.Assert(nameWPrefix == null); if (prefix.Length == 0) { nameWPrefix = localName; } else { nameWPrefix = nt.Add(string.Concat(prefix, ":", localName)); } return nameWPrefix; } int IComparable.CompareTo(object obj) { NodeData other = obj as NodeData; if (other != null) { if (Ref.Equal(localName, other.localName)) { if (Ref.Equal(ns, other.ns)) { return 0; } else { return string.CompareOrdinal(ns, other.ns); } } else { return string.CompareOrdinal(localName, other.localName); } } else { Debug.Assert(false, "We should never get to this point."); // 'other' is null, 'this' is not null. Always return 1, like "".CompareTo(null). return 1; } } } // // DtdDefaultAttributeInfoToNodeDataComparer // // Compares IDtdDefaultAttributeInfo to NodeData private class DtdDefaultAttributeInfoToNodeDataComparer : IComparer<object> { private static IComparer<object> s_instance = new DtdDefaultAttributeInfoToNodeDataComparer(); internal static IComparer<object> Instance { get { return s_instance; } } public int Compare(object x, object y) { Debug.Assert(x == null || x is NodeData || x is IDtdDefaultAttributeInfo); Debug.Assert(y == null || y is NodeData || y is IDtdDefaultAttributeInfo); string localName, localName2; string prefix, prefix2; if (x == null) { return y == null ? 0 : -1; } else if (y == null) { return 1; } NodeData nodeData = x as NodeData; if (nodeData != null) { localName = nodeData.localName; prefix = nodeData.prefix; } else { IDtdDefaultAttributeInfo attrDef = x as IDtdDefaultAttributeInfo; if (attrDef != null) { localName = attrDef.LocalName; prefix = attrDef.Prefix; } else { throw new XmlException(SR.Xml_DefaultException, string.Empty); } } nodeData = y as NodeData; if (nodeData != null) { localName2 = nodeData.localName; prefix2 = nodeData.prefix; } else { IDtdDefaultAttributeInfo attrDef = y as IDtdDefaultAttributeInfo; if (attrDef != null) { localName2 = attrDef.LocalName; prefix2 = attrDef.Prefix; } else { throw new XmlException(SR.Xml_DefaultException, string.Empty); } } // string.Compare does reference euqality first for us, so we don't have to do it here int result = string.Compare(localName, localName2, StringComparison.Ordinal); if (result != 0) { return result; } return string.Compare(prefix, prefix2, StringComparison.Ordinal); } } // // OnDefaultAttributeUse delegate // internal delegate void OnDefaultAttributeUseDelegate(IDtdDefaultAttributeInfo defaultAttribute, XmlTextReaderImpl coreReader); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace Internal.Cryptography.Pal.Native { internal enum CertQueryObjectType : int { CERT_QUERY_OBJECT_FILE = 0x00000001, CERT_QUERY_OBJECT_BLOB = 0x00000002, } [Flags] internal enum ExpectedContentTypeFlags : int { //encoded single certificate CERT_QUERY_CONTENT_FLAG_CERT = 1 << ContentType.CERT_QUERY_CONTENT_CERT, //encoded single CTL CERT_QUERY_CONTENT_FLAG_CTL = 1 << ContentType.CERT_QUERY_CONTENT_CTL, //encoded single CRL CERT_QUERY_CONTENT_FLAG_CRL = 1 << ContentType.CERT_QUERY_CONTENT_CRL, //serialized store CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_STORE, //serialized single certificate CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CERT, //serialized single CTL CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CTL, //serialized single CRL CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CRL, //an encoded PKCS#7 signed message CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED, //an encoded PKCS#7 message. But it is not a signed message CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_UNSIGNED, //the content includes an embedded PKCS7 signed message CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED, //an encoded PKCS#10 CERT_QUERY_CONTENT_FLAG_PKCS10 = 1 << ContentType.CERT_QUERY_CONTENT_PKCS10, //an encoded PFX BLOB CERT_QUERY_CONTENT_FLAG_PFX = 1 << ContentType.CERT_QUERY_CONTENT_PFX, //an encoded CertificatePair (contains forward and/or reverse cross certs) CERT_QUERY_CONTENT_FLAG_CERT_PAIR = 1 << ContentType.CERT_QUERY_CONTENT_CERT_PAIR, //an encoded PFX BLOB, and we do want to load it (not included in //CERT_QUERY_CONTENT_FLAG_ALL) CERT_QUERY_CONTENT_FLAG_PFX_AND_LOAD = 1 << ContentType.CERT_QUERY_CONTENT_PFX_AND_LOAD, CERT_QUERY_CONTENT_FLAG_ALL = CERT_QUERY_CONTENT_FLAG_CERT | CERT_QUERY_CONTENT_FLAG_CTL | CERT_QUERY_CONTENT_FLAG_CRL | CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL | CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED | CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED | CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED | CERT_QUERY_CONTENT_FLAG_PKCS10 | CERT_QUERY_CONTENT_FLAG_PFX | CERT_QUERY_CONTENT_FLAG_CERT_PAIR, } [Flags] internal enum ExpectedFormatTypeFlags : int { CERT_QUERY_FORMAT_FLAG_BINARY = 1 << FormatType.CERT_QUERY_FORMAT_BINARY, CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED = 1 << FormatType.CERT_QUERY_FORMAT_BASE64_ENCODED, CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED = 1 << FormatType.CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED, CERT_QUERY_FORMAT_FLAG_ALL = CERT_QUERY_FORMAT_FLAG_BINARY | CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED | CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED, } internal enum CertEncodingType : int { PKCS_7_ASN_ENCODING = 0x10000, X509_ASN_ENCODING = 0x00001, All = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, } internal enum ContentType : int { //encoded single certificate CERT_QUERY_CONTENT_CERT = 1, //encoded single CTL CERT_QUERY_CONTENT_CTL = 2, //encoded single CRL CERT_QUERY_CONTENT_CRL = 3, //serialized store CERT_QUERY_CONTENT_SERIALIZED_STORE = 4, //serialized single certificate CERT_QUERY_CONTENT_SERIALIZED_CERT = 5, //serialized single CTL CERT_QUERY_CONTENT_SERIALIZED_CTL = 6, //serialized single CRL CERT_QUERY_CONTENT_SERIALIZED_CRL = 7, //a PKCS#7 signed message CERT_QUERY_CONTENT_PKCS7_SIGNED = 8, //a PKCS#7 message, such as enveloped message. But it is not a signed message, CERT_QUERY_CONTENT_PKCS7_UNSIGNED = 9, //a PKCS7 signed message embedded in a file CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED = 10, //an encoded PKCS#10 CERT_QUERY_CONTENT_PKCS10 = 11, //an encoded PFX BLOB CERT_QUERY_CONTENT_PFX = 12, //an encoded CertificatePair (contains forward and/or reverse cross certs) CERT_QUERY_CONTENT_CERT_PAIR = 13, //an encoded PFX BLOB, which was loaded to phCertStore CERT_QUERY_CONTENT_PFX_AND_LOAD = 14, } internal enum FormatType : int { CERT_QUERY_FORMAT_BINARY = 1, CERT_QUERY_FORMAT_BASE64_ENCODED = 2, CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED = 3, } // CRYPTOAPI_BLOB has many typedef aliases in the C++ world (CERT_BLOB, DATA_BLOB, etc.) We'll just stick to one name here. [StructLayout(LayoutKind.Sequential)] internal unsafe struct CRYPTOAPI_BLOB { public CRYPTOAPI_BLOB(int cbData, byte* pbData) { this.cbData = cbData; this.pbData = pbData; } public int cbData; public byte* pbData; public byte[] ToByteArray() { if (cbData == 0) { return Array.Empty<byte>(); } byte[] array = new byte[cbData]; Marshal.Copy((IntPtr)pbData, array, 0, cbData); return array; } } internal enum CertContextPropId : int { CERT_KEY_PROV_INFO_PROP_ID = 2, CERT_SHA1_HASH_PROP_ID = 3, CERT_KEY_CONTEXT_PROP_ID = 5, CERT_FRIENDLY_NAME_PROP_ID = 11, CERT_ARCHIVED_PROP_ID = 19, CERT_KEY_IDENTIFIER_PROP_ID = 20, CERT_PUBKEY_ALG_PARA_PROP_ID = 22, CERT_NCRYPT_KEY_HANDLE_PROP_ID = 78, // CERT_DELETE_KEYSET_PROP_ID is not defined by Windows. It's a custom property set by the framework // as a backchannel message from the portion of X509Certificate2Collection.Import() that loads up the PFX // to the X509Certificate2..ctor(IntPtr) call that creates the managed wrapper. CERT_DELETE_KEYSET_PROP_ID = 101, } [Flags] internal enum CertSetPropertyFlags : int { CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG = 0x40000000, None = 0x00000000, } internal enum CertNameType : int { CERT_NAME_EMAIL_TYPE = 1, CERT_NAME_RDN_TYPE = 2, CERT_NAME_ATTR_TYPE = 3, CERT_NAME_SIMPLE_DISPLAY_TYPE = 4, CERT_NAME_FRIENDLY_DISPLAY_TYPE = 5, CERT_NAME_DNS_TYPE = 6, CERT_NAME_URL_TYPE = 7, CERT_NAME_UPN_TYPE = 8, } [Flags] internal enum CertNameFlags : int { None = 0x00000000, CERT_NAME_ISSUER_FLAG = 0x00000001, } internal enum CertNameStringType : int { CERT_X500_NAME_STR = 3, CERT_NAME_STR_REVERSE_FLAG = 0x02000000, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CONTEXT { public CertEncodingType dwCertEncodingType; public byte* pbCertEncoded; public int cbCertEncoded; public CERT_INFO* pCertInfo; public IntPtr hCertStore; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_INFO { public int dwVersion; public CRYPTOAPI_BLOB SerialNumber; public CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; public CRYPTOAPI_BLOB Issuer; public FILETIME NotBefore; public FILETIME NotAfter; public CRYPTOAPI_BLOB Subject; public CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo; public CRYPT_BIT_BLOB IssuerUniqueId; public CRYPT_BIT_BLOB SubjectUniqueId; public int cExtension; public CERT_EXTENSION* rgExtension; } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_ALGORITHM_IDENTIFIER { public IntPtr pszObjId; public CRYPTOAPI_BLOB Parameters; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_PUBLIC_KEY_INFO { public CRYPT_ALGORITHM_IDENTIFIER Algorithm; public CRYPT_BIT_BLOB PublicKey; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CRYPT_BIT_BLOB { public int cbData; public byte* pbData; public int cUnusedBits; public byte[] ToByteArray() { if (cbData == 0) { return Array.Empty<byte>(); } byte[] array = new byte[cbData]; Marshal.Copy((IntPtr)pbData, array, 0, cbData); return array; } } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_EXTENSION { public IntPtr pszObjId; public int fCritical; public CRYPTOAPI_BLOB Value; } [StructLayout(LayoutKind.Sequential)] internal struct FILETIME { private uint ftTimeLow; private uint ftTimeHigh; public DateTime ToDateTime() { long fileTime = (((long)ftTimeHigh) << 32) + ftTimeLow; return DateTime.FromFileTime(fileTime); } public static FILETIME FromDateTime(DateTime dt) { long fileTime = dt.ToFileTime(); unchecked { return new FILETIME() { ftTimeLow = (uint)fileTime, ftTimeHigh = (uint)(fileTime >> 32), }; } } } internal enum CertStoreProvider : int { CERT_STORE_PROV_MEMORY = 2, CERT_STORE_PROV_SYSTEM_W = 10, } [Flags] internal enum CertStoreFlags : int { CERT_STORE_NO_CRYPT_RELEASE_FLAG = 0x00000001, CERT_STORE_SET_LOCALIZED_NAME_FLAG = 0x00000002, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004, CERT_STORE_DELETE_FLAG = 0x00000010, CERT_STORE_UNSAFE_PHYSICAL_FLAG = 0x00000020, CERT_STORE_SHARE_STORE_FLAG = 0x00000040, CERT_STORE_SHARE_CONTEXT_FLAG = 0x00000080, CERT_STORE_MANIFOLD_FLAG = 0x00000100, CERT_STORE_ENUM_ARCHIVED_FLAG = 0x00000200, CERT_STORE_UPDATE_KEYID_FLAG = 0x00000400, CERT_STORE_BACKUP_RESTORE_FLAG = 0x00000800, CERT_STORE_READONLY_FLAG = 0x00008000, CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000, CERT_STORE_CREATE_NEW_FLAG = 0x00002000, CERT_STORE_MAXIMUM_ALLOWED_FLAG = 0x00001000, CERT_SYSTEM_STORE_CURRENT_USER = 0x00010000, CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x00020000, None = 0x00000000, } internal enum CertStoreAddDisposition : int { CERT_STORE_ADD_NEW = 1, CERT_STORE_ADD_USE_EXISTING = 2, CERT_STORE_ADD_REPLACE_EXISTING = 3, CERT_STORE_ADD_ALWAYS = 4, CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES = 5, CERT_STORE_ADD_NEWER = 6, CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES = 7, } [Flags] internal enum PfxCertStoreFlags : int { CRYPT_EXPORTABLE = 0x00000001, CRYPT_USER_PROTECTED = 0x00000002, CRYPT_MACHINE_KEYSET = 0x00000020, CRYPT_USER_KEYSET = 0x00001000, PKCS12_PREFER_CNG_KSP = 0x00000100, PKCS12_ALWAYS_CNG_KSP = 0x00000200, PKCS12_ALLOW_OVERWRITE_KEY = 0x00004000, PKCS12_NO_PERSIST_KEY = 0x00008000, PKCS12_INCLUDE_EXTENDED_PROPERTIES = 0x00000010, None = 0x00000000, } internal enum CryptMessageParameterType : int { CMSG_SIGNER_COUNT_PARAM = 5, CMSG_SIGNER_INFO_PARAM = 6, } [StructLayout(LayoutKind.Sequential)] internal struct CMSG_SIGNER_INFO_Partial // This is not the full definition of CMSG_SIGNER_INFO. Only defining the part we use. { public int dwVersion; public CRYPTOAPI_BLOB Issuer; public CRYPTOAPI_BLOB SerialNumber; //... more fields follow ... } [Flags] internal enum CertFindFlags : int { None = 0x00000000, } internal enum CertFindType : int { CERT_FIND_SUBJECT_CERT = 0x000b0000, CERT_FIND_HASH = 0x00010000, CERT_FIND_SUBJECT_STR = 0x00080007, CERT_FIND_ISSUER_STR = 0x00080004, CERT_FIND_EXISTING = 0x000d0000, CERT_FIND_ANY = 0x00000000, } [Flags] internal enum PFXExportFlags : int { REPORT_NO_PRIVATE_KEY = 0x00000001, REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY = 0x00000002, EXPORT_PRIVATE_KEYS = 0x00000004, None = 0x00000000, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CRYPT_KEY_PROV_INFO { public char* pwszContainerName; public char* pwszProvName; public int dwProvType; public CryptAcquireContextFlags dwFlags; public int cProvParam; public IntPtr rgProvParam; public int dwKeySpec; } [Flags] internal enum CryptAcquireContextFlags : int { CRYPT_DELETEKEYSET = 0x00000010, CRYPT_MACHINE_KEYSET = 0x00000020, None = 0x00000000, } [Flags] internal enum CertNameStrTypeAndFlags : int { CERT_SIMPLE_NAME_STR = 1, CERT_OID_NAME_STR = 2, CERT_X500_NAME_STR = 3, CERT_NAME_STR_SEMICOLON_FLAG = 0x40000000, CERT_NAME_STR_NO_PLUS_FLAG = 0x20000000, CERT_NAME_STR_NO_QUOTING_FLAG = 0x10000000, CERT_NAME_STR_CRLF_FLAG = 0x08000000, CERT_NAME_STR_COMMA_FLAG = 0x04000000, CERT_NAME_STR_REVERSE_FLAG = 0x02000000, CERT_NAME_STR_DISABLE_IE4_UTF8_FLAG = 0x00010000, CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG = 0x00020000, CERT_NAME_STR_ENABLE_UTF8_UNICODE_FLAG = 0x00040000, CERT_NAME_STR_FORCE_UTF8_DIR_STR_FLAG = 0x00080000, } internal enum FormatObjectType : int { None = 0, } [Flags] internal enum FormatObjectStringType : int { CRYPT_FORMAT_STR_MULTI_LINE = 0x00000001, CRYPT_FORMAT_STR_NO_HEX = 0x00000010, None = 0x00000000, } internal enum FormatObjectStructType : int { X509_NAME = 7, } internal static class AlgId { public const int CALG_RSA_KEYX = 0xa400; public const int CALG_RSA_SIGN = 0x2400; public const int CALG_DSS_SIGN = 0x2200; public const int CALG_SHA1 = 0x8004; } [Flags] internal enum CryptDecodeObjectFlags : int { None = 0x00000000, } internal enum CryptDecodeObjectStructType : int { CNG_RSA_PUBLIC_KEY_BLOB = 72, X509_DSS_PUBLICKEY = 38, X509_DSS_PARAMETERS = 39, X509_KEY_USAGE = 14, X509_BASIC_CONSTRAINTS = 13, X509_BASIC_CONSTRAINTS2 = 15, X509_ENHANCED_KEY_USAGE = 36, X509_CERT_POLICIES = 16, X509_UNICODE_ANY_STRING = 24, X509_CERTIFICATE_TEMPLATE = 64, } [StructLayout(LayoutKind.Sequential)] internal struct CTL_USAGE { public int cUsageIdentifier; public IntPtr rgpszUsageIdentifier; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_USAGE_MATCH { public CertUsageMatchType dwType; public CTL_USAGE Usage; } internal enum CertUsageMatchType : int { USAGE_MATCH_TYPE_AND = 0x00000000, USAGE_MATCH_TYPE_OR = 0x00000001, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CHAIN_PARA { public int cbSize; public CERT_USAGE_MATCH RequestedUsage; public CERT_USAGE_MATCH RequestedIssuancePolicy; public int dwUrlRetrievalTimeout; public int fCheckRevocationFreshnessTime; public int dwRevocationFreshnessTime; public FILETIME* pftCacheResync; public int pStrongSignPara; public int dwStrongSignFlags; } [Flags] internal enum CertChainFlags : int { None = 0x00000000, CERT_CHAIN_REVOCATION_CHECK_END_CERT = 0x10000000, CERT_CHAIN_REVOCATION_CHECK_CHAIN = 0x20000000, CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 0x40000000, CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY = unchecked((int)0x80000000), } internal enum ChainEngine : int { HCCE_CURRENT_USER = 0x0, HCCE_LOCAL_MACHINE = 0x1, } [StructLayout(LayoutKind.Sequential)] internal struct CERT_DSS_PARAMETERS { public CRYPTOAPI_BLOB p; public CRYPTOAPI_BLOB q; public CRYPTOAPI_BLOB g; } internal enum PubKeyMagic : int { DSS_MAGIC = 0x31535344, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_BASIC_CONSTRAINTS_INFO { public CRYPT_BIT_BLOB SubjectType; public int fPathLenConstraint; public int dwPathLenConstraint; public int cSubtreesConstraint; public CRYPTOAPI_BLOB* rgSubtreesConstraint; // PCERT_NAME_BLOB // SubjectType.pbData[0] can contain a CERT_CA_SUBJECT_FLAG that when set indicates that the certificate's subject can act as a CA public const byte CERT_CA_SUBJECT_FLAG = 0x80; }; [StructLayout(LayoutKind.Sequential)] internal struct CERT_BASIC_CONSTRAINTS2_INFO { public int fCA; public int fPathLenConstraint; public int dwPathLenConstraint; }; [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_ENHKEY_USAGE { public int cUsageIdentifier; public IntPtr* rgpszUsageIdentifier; // LPSTR* } internal enum CertStoreSaveAs : int { CERT_STORE_SAVE_AS_STORE = 1, CERT_STORE_SAVE_AS_PKCS7 = 2, } internal enum CertStoreSaveTo : int { CERT_STORE_SAVE_TO_MEMORY = 2, } [StructLayout(LayoutKind.Sequential)] internal struct CERT_POLICY_INFO { public IntPtr pszPolicyIdentifier; public int cPolicyQualifier; public IntPtr rgPolicyQualifier; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_POLICIES_INFO { public int cPolicyInfo; public CERT_POLICY_INFO* rgPolicyInfo; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_NAME_VALUE { public int dwValueType; public CRYPTOAPI_BLOB Value; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_TEMPLATE_EXT { public IntPtr pszObjId; public int dwMajorVersion; public int fMinorVersion; public int dwMinorVersion; } [Flags] internal enum CertControlStoreFlags : int { None = 0x00000000, } internal enum CertControlStoreType : int { CERT_STORE_CTRL_AUTO_RESYNC = 4, } [Flags] internal enum CertTrustErrorStatus : int { CERT_TRUST_NO_ERROR = 0x00000000, CERT_TRUST_IS_NOT_TIME_VALID = 0x00000001, CERT_TRUST_IS_NOT_TIME_NESTED = 0x00000002, CERT_TRUST_IS_REVOKED = 0x00000004, CERT_TRUST_IS_NOT_SIGNATURE_VALID = 0x00000008, CERT_TRUST_IS_NOT_VALID_FOR_USAGE = 0x00000010, CERT_TRUST_IS_UNTRUSTED_ROOT = 0x00000020, CERT_TRUST_REVOCATION_STATUS_UNKNOWN = 0x00000040, CERT_TRUST_IS_CYCLIC = 0x00000080, CERT_TRUST_INVALID_EXTENSION = 0x00000100, CERT_TRUST_INVALID_POLICY_CONSTRAINTS = 0x00000200, CERT_TRUST_INVALID_BASIC_CONSTRAINTS = 0x00000400, CERT_TRUST_INVALID_NAME_CONSTRAINTS = 0x00000800, CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT = 0x00001000, CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT = 0x00002000, CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT = 0x00004000, CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT = 0x00008000, CERT_TRUST_IS_OFFLINE_REVOCATION = 0x01000000, CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY = 0x02000000, CERT_TRUST_IS_EXPLICIT_DISTRUST = 0x04000000, CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT = 0x08000000, CERT_TRUST_HAS_WEAK_SIGNATURE = 0x00100000, // These can be applied to chains only CERT_TRUST_IS_PARTIAL_CHAIN = 0x00010000, CERT_TRUST_CTL_IS_NOT_TIME_VALID = 0x00020000, CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID = 0x00040000, CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE = 0x00080000, } [Flags] internal enum CertTrustInfoStatus : int { // These can be applied to certificates only CERT_TRUST_HAS_EXACT_MATCH_ISSUER = 0x00000001, CERT_TRUST_HAS_KEY_MATCH_ISSUER = 0x00000002, CERT_TRUST_HAS_NAME_MATCH_ISSUER = 0x00000004, CERT_TRUST_IS_SELF_SIGNED = 0x00000008, // These can be applied to certificates and chains CERT_TRUST_HAS_PREFERRED_ISSUER = 0x00000100, CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY = 0x00000200, CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS = 0x00000400, // These can be applied to chains only CERT_TRUST_IS_COMPLEX_CHAIN = 0x00010000, } [StructLayout(LayoutKind.Sequential)] internal struct CERT_TRUST_STATUS { public CertTrustErrorStatus dwErrorStatus; public CertTrustInfoStatus dwInfoStatus; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CHAIN_ELEMENT { public int cbSize; public CERT_CONTEXT* pCertContext; public CERT_TRUST_STATUS TrustStatus; public IntPtr pRevocationInfo; public IntPtr pIssuanceUsage; public IntPtr pApplicationUsage; public IntPtr pwszExtendedErrorInfo; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_SIMPLE_CHAIN { public int cbSize; public CERT_TRUST_STATUS TrustStatus; public int cElement; public CERT_CHAIN_ELEMENT** rgpElement; public IntPtr pTrustListInfo; // fHasRevocationFreshnessTime is only set if we are able to retrieve // revocation information for all elements checked for revocation. // For a CRL its CurrentTime - ThisUpdate. // // dwRevocationFreshnessTime is the largest time across all elements // checked. public int fHasRevocationFreshnessTime; public int dwRevocationFreshnessTime; // seconds } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CHAIN_CONTEXT { public int cbSize; public CERT_TRUST_STATUS TrustStatus; public int cChain; public CERT_SIMPLE_CHAIN** rgpChain; // Following is returned when CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS // is set in dwFlags public int cLowerQualityChainContext; public CERT_CHAIN_CONTEXT** rgpLowerQualityChainContext; // fHasRevocationFreshnessTime is only set if we are able to retrieve // revocation information for all elements checked for revocation. // For a CRL its CurrentTime - ThisUpdate. // // dwRevocationFreshnessTime is the largest time across all elements // checked. public int fHasRevocationFreshnessTime; public int dwRevocationFreshnessTime; // seconds // Flags passed when created via CertGetCertificateChain public int dwCreateFlags; // Following is updated with unique Id when the chain context is logged. public Guid ChainId; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_CHAIN_POLICY_PARA { public int cbSize; public int dwFlags; public IntPtr pvExtraPolicyPara; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_CHAIN_POLICY_STATUS { public int cbSize; public int dwError; public IntPtr lChainIndex; public IntPtr lElementIndex; public IntPtr pvExtraPolicyStatus; } internal enum ChainPolicy : int { // Predefined verify chain policies CERT_CHAIN_POLICY_BASE = 1, } internal enum CryptAcquireFlags : int { CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG = 0x00040000, } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Threading; using NUnit.Framework; using NUnit.Framework.Interfaces; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Internal; using OpenQA.Selenium.Support.UI; namespace Vzhzhzh.SeleniumWrapper { public class DriverHolder { private Lazy<IWebDriver> _lazyDriver = new Lazy<IWebDriver>(CreateDriver); public IWebDriver Instance { get { return _lazyDriver.Value; } } private const int TimeOut = 3; private static IWebDriver CreateDriver() { var driver = new ChromeDriver(); //new FirefoxDriver(); //new PhantomJSDriver(); driver.Manage().Timeouts() .ImplicitlyWait(TimeSpan.FromSeconds(TimeOut)) .SetScriptTimeout(TimeSpan.FromSeconds(TimeOut)); driver.Manage().Window.Size = new Size(1600, 1200); return driver; } public void OpenUrl(string url) { Instance.Navigate().GoToUrl(url); } public IWebElement Find(By by, bool mustBePresent = true) { try { return Instance.FindElement(by); } catch (Exception) { if (mustBePresent) { throw; } } return null; } public IWebElement LongFind(By by, int timeout = 30, bool mustBePresent = true) { Wait(x => ExpectedConditions.ElementIsVisible(@by), timeout); Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(timeout)); var webElement = Find(@by, mustBePresent); Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(TimeOut)); return webElement; } public TResult Find<TResult>(By by, Func<IEnumerable<IWebElement>, TResult> filter) { return filter(Instance.FindElements(by)); } public SelectResult LongGetSelect(By by) { var element = LongFind(@by); return new SelectResult(element, new SelectElement(element)); } public SelectResult FindSelect(By by) { var element = Instance.FindElement(@by); return new SelectResult(element, new SelectElement(element)); } public void SelectFirstAutocompleteOption(IWebElement element) { Click(element); PressEnter(element); } public void CarefullySendKeys(IWebElement element, string value) { Clear(element); foreach (var letter in value) { Thread.Sleep(30); element.SendKeys(new string(letter, 1)); } Thread.Sleep(50); } public void Clear(IWebElement element) { EnsureAction(e => e.Clear(), element); } public void SendKeys(IWebElement element, string text) { EnsureAction(e => { e.SendKeys(text); }, element); } public void PressSpace(IWebElement element) { EnsureAction(e => e.SendKeys(Keys.Space), element); } public void PressEnter(IWebElement element) { EnsureAction(e => e.SendKeys(Keys.Enter), element); } public void Click(IWebElement element) { EnsureAction(e => e.Click(), element); } public void EnsureAction(Action<IWebElement> action, IWebElement element) { if (element != null) { Wait(d => ExpectedConditions.ElementToBeClickable(element), 1); } try { action(element); } catch (ElementNotVisibleException) { // Scroll the page more and retry the click. ((IJavaScriptExecutor)Instance).ExecuteScript("window.scrollBy(" + 0 + "," + 200 + ");"); action(element); } catch (InvalidOperationException) { // Scroll the page more and retry the click. ((IJavaScriptExecutor)Instance).ExecuteScript("window.scrollBy(" + 0 + "," + 200 + ");"); action(element); } } public TResult Wait<TResult>(Func<IWebDriver, TResult> condition, int thesholdInSeconds = 10) { var wait = new WebDriverWait(Instance, TimeSpan.FromSeconds(thesholdInSeconds)); return wait.Until(condition); } public void TearDown() { try { if (TestContext.CurrentContext.Result.Outcome == ResultState.Failure) { var wrapps = ((IWrapsDriver)Instance); if (wrapps != null) { var takesScreenshot = wrapps.WrappedDriver as ITakesScreenshot; if (takesScreenshot != null) { takesScreenshot.GetScreenshot() .SaveAsFile(TestContext.CurrentContext.Test.FullName + ".jpg", ImageFormat.Jpeg); } } } } catch { } try { Instance.Quit(); KillChromeDriverProcess(); _lazyDriver = new Lazy<IWebDriver>(CreateDriver); } catch { } } private static void KillChromeDriverProcess() { var processes = Process.GetProcessesByName("chromedriver.exe"); var chromeDriverProcess = processes.FirstOrDefault(); if (chromeDriverProcess != null) { chromeDriverProcess.Kill(); } } public class SelectResult { public IWebElement Element { get; private set; } public SelectElement Select { get; private set; } public SelectResult(IWebElement element, SelectElement select) { Element = element; Select = @select; } } } }
#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 //#if HAVE_ASYNC using System; using System.Globalization; using System.Threading; #if HAVE_BIG_INTEGER using System.Numerics; #endif using System.Threading.Tasks; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { public partial class JsonTextWriter { // It's not safe to perform the async methods here in a derived class as if the synchronous equivalent // has been overriden then the asychronous method will no longer be doing the same operation. #if HAVE_ASYNC // Double-check this isn't included inappropriately. private readonly bool _safeAsync; #endif /// <summary> /// Asynchronously flushes whatever is in the buffer to the destination and also flushes the destination. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task FlushAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoFlushAsync(cancellationToken) : base.FlushAsync(cancellationToken); } internal Task DoFlushAsync(CancellationToken cancellationToken) { return cancellationToken.CancelIfRequestedAsync() ?? _writer.FlushAsync(); } /// <summary> /// Asynchronously writes the JSON value delimiter. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> protected override Task WriteValueDelimiterAsync(CancellationToken cancellationToken) { return _safeAsync ? DoWriteValueDelimiterAsync(cancellationToken) : base.WriteValueDelimiterAsync(cancellationToken); } internal Task DoWriteValueDelimiterAsync(CancellationToken cancellationToken) { return _writer.WriteAsync(',', cancellationToken); } /// <summary> /// Asynchronously writes the specified end token. /// </summary> /// <param name="token">The end token to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> protected override Task WriteEndAsync(JsonToken token, CancellationToken cancellationToken) { return _safeAsync ? DoWriteEndAsync(token, cancellationToken) : base.WriteEndAsync(token, cancellationToken); } internal Task DoWriteEndAsync(JsonToken token, CancellationToken cancellationToken) { switch (token) { case JsonToken.EndObject: return _writer.WriteAsync('}', cancellationToken); case JsonToken.EndArray: return _writer.WriteAsync(']', cancellationToken); case JsonToken.EndConstructor: return _writer.WriteAsync(')', cancellationToken); default: throw JsonWriterException.Create(this, "Invalid JsonToken: " + token, null); } } /// <summary> /// Asynchronously closes this writer. /// If <see cref="JsonWriter.CloseOutput"/> is set to <c>true</c>, the destination is also closed. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task CloseAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoCloseAsync(cancellationToken) : base.CloseAsync(cancellationToken); } internal async Task DoCloseAsync(CancellationToken cancellationToken) { if (Top == 0) // otherwise will happen in calls to WriteEndAsync { cancellationToken.ThrowIfCancellationRequested(); } while (Top > 0) { await WriteEndAsync(cancellationToken).ConfigureAwait(false); } CloseBufferAndWriter(); } /// <summary> /// Asynchronously writes the end of the current JSON object or array. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteEndAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? WriteEndInternalAsync(cancellationToken) : base.WriteEndAsync(cancellationToken); } /// <summary> /// Asynchronously writes indent characters. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> protected override Task WriteIndentAsync(CancellationToken cancellationToken) { return _safeAsync ? DoWriteIndentAsync(cancellationToken) : base.WriteIndentAsync(cancellationToken); } internal Task DoWriteIndentAsync(CancellationToken cancellationToken) { // levels of indentation multiplied by the indent count int currentIndentCount = Top * _indentation; int newLineLen = SetIndentChars(); if (currentIndentCount <= IndentCharBufferSize) { return _writer.WriteAsync(_indentChars, 0, newLineLen + currentIndentCount, cancellationToken); } return WriteIndentAsync(currentIndentCount, newLineLen, cancellationToken); } private async Task WriteIndentAsync(int currentIndentCount, int newLineLen, CancellationToken cancellationToken) { await _writer.WriteAsync(_indentChars, 0, newLineLen + Math.Min(currentIndentCount, IndentCharBufferSize), cancellationToken).ConfigureAwait(false); while ((currentIndentCount -= IndentCharBufferSize) > 0) { await _writer.WriteAsync(_indentChars, newLineLen, Math.Min(currentIndentCount, IndentCharBufferSize), cancellationToken).ConfigureAwait(false); } } private Task WriteValueInternalAsync(JsonToken token, string value, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(token, cancellationToken); if (task.IsCompletedSucessfully()) { return _writer.WriteAsync(value, cancellationToken); } return WriteValueInternalAsync(task, value, cancellationToken); } private async Task WriteValueInternalAsync(Task task, string value, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await _writer.WriteAsync(value, cancellationToken).ConfigureAwait(false); } /// <summary> /// Asynchronously writes an indent space. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> protected override Task WriteIndentSpaceAsync(CancellationToken cancellationToken) { return _safeAsync ? DoWriteIndentSpaceAsync(cancellationToken) : base.WriteIndentSpaceAsync(cancellationToken); } internal Task DoWriteIndentSpaceAsync(CancellationToken cancellationToken) { return _writer.WriteAsync(' ', cancellationToken); } /// <summary> /// Asynchronously writes raw JSON without changing the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteRawAsync(string json, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteRawAsync(json, cancellationToken) : base.WriteRawAsync(json, cancellationToken); } internal Task DoWriteRawAsync(string json, CancellationToken cancellationToken) { return _writer.WriteAsync(json, cancellationToken); } /// <summary> /// Asynchronously writes a null value. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteNullAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteNullAsync(cancellationToken) : base.WriteNullAsync(cancellationToken); } internal Task DoWriteNullAsync(CancellationToken cancellationToken) { return WriteValueInternalAsync(JsonToken.Null, JsonConvert.Null, cancellationToken); } private Task WriteDigitsAsync(ulong uvalue, bool negative, CancellationToken cancellationToken) { if (uvalue <= 9 & !negative) { return _writer.WriteAsync((char)('0' + uvalue), cancellationToken); } int length = WriteNumberToBuffer(uvalue, negative); return _writer.WriteAsync(_writeBuffer, 0, length, cancellationToken); } private Task WriteIntegerValueAsync(ulong uvalue, bool negative, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.Integer, cancellationToken); if (task.IsCompletedSucessfully()) { return WriteDigitsAsync(uvalue, negative, cancellationToken); } return WriteIntegerValueAsync(task, uvalue, negative, cancellationToken); } private async Task WriteIntegerValueAsync(Task task, ulong uvalue, bool negative, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await WriteDigitsAsync(uvalue, negative, cancellationToken).ConfigureAwait(false); } internal Task WriteIntegerValueAsync(long value, CancellationToken cancellationToken) { bool negative = value < 0; if (negative) { value = -value; } return WriteIntegerValueAsync((ulong)value, negative, cancellationToken); } internal Task WriteIntegerValueAsync(ulong uvalue, CancellationToken cancellationToken) { return WriteIntegerValueAsync(uvalue, false, cancellationToken); } private Task WriteEscapedStringAsync(string value, bool quote, CancellationToken cancellationToken) { return JavaScriptUtils.WriteEscapedJavaScriptStringAsync(_writer, value, _quoteChar, quote, _charEscapeFlags, StringEscapeHandling, this, _writeBuffer, cancellationToken); } /// <summary> /// Asynchronously writes the property name of a name/value pair of a JSON object. /// </summary> /// <param name="name">The name of the property.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WritePropertyNameAsync(string name, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWritePropertyNameAsync(name, cancellationToken) : base.WritePropertyNameAsync(name, cancellationToken); } internal Task DoWritePropertyNameAsync(string name, CancellationToken cancellationToken) { Task task = InternalWritePropertyNameAsync(name, cancellationToken); if (task.Status != TaskStatus.RanToCompletion) { return DoWritePropertyNameAsync(task, name, cancellationToken); } task = WriteEscapedStringAsync(name, _quoteName, cancellationToken); if (task.Status == TaskStatus.RanToCompletion) { return _writer.WriteAsync(':', cancellationToken); } return JavaScriptUtils.WriteCharAsync(task, _writer, ':', cancellationToken); } private async Task DoWritePropertyNameAsync(Task task, string name, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await WriteEscapedStringAsync(name, _quoteName, cancellationToken).ConfigureAwait(false); await _writer.WriteAsync(':').ConfigureAwait(false); } /// <summary> /// Asynchronously writes the property name of a name/value pair of a JSON object. /// </summary> /// <param name="name">The name of the property.</param> /// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WritePropertyNameAsync(string name, bool escape, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWritePropertyNameAsync(name, escape, cancellationToken) : base.WritePropertyNameAsync(name, escape, cancellationToken); } internal async Task DoWritePropertyNameAsync(string name, bool escape, CancellationToken cancellationToken) { await InternalWritePropertyNameAsync(name, cancellationToken).ConfigureAwait(false); if (escape) { await WriteEscapedStringAsync(name, _quoteName, cancellationToken).ConfigureAwait(false); } else { if (_quoteName) { await _writer.WriteAsync(_quoteChar).ConfigureAwait(false); } await _writer.WriteAsync(name, cancellationToken).ConfigureAwait(false); if (_quoteName) { await _writer.WriteAsync(_quoteChar).ConfigureAwait(false); } } await _writer.WriteAsync(':').ConfigureAwait(false); } /// <summary> /// Asynchronously writes the beginning of a JSON array. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteStartArrayAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteStartArrayAsync(cancellationToken) : base.WriteStartArrayAsync(cancellationToken); } internal Task DoWriteStartArrayAsync(CancellationToken cancellationToken) { Task task = InternalWriteStartAsync(JsonToken.StartArray, JsonContainerType.Array, cancellationToken); if (task.Status == TaskStatus.RanToCompletion) { return _writer.WriteAsync('[', cancellationToken); } return DoWriteStartArrayAsync(task, cancellationToken); } internal async Task DoWriteStartArrayAsync(Task task, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await _writer.WriteAsync('[').ConfigureAwait(false); } /// <summary> /// Asynchronously writes the beginning of a JSON object. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteStartObjectAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteStartObjectAsync(cancellationToken) : base.WriteStartObjectAsync(cancellationToken); } internal Task DoWriteStartObjectAsync(CancellationToken cancellationToken) { Task task = InternalWriteStartAsync(JsonToken.StartObject, JsonContainerType.Object, cancellationToken); if (task.Status == TaskStatus.RanToCompletion) { return _writer.WriteAsync('{', cancellationToken); } return DoWriteStartObjectAsync(task, cancellationToken); } internal async Task DoWriteStartObjectAsync(Task task, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await _writer.WriteAsync('{').ConfigureAwait(false); } /// <summary> /// Asynchronously writes the start of a constructor with the given name. /// </summary> /// <param name="name">The name of the constructor.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteStartConstructorAsync(string name, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteStartConstructorAsync(name, cancellationToken) : base.WriteStartConstructorAsync(name, cancellationToken); } internal async Task DoWriteStartConstructorAsync(string name, CancellationToken cancellationToken) { await InternalWriteStartAsync(JsonToken.StartConstructor, JsonContainerType.Constructor, cancellationToken).ConfigureAwait(false); await _writer.WriteAsync("new ", cancellationToken).ConfigureAwait(false); await _writer.WriteAsync(name, cancellationToken).ConfigureAwait(false); await _writer.WriteAsync('(').ConfigureAwait(false); } /// <summary> /// Asynchronously writes an undefined value. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteUndefinedAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteUndefinedAsync(cancellationToken) : base.WriteUndefinedAsync(cancellationToken); } internal Task DoWriteUndefinedAsync(CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.Undefined, cancellationToken); if (task.Status == TaskStatus.RanToCompletion) { return _writer.WriteAsync(JsonConvert.Undefined, cancellationToken); } return DoWriteUndefinedAsync(task, cancellationToken); } private async Task DoWriteUndefinedAsync(Task task, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await _writer.WriteAsync(JsonConvert.Undefined, cancellationToken).ConfigureAwait(false); } internal Task DoWriteValueAsync(string value, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.String, cancellationToken); if (task.Status == TaskStatus.RanToCompletion) { return value == null ? _writer.WriteAsync(JsonConvert.Null, cancellationToken) : WriteEscapedStringAsync(value, true, cancellationToken); } return DoWriteValueAsync(task, value, cancellationToken); } private async Task DoWriteValueAsync(Task task, string value, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await (value == null ? _writer.WriteAsync(JsonConvert.Null, cancellationToken) : WriteEscapedStringAsync(value, true, cancellationToken)).ConfigureAwait(false); } /// <summary> /// Asynchronously writes a <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The <see cref="TimeSpan"/> value to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteValueAsync(TimeSpan value, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteValueAsync(value, cancellationToken) : base.WriteValueAsync(value, cancellationToken); } internal async Task DoWriteValueAsync(TimeSpan value, CancellationToken cancellationToken) { await InternalWriteValueAsync(JsonToken.String, cancellationToken).ConfigureAwait(false); await _writer.WriteAsync(_quoteChar, cancellationToken).ConfigureAwait(false); await _writer.WriteAsync(value.ToString(null, CultureInfo.InvariantCulture), cancellationToken).ConfigureAwait(false); await _writer.WriteAsync(_quoteChar, cancellationToken).ConfigureAwait(false); } /// <summary> /// Asynchronously writes a <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteValueAsync(TimeSpan? value, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteValueAsync(value, cancellationToken) : base.WriteValueAsync(value, cancellationToken); } internal Task DoWriteValueAsync(TimeSpan? value, CancellationToken cancellationToken) { return value == null ? DoWriteNullAsync(cancellationToken) : DoWriteValueAsync(value.GetValueOrDefault(), cancellationToken); } /// <summary> /// Asynchronously writes a <see cref="uint"/> value. /// </summary> /// <param name="value">The <see cref="uint"/> value to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> [CLSCompliant(false)] public override Task WriteValueAsync(uint value, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? WriteIntegerValueAsync(value, cancellationToken) : base.WriteValueAsync(value, cancellationToken); } /// <summary> /// Asynchronously writes a <see cref="Nullable{T}"/> of <see cref="uint"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="uint"/> value to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> [CLSCompliant(false)] public override Task WriteValueAsync(uint? value, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteValueAsync(value, cancellationToken) : base.WriteValueAsync(value, cancellationToken); } internal Task DoWriteValueAsync(uint? value, CancellationToken cancellationToken) { return value == null ? DoWriteNullAsync(cancellationToken) : WriteIntegerValueAsync(value.GetValueOrDefault(), cancellationToken); } /// <summary> /// Asynchronously writes a <see cref="ulong"/> value. /// </summary> /// <param name="value">The <see cref="ulong"/> value to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> [CLSCompliant(false)] public override Task WriteValueAsync(ulong value, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? WriteIntegerValueAsync(value, cancellationToken) : base.WriteValueAsync(value, cancellationToken); } /// <summary> /// Asynchronously writes a <see cref="Nullable{T}"/> of <see cref="ulong"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="ulong"/> value to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> [CLSCompliant(false)] public override Task WriteValueAsync(ulong? value, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteValueAsync(value, cancellationToken) : base.WriteValueAsync(value, cancellationToken); } internal Task DoWriteValueAsync(ulong? value, CancellationToken cancellationToken) { return value == null ? DoWriteNullAsync(cancellationToken) : WriteIntegerValueAsync(value.GetValueOrDefault(), cancellationToken); } /// <summary> /// Asynchronously writes a <see cref="Uri"/> value. /// </summary> /// <param name="value">The <see cref="Uri"/> value to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteValueAsync(Uri value, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? (value == null ? WriteNullAsync(cancellationToken) : WriteValueNotNullAsync(value, cancellationToken)) : base.WriteValueAsync(value, cancellationToken); } internal Task WriteValueNotNullAsync(Uri value, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.String, cancellationToken); if (task.Status == TaskStatus.RanToCompletion) { return WriteEscapedStringAsync(value.OriginalString, true, cancellationToken); } return WriteValueNotNullAsync(task, value, cancellationToken); } internal async Task WriteValueNotNullAsync(Task task, Uri value, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await WriteEscapedStringAsync(value.OriginalString, true, cancellationToken).ConfigureAwait(false); } /// <summary> /// Asynchronously writes a <see cref="ushort"/> value. /// </summary> /// <param name="value">The <see cref="ushort"/> value to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> [CLSCompliant(false)] public override Task WriteValueAsync(ushort value, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? WriteIntegerValueAsync(value, cancellationToken) : base.WriteValueAsync(value, cancellationToken); } /// <summary> /// Asynchronously writes a <see cref="Nullable{T}"/> of <see cref="ushort"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="ushort"/> value to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> [CLSCompliant(false)] public override Task WriteValueAsync(ushort? value, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteValueAsync(value, cancellationToken) : base.WriteValueAsync(value, cancellationToken); } internal Task DoWriteValueAsync(ushort? value, CancellationToken cancellationToken) { return value == null ? DoWriteNullAsync(cancellationToken) : WriteIntegerValueAsync(value.GetValueOrDefault(), cancellationToken); } /// <summary> /// Asynchronously writes a comment <c>/*...*/</c> containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteCommentAsync(string text, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteCommentAsync(text, cancellationToken) : base.WriteCommentAsync(text, cancellationToken); } internal async Task DoWriteCommentAsync(string text, CancellationToken cancellationToken) { await InternalWriteCommentAsync(cancellationToken).ConfigureAwait(false); await _writer.WriteAsync("/*", cancellationToken).ConfigureAwait(false); await _writer.WriteAsync(text, cancellationToken).ConfigureAwait(false); await _writer.WriteAsync("*/", cancellationToken).ConfigureAwait(false); } /// <summary> /// Asynchronously writes the end of an array. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteEndArrayAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? InternalWriteEndAsync(JsonContainerType.Array, cancellationToken) : base.WriteEndArrayAsync(cancellationToken); } /// <summary> /// Asynchronously writes the end of a constructor. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteEndConstructorAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? InternalWriteEndAsync(JsonContainerType.Constructor, cancellationToken) : base.WriteEndConstructorAsync(cancellationToken); } /// <summary> /// Asynchronously writes the end of a JSON object. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteEndObjectAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? InternalWriteEndAsync(JsonContainerType.Object, cancellationToken) : base.WriteEndObjectAsync(cancellationToken); } /// <summary> /// Asynchronously writes raw JSON where a value is expected and updates the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task.</remarks> public override Task WriteRawValueAsync(string json, CancellationToken cancellationToken = default(CancellationToken)) { return _safeAsync ? DoWriteRawValueAsync(json, cancellationToken) : base.WriteRawValueAsync(json, cancellationToken); } internal Task DoWriteRawValueAsync(string json, CancellationToken cancellationToken) { UpdateScopeWithFinishedValue(); Task task = AutoCompleteAsync(JsonToken.Undefined, cancellationToken); if (task.Status == TaskStatus.RanToCompletion) { return WriteRawAsync(json, cancellationToken); } return DoWriteRawValueAsync(task, json, cancellationToken); } private async Task DoWriteRawValueAsync(Task task, string json, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await WriteRawAsync(json, cancellationToken).ConfigureAwait(false); } internal char[] EnsureWriteBuffer(int length, int copyTo) { if (length < 35) { length = 35; } char[] buffer = _writeBuffer; if (buffer == null) { return _writeBuffer = BufferUtils.RentBuffer(_arrayPool, length); } if (buffer.Length >= length) { return buffer; } char[] newBuffer = BufferUtils.RentBuffer(_arrayPool, length); if (copyTo != 0) { Array.Copy(buffer, newBuffer, copyTo); } BufferUtils.ReturnBuffer(_arrayPool, buffer); _writeBuffer = newBuffer; return newBuffer; } } } //#endif
// // Copyright 2012-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading; using System.Threading.Tasks; #if __UNIFIED__ using UIKit; using Foundation; using CoreAnimation; using CoreGraphics; using CGRect = global::System.Drawing.RectangleF; #else using MonoTouch.UIKit; using MonoTouch.Foundation; using MonoTouch.CoreAnimation; using MonoTouch.CoreGraphics; using System.Drawing; using CGRect = global::System.Drawing.RectangleF; using CGPoint = global::System.Drawing.PointF; using CGSize = global::System.Drawing.SizeF; using nfloat = global::System.Single; using nint = global::System.Int32; using nuint = global::System.UInt32; #endif using Xamarin.Auth; using Xamarin.Utilities.iOS; namespace Xamarin.Social { public class ShareViewController : UIViewController { Service service; Item item; List<Account> accounts = new List<Account>(); Action<ShareResult> completionHandler; Task<IEnumerable<Account>> futureAccounts; UITextView textEditor; ProgressLabel progress; TextLengthLabel textLengthLabel; UILabel linksLabel; ChoiceField accountField = null; bool sharing = false; bool canceledFromOutside = false; UIAlertView accountsAlert; static UIFont TextEditorFont = UIFont.SystemFontOfSize (18); static readonly UIColor FieldColor = UIColor.FromRGB (56, 84, 135); internal ShareViewController (Service service, Item item, Action<ShareResult> completionHandler) { this.service = service; this.item = item; this.completionHandler = completionHandler; Title = NSBundle.MainBundle.LocalizedString (service.ShareTitle, "Title of Share dialog"); View.BackgroundColor = UIColor.White; if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) EdgesForExtendedLayout = UIRectEdge.None; futureAccounts = service.GetAccountsAsync (); } public override void ViewDidLoad() { BuildUI(); base.ViewDidLoad(); } public override void ViewDidAppear (bool animated) { base.ViewDidAppear (animated); var fa = Interlocked.Exchange (ref futureAccounts, null); if (fa != null) { fa.ContinueWith (t => { accounts.AddRange (t.Result); foreach (string username in accounts.Select (a => a.Username)) accountField.Items.Add (username); CheckForAccounts(); }, TaskScheduler.FromCurrentSynchronizationContext()); } else if (canceledFromOutside) canceledFromOutside = false; else CheckForAccounts(); } void CheckForAccounts () { if (accounts.Count == 0) { var title = "No " + service.Title + " Accounts"; var msg = "There are no configured " + service.Title + " accounts. " + "Would you like to add one?"; accountsAlert = new UIAlertView ( title, msg, null, "Cancel", "Add Account"); accountsAlert.Clicked += (sender, e) => { if (e.ButtonIndex == 1) { Authenticate (); } else { completionHandler (ShareResult.Cancelled); } }; accountsAlert.Show (); } else { textEditor.BecomeFirstResponder (); } } void Authenticate () { var vc = service.GetAuthenticateUI (account => { if (account != null) accounts.Add (account); else canceledFromOutside = true; DismissViewController (true, () => { if (account != null) { accountField.Items.Add (account.Username); textEditor.BecomeFirstResponder (); } else { completionHandler (ShareResult.Cancelled); } }); }); vc.ModalTransitionStyle = UIModalTransitionStyle.FlipHorizontal; PresentViewController (vc, true, null); } void BuildUI () { var b = View.Bounds; var statusHeight = 22.0f; // // Account Field // var fieldHeight = 33; accountField = new ChoiceField ( #if ! __UNIFIED__ new RectangleF (0, b.Y, b.Width, 33), #else new RectangleF (0, (float)b.Y, (float)b.Width, 33), #endif this, NSBundle.MainBundle.LocalizedString ("From", "From title when sharing")); View.AddSubview (accountField); b.Y += fieldHeight; b.Height -= fieldHeight; // // Text Editor // var editorHeight = b.Height; if (service.HasMaxTextLength || item.Links.Count > 0) { editorHeight -= statusHeight; } textEditor = new UITextView ( #if ! __UNIFIED__ new RectangleF (0, b.Y, b.Width, editorHeight)) #else new RectangleF (0, (float) b.Y, (float) b.Width, (float)editorHeight)) #endif { Font = TextEditorFont, AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight, Text = item.Text, }; textEditor.Delegate = new TextEditorDelegate (this); View.AddSubview (textEditor); // // Icons // if (item.Images.Count > 0) { var rem = 4.0f; RectangleF f; var x = b.Right - AttachmentIcon.Size - 8 - rem*(item.Images.Count - 1); var y = textEditor.Frame.Y + 8; #if ! __UNIFIED__ f = textEditor.Frame; f.Width = x - 8 - f.X; #else f = (RectangleF)textEditor.Frame; f.Width = (float)x - 8 - f.X; #endif textEditor.Frame = f; foreach (var i in item.Images) { var icon = new ImageIcon (i.Image); #if ! __UNIFIED__ f = icon.Frame; f.X = x; f.Y = y; #else f = (RectangleF) icon.Frame; f.X = (float)x; f.Y = (float)y; #endif icon.Frame = f; View.AddSubview (icon); x += rem; y += rem; } } // // Remaining Text Length // if (service.HasMaxTextLength) { textLengthLabel = new TextLengthLabel ( #if ! __UNIFIED__ new RectangleF (4, b.Bottom - statusHeight, textEditor.Frame.Width - 8, statusHeight), #else new RectangleF (4, (float)(b.Bottom - statusHeight), (float)(textEditor.Frame.Width - 8), statusHeight), #endif service.MaxTextLength) { TextLength = service.GetTextLength (item), }; View.AddSubview (textLengthLabel); } // // Links Label // if (item.Links.Count > 0) { linksLabel = new UILabel ( #if ! __UNIFIED__ new RectangleF (4, b.Bottom - statusHeight, textEditor.Frame.Width - 66, statusHeight)) { #else new RectangleF (4, (float)(b.Bottom - statusHeight), (float)(textEditor.Frame.Width - 66), statusHeight)) { #endif TextColor = UIColor.FromRGB (124, 124, 124), AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleWidth, UserInteractionEnabled = false, BackgroundColor = UIColor.Clear, Font = UIFont.SystemFontOfSize (16), LineBreakMode = UILineBreakMode.HeadTruncation, }; if (item.Links.Count == 1) { linksLabel.Text = item.Links[0].AbsoluteUri; } else { linksLabel.Text = string.Format ( NSBundle.MainBundle.LocalizedString ("{0} links", "# of links label"), item.Links.Count); } View.AddSubview (linksLabel); } // // Navigation Items // NavigationItem.LeftBarButtonItem = new UIBarButtonItem ( UIBarButtonSystemItem.Cancel, delegate { completionHandler (ShareResult.Cancelled); }); NavigationItem.RightBarButtonItem = new UIBarButtonItem ( NSBundle.MainBundle.LocalizedString ("Send", "Send button text when sharing"), UIBarButtonItemStyle.Done, HandleSend); // // Watch for the keyboard // NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.DidShowNotification, HandleKeyboardDidShow); NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification, HandleKeyboardDidHide); } void HandleSend (object sender, EventArgs e) { if (sharing) return; item.Text = textEditor.Text; StartSharing (); var account = accounts.FirstOrDefault (); if (accounts.Count > 1 && accountField != null) { account = accounts.FirstOrDefault (x => x.Username == accountField.SelectedItem); } try { service.ShareItemAsync (item, account).ContinueWith (shareTask => { StopSharing (); if (shareTask.IsFaulted) { this.ShowError ("Share Error", shareTask.Exception); } else { completionHandler (ShareResult.Done); } }, TaskScheduler.FromCurrentSynchronizationContext ()); } catch (Exception ex) { StopSharing (); this.ShowError ("Share Error", ex); } } void StartSharing () { sharing = true; NavigationItem.RightBarButtonItem.Enabled = false; if (progress == null) { progress = new ProgressLabel (NSBundle.MainBundle.LocalizedString ("Sending...", "Sending... status message when sharing")); NavigationItem.TitleView = progress; progress.StartAnimating (); } } void StopSharing () { sharing = false; NavigationItem.RightBarButtonItem.Enabled = true; if (progress != null) { progress.StopAnimating (); NavigationItem.TitleView = null; progress = null; } } public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { return true; } void ResignFirstResponders () { textEditor.ResignFirstResponder (); } void HandleKeyboardDidShow (NSNotification n) { var size = UIKeyboard.BoundsFromNotification (n).Size; var f = textEditor.Frame; f.Height -= size.Height; textEditor.Frame = f; if (textLengthLabel != null) { f = textLengthLabel.Frame; f.Y -= size.Height; textLengthLabel.Frame = f; } if (linksLabel != null) { f = linksLabel.Frame; f.Y -= size.Height; linksLabel.Frame = f; } } void HandleKeyboardDidHide (NSNotification n) { var size = UIKeyboard.BoundsFromNotification (n).Size; UIView.BeginAnimations ("kbd"); var f = textEditor.Frame; f.Height += size.Height; textEditor.Frame = f; if (textLengthLabel != null) { f = textLengthLabel.Frame; f.Y += size.Height; textLengthLabel.Frame = f; } if (linksLabel != null) { f = linksLabel.Frame; f.Y += size.Height; linksLabel.Frame = f; } UIView.CommitAnimations (); } class TextEditorDelegate : UITextViewDelegate { ShareViewController controller; public TextEditorDelegate (ShareViewController controller) { this.controller = controller; } public override void Changed (UITextView textView) { controller.item.Text = textView.Text; if (controller.textLengthLabel != null) { controller.textLengthLabel.TextLength = controller.service.GetTextLength (controller.item); } } } class TextLengthLabel : UILabel { int maxLength; int textLength; static readonly UIColor okColor = UIColor.FromRGB (124, 124, 124); static readonly UIColor errorColor = UIColor.FromRGB (166, 80, 80); public int TextLength { get { return textLength; } set { textLength = value; Update (); } } public TextLengthLabel (RectangleF frame, int maxLength) : base (frame) { this.maxLength = maxLength; this.textLength = 0; UserInteractionEnabled = false; BackgroundColor = UIColor.Clear; AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin; TextAlignment = UITextAlignment.Right; Font = UIFont.BoldSystemFontOfSize (16); TextColor = okColor; } void Update () { var rem = maxLength - textLength; Text = rem.ToString (); if (rem < 0) { TextColor = errorColor; } else { TextColor = okColor; } } } abstract class AttachmentIcon : UIImageView { public static float Size { get { return 72; } } static readonly CGColor borderColor = new CGColor (0.75f, 0.75f, 0.75f); static readonly CGColor shadowColor = new CGColor (0.25f, 0.25f, 0.25f); public AttachmentIcon () : base (new RectangleF (0, 0, Size, Size)) { ContentMode = UIViewContentMode.ScaleAspectFill; ClipsToBounds = true; AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin; Layer.CornerRadius = 4; Layer.ShadowOffset = new SizeF (0, 0); Layer.ShadowColor = shadowColor; Layer.ShadowRadius = 4; Layer.ShadowOpacity = 1.0f; Layer.BorderColor = borderColor; Layer.BorderWidth = 1; } } class ImageIcon : AttachmentIcon { public ImageIcon (UIImage image) { Image = image; } } abstract class Field : UIView { public ShareViewController Controller { get; private set; } public UILabel TitleLabel { get; private set; } public Field (RectangleF frame, ShareViewController controller, string title) : base (frame) { Controller = controller; BackgroundColor = UIColor.White; Opaque = true; AutoresizingMask = UIViewAutoresizing.FlexibleWidth; TitleLabel = new UILabel () { BackgroundColor = UIColor.White, Font = TextEditorFont, Text = title + ":", TextColor = UIColor.Gray, }; #if ! __UNIFIED__ TitleLabel.Frame = new RectangleF (8, 0, frame.Width, frame.Height - 1); #else TitleLabel.Frame = new RectangleF (8, 0, (float)frame.Width, frame.Height - 1); #endif AddSubview (TitleLabel); } #if ! __UNIFIED__ public override void Draw (RectangleF rect) #else public void Draw (RectangleF rect) #endif { var b = Bounds; using (var c = UIGraphics.GetCurrentContext ()) { UIColor.LightGray.SetStroke (); c.SetLineWidth (1.0f); c.MoveTo (0, b.Bottom); c.AddLineToPoint (b.Right, b.Bottom); c.StrokePath (); } } } class ChoiceField : Field { public string SelectedItem { get { return Picker.SelectedItem; } } public LabelButton ValueLabel { get; private set; } public CheckedPickerView Picker { get; private set; } public IList<string> Items { get { return Picker.Items; } set { Picker.Items = value; } } public ChoiceField (RectangleF frame, ShareViewController controller, string title) : base (frame, controller, title) { ValueLabel = new LabelButton () { BackgroundColor = UIColor.Clear, Font = TextEditorFont, TextColor = UIColor.DarkTextColor, TextAlignment = UITextAlignment.Right, AutoresizingMask = UIViewAutoresizing.FlexibleWidth, }; var tf = TitleLabel.Frame; #if ! __UNIFIED__ ValueLabel.Frame = new RectangleF (tf.Right, 0, frame.Width - tf.Right, frame.Height - 1); #else // ValueLabel.Frame = new RectangleF ((float)tf.Right, 0, (float)((nfloat)frame.Width - tf.Right), (float)(frame.Height - 1)); ValueLabel.Frame = new RectangleF (0, 0, (float)((nfloat)frame.Width - tf.Left), (float)(frame.Height - 1)); #endif ValueLabel.TouchUpInside += HandleTouchUpInside; AddSubview (ValueLabel); Picker = new CheckedPickerView (new RectangleF (0, 0, 320, 216)); Picker.Hidden = true; Picker.SelectedItemChanged += delegate { ValueLabel.Text = Picker.SelectedItem; }; controller.View.AddSubview (Picker); ValueLabel.Text = Picker.SelectedItem; } private UIAlertController accountActionView; private void DeleteCurrentAccount() { var account = Controller.accounts.FirstOrDefault (x => x.Username == ValueLabel.Text); Controller.service.DeleteAccount(account); accountActionView.DismissViewController (true, null); Controller.DismissViewController (true, null); } void ChangeCurrentAccount() { if (Items.Count > 1) { Controller.ResignFirstResponders (); var v = Controller.View; Picker.Hidden = false; #if ! __UNIFIED__ Picker.Frame = new RectangleF (0, v.Bounds.Bottom - 216, 320, 216); #else Picker.Frame = new RectangleF (0, (float)(v.Bounds.Bottom - 216), 320, 216); #endif v.BringSubviewToFront (Picker); } } void HandleTouchUpInside (object sender, EventArgs e) { accountActionView = UIAlertController.Create (null, null, UIAlertControllerStyle.ActionSheet); accountActionView.AddAction(UIAlertAction.Create("Change Account", UIAlertActionStyle.Default, a => ChangeCurrentAccount() )); accountActionView.AddAction(UIAlertAction.Create("Delete Account", UIAlertActionStyle.Destructive, a => DeleteCurrentAccount() )); accountActionView.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null )); Controller.PresentViewController (accountActionView, true, null); } } class LabelButton : UILabel { public event EventHandler TouchUpInside; public LabelButton () { UserInteractionEnabled = true; } public override void TouchesBegan (NSSet touches, UIEvent evt) { TextColor = FieldColor; } public override void TouchesEnded (NSSet touches, UIEvent evt) { TextColor = UIColor.DarkTextColor; var t = touches.ToArray<UITouch> ().First (); if (Bounds.Contains (t.LocationInView (this))) { var ev = TouchUpInside; if (ev != null) { ev (this, EventArgs.Empty); } } } public override void TouchesCancelled (NSSet touches, UIEvent evt) { TextColor = UIColor.DarkTextColor; } } } }
/* * 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 autoscaling-2011-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.AutoScaling.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.AutoScaling.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for AutoScalingGroup Object /// </summary> public class AutoScalingGroupUnmarshaller : IUnmarshaller<AutoScalingGroup, XmlUnmarshallerContext>, IUnmarshaller<AutoScalingGroup, JsonUnmarshallerContext> { public AutoScalingGroup Unmarshall(XmlUnmarshallerContext context) { AutoScalingGroup unmarshalledObject = new AutoScalingGroup(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("AutoScalingGroupARN", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.AutoScalingGroupARN = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("AutoScalingGroupName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.AutoScalingGroupName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("AvailabilityZones/member", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.AvailabilityZones.Add(item); continue; } if (context.TestExpression("CreatedTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.CreatedTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DefaultCooldown", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.DefaultCooldown = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DesiredCapacity", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.DesiredCapacity = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("EnabledMetrics/member", targetDepth)) { var unmarshaller = EnabledMetricUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.EnabledMetrics.Add(item); continue; } if (context.TestExpression("HealthCheckGracePeriod", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.HealthCheckGracePeriod = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("HealthCheckType", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.HealthCheckType = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Instances/member", targetDepth)) { var unmarshaller = InstanceUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.Instances.Add(item); continue; } if (context.TestExpression("LaunchConfigurationName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.LaunchConfigurationName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LoadBalancerNames/member", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.LoadBalancerNames.Add(item); continue; } if (context.TestExpression("MaxSize", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.MaxSize = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("MinSize", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.MinSize = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("PlacementGroup", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.PlacementGroup = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Status", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Status = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SuspendedProcesses/member", targetDepth)) { var unmarshaller = SuspendedProcessUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.SuspendedProcesses.Add(item); continue; } if (context.TestExpression("Tags/member", targetDepth)) { var unmarshaller = TagDescriptionUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.Tags.Add(item); continue; } if (context.TestExpression("TerminationPolicies/member", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); unmarshalledObject.TerminationPolicies.Add(item); continue; } if (context.TestExpression("VPCZoneIdentifier", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.VPCZoneIdentifier = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } public AutoScalingGroup Unmarshall(JsonUnmarshallerContext context) { return null; } private static AutoScalingGroupUnmarshaller _instance = new AutoScalingGroupUnmarshaller(); public static AutoScalingGroupUnmarshaller Instance { get { return _instance; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using Term = Lucene.Net.Index.Term; using BooleanClause = Lucene.Net.Search.BooleanClause; using BooleanQuery = Lucene.Net.Search.BooleanQuery; using Hits = Lucene.Net.Search.Hits; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using Query = Lucene.Net.Search.Query; using TermQuery = Lucene.Net.Search.TermQuery; using Directory = Lucene.Net.Store.Directory; using SpellChecker.Net.Search.Spell; using Lucene.Net.Store; using Lucene.Net.Search; namespace SpellChecker.Net.Search.Spell { /// <summary> <p> /// Spell Checker class (Main class) <br/> /// (initially inspired by the David Spencer code). /// </p> /// /// <p>Example Usage: /// /// <pre> /// SpellChecker spellchecker = new SpellChecker(spellIndexDirectory); /// // To index a field of a user index: /// spellchecker.indexDictionary(new LuceneDictionary(my_lucene_reader, a_field)); /// // To index a file containing words: /// spellchecker.indexDictionary(new PlainTextDictionary(new File("myfile.txt"))); /// String[] suggestions = spellchecker.suggestSimilar("misspelt", 5); /// </pre> /// /// </summary> /// <author> Nicolas Maisonneuve /// </author> /// <version> 1.0 /// </version> public class SpellChecker { /// <summary> Field name for each word in the ngram index.</summary> public const System.String F_WORD = "word"; private readonly Term F_WORD_TERM = new Term(F_WORD); /// <summary> the spell index</summary> internal Directory spellindex; /// <summary> Boost value for start and end grams</summary> private float bStart = 2.0f; private float bEnd = 1.0f; //private IndexReader reader; // don't use this searcher directly - see #swapSearcher() private IndexSearcher searcher; /// <summary> /// this locks all modifications to the current searcher. /// </summary> private static System.Object searcherLock = new System.Object(); /* * this lock synchronizes all possible modifications to the * current index directory. It should not be possible to try modifying * the same index concurrently. Note: Do not acquire the searcher lock * before acquiring this lock! */ private static System.Object modifyCurrentIndexLock = new System.Object(); private volatile bool closed = false; internal float minScore = 0.5f; //LUCENENET-359 Spellchecker accuracy gets overwritten private StringDistance sd; /// <summary> /// Use the given directory as a spell checker index. The directory /// is created if it doesn't exist yet. /// </summary> /// <param name="gramIndex">the spell index directory</param> /// <param name="sd">the {@link StringDistance} measurement to use </param> public SpellChecker(Directory gramIndex, StringDistance sd) { this.SetSpellIndex(gramIndex); this.setStringDistance(sd); } /// <summary> /// Use the given directory as a spell checker index with a /// {@link LevensteinDistance} as the default {@link StringDistance}. The /// directory is created if it doesn't exist yet. /// </summary> /// <param name="gramIndex">the spell index directory</param> public SpellChecker(Directory gramIndex) : this(gramIndex, new LevenshteinDistance()) { } /// <summary> /// Use a different index as the spell checker index or re-open /// the existing index if <code>spellIndex</code> is the same value /// as given in the constructor. /// </summary> /// <param name="spellIndexDir">spellIndexDir the spell directory to use </param> /// <throws>AlreadyClosedException if the Spellchecker is already closed</throws> /// <throws>IOException if spellchecker can not open the directory</throws> virtual public void SetSpellIndex(Directory spellIndexDir) { // this could be the same directory as the current spellIndex // modifications to the directory should be synchronized lock (modifyCurrentIndexLock) { EnsureOpen(); if (!IndexReader.IndexExists(spellIndexDir)) { IndexWriter writer = new IndexWriter(spellIndexDir, null, true, IndexWriter.MaxFieldLength.UNLIMITED); writer.Close(); } SwapSearcher(spellIndexDir); } } /// <summary> /// Sets the {@link StringDistance} implementation for this /// {@link SpellChecker} instance. /// </summary> /// <param name="sd">the {@link StringDistance} implementation for this /// {@link SpellChecker} instance.</param> public void setStringDistance(StringDistance sd) { this.sd = sd; } /// <summary> /// Returns the {@link StringDistance} instance used by this /// {@link SpellChecker} instance. /// </summary> /// <returns> /// Returns the {@link StringDistance} instance used by this /// {@link SpellChecker} instance. /// </returns> public StringDistance GetStringDistance() { return sd; } /// <summary> Set the accuracy 0 &lt; min &lt; 1; default 0.5</summary> virtual public void SetAccuracy(float minScore) { this.minScore = minScore; } /// <summary> Suggest similar words</summary> /// <param name="word">String the word you want a spell check done on /// </param> /// <param name="num_sug">int the number of suggest words /// </param> /// <throws> IOException </throws> /// <returns> String[] /// </returns> public virtual System.String[] SuggestSimilar(System.String word, int num_sug) { return this.SuggestSimilar(word, num_sug, null, null, false); } /// <summary> Suggest similar words (restricted or not to a field of a user index)</summary> /// <param name="word">String the word you want a spell check done on /// </param> /// <param name="numSug">int the number of suggest words /// </param> /// <param name="ir">the indexReader of the user index (can be null see field param) /// </param> /// <param name="field">String the field of the user index: if field is not null, the suggested /// words are restricted to the words present in this field. /// </param> /// <param name="morePopular">boolean return only the suggest words that are more frequent than the searched word /// (only if restricted mode = (indexReader!=null and field!=null) /// </param> /// <throws> IOException </throws> /// <returns> String[] the sorted list of the suggest words with this 2 criteria: /// first criteria: the edit distance, second criteria (only if restricted mode): the popularity /// of the suggest words in the field of the user index /// </returns> public virtual System.String[] SuggestSimilar(System.String word, int numSug, IndexReader ir, System.String field, bool morePopular) { // obtainSearcher calls ensureOpen IndexSearcher indexSearcher = ObtainSearcher(); try { float min = this.minScore; int lengthWord = word.Length; int freq = (ir != null && field != null) ? ir.DocFreq(new Term(field, word)) : 0; int goalFreq = (morePopular && ir != null && field != null) ? freq : 0; // if the word exists in the real index and we don't care for word frequency, return the word itself if (!morePopular && freq > 0) { return new String[] { word }; } BooleanQuery query = new BooleanQuery(); String[] grams; String key; for (int ng = GetMin(lengthWord); ng <= GetMax(lengthWord); ng++) { key = "gram" + ng; // form key grams = FormGrams(word, ng); // form word into ngrams (allow dups too) if (grams.Length == 0) { continue; // hmm } if (bStart > 0) { // should we boost prefixes? Add(query, "start" + ng, grams[0], bStart); // matches start of word } if (bEnd > 0) { // should we boost suffixes Add(query, "end" + ng, grams[grams.Length - 1], bEnd); // matches end of word } for (int i = 0; i < grams.Length; i++) { Add(query, key, grams[i]); } } int maxHits = 10 * numSug; // System.out.println("Q: " + query); ScoreDoc[] hits = indexSearcher.Search(query, null, maxHits).scoreDocs; // System.out.println("HITS: " + hits.length()); SuggestWordQueue sugQueue = new SuggestWordQueue(numSug); // go thru more than 'maxr' matches in case the distance filter triggers int stop = Math.Min(hits.Length, maxHits); SuggestWord sugWord = new SuggestWord(); for (int i = 0; i < stop; i++) { sugWord.string_Renamed = indexSearcher.Doc(hits[i].doc).Get(F_WORD); // get orig word // don't suggest a word for itself, that would be silly if (sugWord.string_Renamed.Equals(word)) { continue; } // edit distance sugWord.score = sd.GetDistance(word, sugWord.string_Renamed); if (sugWord.score < min) { continue; } if (ir != null && field != null) { // use the user index sugWord.freq = ir.DocFreq(new Term(field, sugWord.string_Renamed)); // freq in the index // don't suggest a word that is not present in the field if ((morePopular && goalFreq > sugWord.freq) || sugWord.freq < 1) { continue; } } sugQueue.InsertWithOverflow(sugWord); if (sugQueue.Size() == numSug) { // if queue full, maintain the minScore score min = ((SuggestWord)sugQueue.Top()).score; } sugWord = new SuggestWord(); } // convert to array string String[] list = new String[sugQueue.Size()]; for (int i = sugQueue.Size() - 1; i >= 0; i--) { list[i] = ((SuggestWord)sugQueue.Pop()).string_Renamed; } return list; } finally { ReleaseSearcher(indexSearcher); } } /// <summary> Add a clause to a boolean query.</summary> private static void Add(BooleanQuery q, System.String k, System.String v, float boost) { Query tq = new TermQuery(new Term(k, v)); tq.SetBoost(boost); q.Add(new BooleanClause(tq, BooleanClause.Occur.SHOULD)); } /// <summary> Add a clause to a boolean query.</summary> private static void Add(BooleanQuery q, System.String k, System.String v) { q.Add(new BooleanClause(new TermQuery(new Term(k, v)), BooleanClause.Occur.SHOULD)); } /// <summary> Form all ngrams for a given word.</summary> /// <param name="text">the word to parse /// </param> /// <param name="ng">the ngram length e.g. 3 /// </param> /// <returns> an array of all ngrams in the word and note that duplicates are not removed /// </returns> private static System.String[] FormGrams(System.String text, int ng) { int len = text.Length; System.String[] res = new System.String[len - ng + 1]; for (int i = 0; i < len - ng + 1; i++) { res[i] = text.Substring(i, (i + ng) - (i)); } return res; } /// <summary> /// Removes all terms from the spell check index. /// </summary> public virtual void ClearIndex() { lock (modifyCurrentIndexLock) { EnsureOpen(); Directory dir = this.spellindex; IndexWriter writer = new IndexWriter(dir, null, true, IndexWriter.MaxFieldLength.UNLIMITED); writer.Close(); SwapSearcher(dir); } } /// <summary> Check whether the word exists in the index.</summary> /// <param name="word">String /// </param> /// <throws> IOException </throws> /// <returns> true iff the word exists in the index /// </returns> public virtual bool Exist(System.String word) { // obtainSearcher calls ensureOpen IndexSearcher indexSearcher = ObtainSearcher(); try { return indexSearcher.DocFreq(F_WORD_TERM.CreateTerm(word)) > 0; } finally { ReleaseSearcher(indexSearcher); } } /// <summary> Index a Dictionary</summary> /// <param name="dict">the dictionary to index</param> /// <param name="mergeFactor">mergeFactor to use when indexing</param> /// <param name="ramMB">the max amount or memory in MB to use</param> /// <throws> IOException </throws> /// <throws>AlreadyClosedException if the Spellchecker is already closed</throws> public virtual void IndexDictionary(Dictionary dict, int mergeFactor, int ramMB) { lock (modifyCurrentIndexLock) { EnsureOpen(); Directory dir = this.spellindex; IndexWriter writer = new IndexWriter(spellindex, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED); writer.SetMergeFactor(mergeFactor); writer.SetMaxBufferedDocs(ramMB); System.Collections.IEnumerator iter = dict.GetWordsIterator(); while (iter.MoveNext()) { System.String word = (System.String)iter.Current; int len = word.Length; if (len < 3) { continue; // too short we bail but "too long" is fine... } if (this.Exist(word)) { // if the word already exist in the gramindex continue; } // ok index the word Document doc = CreateDocument(word, GetMin(len), GetMax(len)); writer.AddDocument(doc); } // close writer writer.Optimize(); writer.Close(); // also re-open the spell index to see our own changes when the next suggestion // is fetched: SwapSearcher(dir); } } /// <summary> /// Indexes the data from the given {@link Dictionary}. /// </summary> /// <param name="dict">dict the dictionary to index</param> public void IndexDictionary(Dictionary dict) { IndexDictionary(dict, 300, 10); } private int GetMin(int l) { if (l > 5) { return 3; } if (l == 5) { return 2; } return 1; } private int GetMax(int l) { if (l > 5) { return 4; } if (l == 5) { return 3; } return 2; } private static Document CreateDocument(System.String text, int ng1, int ng2) { Document doc = new Document(); doc.Add(new Field(F_WORD, text, Field.Store.YES, Field.Index.NOT_ANALYZED)); // orig term AddGram(text, doc, ng1, ng2); return doc; } private static void AddGram(System.String text, Document doc, int ng1, int ng2) { int len = text.Length; for (int ng = ng1; ng <= ng2; ng++) { System.String key = "gram" + ng; System.String end = null; for (int i = 0; i < len - ng + 1; i++) { System.String gram = text.Substring(i, (i + ng) - (i)); doc.Add(new Field(key, gram, Field.Store.NO, Field.Index.NOT_ANALYZED)); if (i == 0) { doc.Add(new Field("start" + ng, gram, Field.Store.NO, Field.Index.NOT_ANALYZED)); } end = gram; } if (end != null) { // may not be present if len==ng1 doc.Add(new Field("end" + ng, end, Field.Store.NO, Field.Index.NOT_ANALYZED)); } } } private IndexSearcher ObtainSearcher() { lock (searcherLock) { EnsureOpen(); searcher.GetIndexReader().IncRef(); return searcher; } } private void ReleaseSearcher(IndexSearcher aSearcher) { // don't check if open - always decRef // don't decrement the private searcher - could have been swapped aSearcher.GetIndexReader().DecRef(); } private void EnsureOpen() { if (closed) { throw new AlreadyClosedException("Spellchecker has been closed"); } } public void Close() { lock (searcherLock) { EnsureOpen(); closed = true; if (searcher != null) { searcher.Close(); } searcher = null; } } private void SwapSearcher(Directory dir) { /* * opening a searcher is possibly very expensive. * We rather close it again if the Spellchecker was closed during * this operation than block access to the current searcher while opening. */ IndexSearcher indexSearcher = CreateSearcher(dir); lock (searcherLock) { if (closed) { indexSearcher.Close(); throw new AlreadyClosedException("Spellchecker has been closed"); } if (searcher != null) { searcher.Close(); } // set the spellindex in the sync block - ensure consistency. searcher = indexSearcher; this.spellindex = dir; } } /// <summary> /// Creates a new read-only IndexSearcher (for testing purposes) /// </summary> /// <param name="dir">dir the directory used to open the searcher</param> /// <returns>a new read-only IndexSearcher. (throws IOException f there is a low-level IO error)</returns> public virtual IndexSearcher CreateSearcher(Directory dir) { return new IndexSearcher(dir, true); } /// <summary> /// Returns <code>true</code> if and only if the {@link SpellChecker} is /// closed, otherwise <code>false</code>. /// </summary> /// <returns><code>true</code> if and only if the {@link SpellChecker} is /// closed, otherwise <code>false</code>. ///</returns> bool IsClosed() { return closed; } ~SpellChecker() { this.Close(); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using QuantConnect.Data; using QuantConnect.Lean.Engine.DataFeeds.Transport; using QuantConnect.Util; namespace QuantConnect.Lean.Engine.DataFeeds { /// <summary> /// Provides an implementations of <see cref="ISubscriptionFactory"/> that uses the /// <see cref="BaseData.Reader(QuantConnect.Data.SubscriptionDataConfig,string,System.DateTime,bool)"/> /// method to read lines of text from a <see cref="SubscriptionDataSource"/> /// </summary> public class BaseDataSubscriptionFactory : ISubscriptionFactory { private readonly bool _isLiveMode; private readonly BaseData _factory; private readonly DateTime _date; private readonly SubscriptionDataConfig _config; /// <summary> /// Event fired when the specified source is considered invalid, this may /// be from a missing file or failure to download a remote source /// </summary> public event EventHandler<InvalidSourceEventArgs> InvalidSource; /// <summary> /// Event fired when an exception is thrown during a call to /// <see cref="BaseData.Reader(QuantConnect.Data.SubscriptionDataConfig,string,System.DateTime,bool)"/> /// </summary> public event EventHandler<ReaderErrorEventArgs> ReaderError; /// <summary> /// Event fired when there's an error creating an <see cref="IStreamReader"/> or the /// instantiated <see cref="IStreamReader"/> has no data. /// </summary> public event EventHandler<CreateStreamReaderErrorEventArgs> CreateStreamReaderError; /// <summary> /// Initializes a new instance of the <see cref="BaseDataSubscriptionFactory"/> class /// </summary> /// <param name="config">The subscription's configuration</param> /// <param name="date">The date this factory was produced to read data for</param> /// <param name="isLiveMode">True if we're in live mode, false for backtesting</param> public BaseDataSubscriptionFactory(SubscriptionDataConfig config, DateTime date, bool isLiveMode) { _date = date; _config = config; _isLiveMode = isLiveMode; _factory = (BaseData) ObjectActivator.GetActivator(config.Type).Invoke(new object[0]); } /// <summary> /// Reads the specified <paramref name="source"/> /// </summary> /// <param name="source">The source to be read</param> /// <returns>An <see cref="IEnumerable{BaseData}"/> that contains the data in the source</returns> public IEnumerable<BaseData> Read(SubscriptionDataSource source) { using (var reader = CreateStreamReader(source)) { // if the reader doesn't have data then we're done with this subscription if (reader == null || reader.EndOfStream) { OnCreateStreamReaderError(_date, source); yield break; } // while the reader has data while (!reader.EndOfStream) { // read a line and pass it to the base data factory var line = reader.ReadLine(); BaseData instance = null; try { instance = _factory.Reader(_config, line, _date, _isLiveMode); } catch (Exception err) { OnReaderError(line, err); } if (instance != null) { yield return instance; } } } } /// <summary> /// Creates a new <see cref="IStreamReader"/> for the specified <paramref name="subscriptionDataSource"/> /// </summary> /// <param name="subscriptionDataSource">The source to produce an <see cref="IStreamReader"/> for</param> /// <returns>A new instance of <see cref="IStreamReader"/> to read the source, or null if there was an error</returns> private IStreamReader CreateStreamReader(SubscriptionDataSource subscriptionDataSource) { IStreamReader reader; switch (subscriptionDataSource.TransportMedium) { case SubscriptionTransportMedium.LocalFile: reader = HandleLocalFileSource(subscriptionDataSource); break; case SubscriptionTransportMedium.RemoteFile: reader = HandleRemoteSourceFile(subscriptionDataSource); break; case SubscriptionTransportMedium.Rest: reader = new RestSubscriptionStreamReader(subscriptionDataSource.Source); break; default: throw new InvalidEnumArgumentException("Unexpected SubscriptionTransportMedium specified: " + subscriptionDataSource.TransportMedium); } return reader; } /// <summary> /// Event invocator for the <see cref="InvalidSource"/> event /// </summary> /// <param name="source">The <see cref="SubscriptionDataSource"/> that was invalid</param> /// <param name="exception">The exception if one was raised, otherwise null</param> private void OnInvalidSource(SubscriptionDataSource source, Exception exception) { var handler = InvalidSource; if (handler != null) handler(this, new InvalidSourceEventArgs(source, exception)); } /// <summary> /// Event invocator for the <see cref="ReaderError"/> event /// </summary> /// <param name="line">The line that caused the exception</param> /// <param name="exception">The exception that was caught</param> private void OnReaderError(string line, Exception exception) { var handler = ReaderError; if (handler != null) handler(this, new ReaderErrorEventArgs(line, exception)); } /// <summary> /// Event invocator for the <see cref="CreateStreamReaderError"/> event /// </summary> /// <param name="date">The date of the source</param> /// <param name="source">The source that caused the error</param> private void OnCreateStreamReaderError(DateTime date, SubscriptionDataSource source) { var handler = CreateStreamReaderError; if (handler != null) handler(this, new CreateStreamReaderErrorEventArgs(date, source)); } /// <summary> /// Opens up an IStreamReader for a local file source /// </summary> private IStreamReader HandleLocalFileSource(SubscriptionDataSource source) { if (!File.Exists(source.Source)) { OnInvalidSource(source, new FileNotFoundException("The specified file was not found", source.Source)); return null; } // handles zip or text files return new LocalFileSubscriptionStreamReader(source.Source); } /// <summary> /// Opens up an IStreamReader for a remote file source /// </summary> private IStreamReader HandleRemoteSourceFile(SubscriptionDataSource source) { // clean old files out of the cache if (!Directory.Exists(Constants.Cache)) Directory.CreateDirectory(Constants.Cache); foreach (var file in Directory.EnumerateFiles(Constants.Cache)) { if (File.GetCreationTime(file) < DateTime.Now.AddHours(-24)) File.Delete(file); } try { // this will fire up a web client in order to download the 'source' file to the cache return new RemoteFileSubscriptionStreamReader(source.Source, Constants.Cache); } catch (Exception err) { OnInvalidSource(source, err); return null; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.DataFeeds.Transport; using QuantConnect.Util; namespace QuantConnect.Lean.Engine.DataFeeds { /// <summary> /// Provides an implementations of <see cref="ISubscriptionDataSourceReader"/> that uses the /// <see cref="BaseData.Reader(QuantConnect.Data.SubscriptionDataConfig,string,System.DateTime,bool)"/> /// method to read lines of text from a <see cref="SubscriptionDataSource"/> /// </summary> public class TextSubscriptionDataSourceReader : ISubscriptionDataSourceReader { private readonly bool _isLiveMode; private readonly BaseData _factory; private readonly DateTime _date; private readonly SubscriptionDataConfig _config; private readonly IDataCacheProvider _dataCacheProvider; /// <summary> /// Event fired when the specified source is considered invalid, this may /// be from a missing file or failure to download a remote source /// </summary> public event EventHandler<InvalidSourceEventArgs> InvalidSource; /// <summary> /// Event fired when an exception is thrown during a call to /// <see cref="BaseData.Reader(QuantConnect.Data.SubscriptionDataConfig,string,System.DateTime,bool)"/> /// </summary> public event EventHandler<ReaderErrorEventArgs> ReaderError; /// <summary> /// Event fired when there's an error creating an <see cref="IStreamReader"/> or the /// instantiated <see cref="IStreamReader"/> has no data. /// </summary> public event EventHandler<CreateStreamReaderErrorEventArgs> CreateStreamReaderError; /// <summary> /// Initializes a new instance of the <see cref="TextSubscriptionDataSourceReader"/> class /// </summary> /// <param name="dataCacheProvider">This provider caches files if needed</param> /// <param name="config">The subscription's configuration</param> /// <param name="date">The date this factory was produced to read data for</param> /// <param name="isLiveMode">True if we're in live mode, false for backtesting</param> public TextSubscriptionDataSourceReader(IDataCacheProvider dataCacheProvider, SubscriptionDataConfig config, DateTime date, bool isLiveMode) { _dataCacheProvider = dataCacheProvider; _date = date; _config = config; _isLiveMode = isLiveMode; _factory = (BaseData) ObjectActivator.GetActivator(config.Type).Invoke(new object[] { config.Type }); } /// <summary> /// Reads the specified <paramref name="source"/> /// </summary> /// <param name="source">The source to be read</param> /// <returns>An <see cref="IEnumerable{BaseData}"/> that contains the data in the source</returns> public IEnumerable<BaseData> Read(SubscriptionDataSource source) { using (var reader = CreateStreamReader(source)) { // if the reader doesn't have data then we're done with this subscription if (reader == null || reader.EndOfStream) { OnCreateStreamReaderError(_date, source); yield break; } // while the reader has data while (!reader.EndOfStream) { // read a line and pass it to the base data factory var line = reader.ReadLine(); BaseData instance = null; try { instance = _factory.Reader(_config, line, _date, _isLiveMode); } catch (Exception err) { OnReaderError(line, err); } if (instance != null) { yield return instance; } } } } /// <summary> /// Creates a new <see cref="IStreamReader"/> for the specified <paramref name="subscriptionDataSource"/> /// </summary> /// <param name="subscriptionDataSource">The source to produce an <see cref="IStreamReader"/> for</param> /// <returns>A new instance of <see cref="IStreamReader"/> to read the source, or null if there was an error</returns> private IStreamReader CreateStreamReader(SubscriptionDataSource subscriptionDataSource) { IStreamReader reader; switch (subscriptionDataSource.TransportMedium) { case SubscriptionTransportMedium.LocalFile: reader = HandleLocalFileSource(subscriptionDataSource); break; case SubscriptionTransportMedium.RemoteFile: reader = HandleRemoteSourceFile(subscriptionDataSource); break; case SubscriptionTransportMedium.Rest: reader = new RestSubscriptionStreamReader(subscriptionDataSource.Source); break; default: throw new InvalidEnumArgumentException("Unexpected SubscriptionTransportMedium specified: " + subscriptionDataSource.TransportMedium); } return reader; } /// <summary> /// Event invocator for the <see cref="InvalidSource"/> event /// </summary> /// <param name="source">The <see cref="SubscriptionDataSource"/> that was invalid</param> /// <param name="exception">The exception if one was raised, otherwise null</param> private void OnInvalidSource(SubscriptionDataSource source, Exception exception) { var handler = InvalidSource; if (handler != null) handler(this, new InvalidSourceEventArgs(source, exception)); } /// <summary> /// Event invocator for the <see cref="ReaderError"/> event /// </summary> /// <param name="line">The line that caused the exception</param> /// <param name="exception">The exception that was caught</param> private void OnReaderError(string line, Exception exception) { var handler = ReaderError; if (handler != null) handler(this, new ReaderErrorEventArgs(line, exception)); } /// <summary> /// Event invocator for the <see cref="CreateStreamReaderError"/> event /// </summary> /// <param name="date">The date of the source</param> /// <param name="source">The source that caused the error</param> private void OnCreateStreamReaderError(DateTime date, SubscriptionDataSource source) { var handler = CreateStreamReaderError; if (handler != null) handler(this, new CreateStreamReaderErrorEventArgs(date, source)); } /// <summary> /// Opens up an IStreamReader for a local file source /// </summary> private IStreamReader HandleLocalFileSource(SubscriptionDataSource source) { // handles zip or text files return new LocalFileSubscriptionStreamReader(_dataCacheProvider, source.Source); } /// <summary> /// Opens up an IStreamReader for a remote file source /// </summary> private IStreamReader HandleRemoteSourceFile(SubscriptionDataSource source) { // clean old files out of the cache if (!Directory.Exists(Globals.Cache)) Directory.CreateDirectory(Globals.Cache); foreach (var file in Directory.EnumerateFiles(Globals.Cache)) { if (File.GetCreationTime(file) < DateTime.Now.AddHours(-24)) File.Delete(file); } try { // this will fire up a web client in order to download the 'source' file to the cache return new RemoteFileSubscriptionStreamReader(_dataCacheProvider, source.Source, Globals.Cache); } catch (Exception err) { OnInvalidSource(source, err); return null; } } } }
#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; using System.Collections.Generic; using System.Threading; using SoftLogik.Miscellaneous; namespace SoftLogik.Collections { public class ListWrapper<T> : IList<T>, IList { private readonly IList _list; private readonly IList<T> _genericList; private object _syncRoot; public ListWrapper(IList list) { ValidationUtils.ArgumentNotNull(list, "list"); _list = list; } public ListWrapper(IList<T> list) { ValidationUtils.ArgumentNotNull(list, "list"); _genericList = list; } public int IndexOf(T item) { if (_genericList != null) return _genericList.IndexOf(item); return _list.IndexOf(item); } public void Insert(int index, T item) { if (_genericList != null) _genericList.Insert(index, item); _list.Insert(index, item); } public void RemoveAt(int index) { if (_genericList != null) _genericList.RemoveAt(index); _list.RemoveAt(index); } public T this[int index] { get { if (_genericList != null) return _genericList[index]; return (T)_list[index]; } set { if (_genericList != null) _genericList[index] = value; _list[index] = value; } } public void Add(T item) { if (_genericList != null) _genericList.Add(item); _list.Add(item); } public void Clear() { if (_genericList != null) _genericList.Clear(); _list.Clear(); } public bool Contains(T item) { if (_genericList != null) return _genericList.Contains(item); return _list.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { if (_genericList != null) _genericList.CopyTo(array, arrayIndex); _list.CopyTo(array, arrayIndex); } public int Count { get { if (_genericList != null) return _genericList.Count; return _list.Count; } } public bool IsReadOnly { get { if (_genericList != null) return _genericList.IsReadOnly; return _list.IsReadOnly; } } public bool Remove(T item) { if (_genericList != null) return _genericList.Remove(item); bool contains = _list.Contains(item); if (contains) _list.Remove(item); return contains; } public IEnumerator<T> GetEnumerator() { if (_genericList != null) return _genericList.GetEnumerator(); return new EnumeratorWrapper<T>(_list.GetEnumerator()); } IEnumerator IEnumerable.GetEnumerator() { if (_genericList != null) return _genericList.GetEnumerator(); return _list.GetEnumerator(); } int IList.Add(object value) { VerifyValueType(value); Add((T)value); return (Count - 1); } bool IList.Contains(object value) { if (IsCompatibleObject(value)) return Contains((T)value); return false; } int IList.IndexOf(object value) { if (IsCompatibleObject(value)) return IndexOf((T)value); return -1; } void IList.Insert(int index, object value) { VerifyValueType(value); Insert(index, (T)value); } bool IList.IsFixedSize { get { return false; } } void IList.Remove(object value) { if (IsCompatibleObject(value)) Remove((T)value); } object IList.this[int index] { get { return this[index]; } set { VerifyValueType(value); this[index] = (T)value; } } void ICollection.CopyTo(Array array, int arrayIndex) { CopyTo((T[])array, arrayIndex); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) Interlocked.CompareExchange(ref _syncRoot, new object(), null); return _syncRoot; } } private static void VerifyValueType(object value) { if (!IsCompatibleObject(value)) throw new ArgumentException(string.Format("The value '{0}' is not of type '{1}' and cannot be used in this generic collection.", value, typeof(T)), "value"); } private static bool IsCompatibleObject(object value) { if (!(value is T) && (value != null || typeof(T).IsValueType)) return false; return true; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using System.IO.Abstractions; using System.IO.Compression; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Script.Description; using Microsoft.Azure.WebJobs.Script.Management.Models; using Microsoft.Azure.WebJobs.Script.WebHost.Extensions; using Microsoft.Azure.WebJobs.Script.WebHost.Filters; using Microsoft.Azure.WebJobs.Script.WebHost.Management; using Microsoft.Azure.WebJobs.Script.WebHost.Models; using Microsoft.Azure.WebJobs.Script.WebHost.Security.Authorization.Policies; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; namespace Microsoft.Azure.WebJobs.Script.WebHost.Controllers { /// <summary> /// Controller responsible for administrative and management operations on functions /// example retrieving a list of functions, invoking a function, creating a function, etc /// </summary> public class FunctionsController : Controller { private readonly IWebFunctionsManager _functionsManager; private readonly IWebJobsRouter _webJobsRouter; private readonly ILogger _logger; public FunctionsController(IWebFunctionsManager functionsManager, IWebJobsRouter webJobsRouter, ILoggerFactory loggerFactory) { _functionsManager = functionsManager; _webJobsRouter = webJobsRouter; _logger = loggerFactory?.CreateLogger(ScriptConstants.LogCategoryFunctionsController); } [HttpGet] [Route("admin/functions")] [Authorize(Policy = PolicyNames.AdminAuthLevel)] public async Task<IActionResult> List(bool includeProxies = false) { var result = await _functionsManager.GetFunctionsMetadata(includeProxies); return Ok(result); } [HttpGet] [Route("admin/functions/{name}")] [Authorize(Policy = PolicyNames.AdminAuthLevel)] public async Task<IActionResult> Get(string name) { (var success, var function) = await _functionsManager.TryGetFunction(name, Request); return success ? Ok(function) : NotFound() as IActionResult; } [HttpPut] [Route("admin/functions/{name}")] [Authorize(Policy = PolicyNames.AdminAuthLevel)] public async Task<IActionResult> CreateOrUpdate(string name, [FromBody] FunctionMetadataResponse functionMetadata) { if (!Utility.IsValidFunctionName(name)) { return BadRequest($"{name} is not a valid function name"); } (var success, var configChanged, var functionMetadataResponse) = await _functionsManager.CreateOrUpdate(name, functionMetadata, Request); if (success) { return Created(Request.GetDisplayUrl(), functionMetadataResponse); } else { return StatusCode(500); } } [HttpPost] [Route("admin/functions/{name}")] [Authorize(Policy = PolicyNames.AdminAuthLevel)] [RequiresRunningHost] public IActionResult Invoke(string name, [FromBody] FunctionInvocation invocation, [FromServices] IScriptJobHost scriptHost) { if (invocation == null) { return BadRequest(); } FunctionDescriptor function = scriptHost.GetFunctionOrNull(name); if (function == null) { return NotFound(); } ParameterDescriptor inputParameter = function.Parameters.First(p => p.IsTrigger); Dictionary<string, object> arguments = new Dictionary<string, object>() { { inputParameter.Name, invocation.Input } }; Task.Run(async () => { IDictionary<string, object> loggerScope = new Dictionary<string, object> { { "MS_IgnoreActivity", null } }; using (_logger.BeginScope(loggerScope)) { await scriptHost.CallAsync(function.Name, arguments); } }); return Accepted(); } [HttpGet] [Route("admin/functions/{name}/status")] [Authorize(Policy = PolicyNames.AdminAuthLevel)] public async Task<IActionResult> GetFunctionStatus(string name, [FromServices] IScriptJobHost scriptHost = null) { FunctionStatus status = new FunctionStatus(); // first see if the function has any errors // if the host is not running or is offline // there will be no error info if (scriptHost != null && scriptHost.FunctionErrors.TryGetValue(name, out ICollection<string> functionErrors)) { status.Errors = functionErrors; } else { // if we don't have any errors registered, make sure the function exists // before returning empty errors var result = await _functionsManager.GetFunctionsMetadata(includeProxies: true); var function = result.FirstOrDefault(p => p.Name.ToLowerInvariant() == name.ToLowerInvariant()); if (function == null) { return NotFound(); } } return Ok(status); } [HttpDelete] [Route("admin/functions/{name}")] [Authorize(Policy = PolicyNames.AdminAuthLevel)] public async Task<IActionResult> Delete(string name) { (var found, var function) = await _functionsManager.TryGetFunction(name, Request); if (!found) { return NotFound(); } (var deleted, var error) = _functionsManager.TryDeleteFunction(function); if (deleted) { return NoContent(); } else { return StatusCode(StatusCodes.Status500InternalServerError, error); } } [HttpGet] [Route("admin/functions/download")] [Authorize(Policy = PolicyNames.AdminAuthLevel)] public IActionResult Download([FromServices] IOptions<ScriptApplicationHostOptions> webHostOptions) { var path = webHostOptions.Value.ScriptPath; var dirInfo = FileUtility.DirectoryInfoFromDirectoryName(path); return new FileCallbackResult(new MediaTypeHeaderValue("application/octet-stream"), async (outputStream, _) => { using (var zipArchive = new ZipArchive(outputStream, ZipArchiveMode.Create)) { foreach (FileSystemInfoBase fileSysInfo in dirInfo.GetFileSystemInfos()) { if (fileSysInfo is DirectoryInfoBase directoryInfo) { await zipArchive.AddDirectory(directoryInfo, fileSysInfo.Name); } else { // Add it at the root of the zip await zipArchive.AddFile(fileSysInfo.FullName, string.Empty); } } } }) { FileDownloadName = (System.Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "functions") + ".zip" }; } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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.IO; using SharpDX.Direct3D11; using SharpDX.IO; namespace SharpDX.Toolkit.Graphics { /// <summary> /// A TextureCube front end to <see cref="SharpDX.Direct3D11.Texture2D"/>. /// </summary> public class TextureCube : Texture2DBase { internal TextureCube(Device device, Texture2DDescription description2D, params DataBox[] dataBoxes) : base(device, description2D, dataBoxes) { Initialize(Resource); } internal TextureCube(Device device, Direct3D11.Texture2D texture) : base(device, texture) { Initialize(Resource); } internal override TextureView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipMapSlice) { throw new System.NotSupportedException(); } /// <summary> /// Makes a copy of this texture. /// </summary> /// <remarks> /// This method doesn't copy the content of the texture. /// </remarks> /// <returns> /// A copy of this texture. /// </returns> public override Texture Clone() { return new TextureCube(GraphicsDevice, this.Description); } /// <summary> /// Creates a new texture from a <see cref="Texture2DDescription"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="description">The description.</param> /// <returns> /// A new instance of <see cref="TextureCube"/> class. /// </returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static TextureCube New(Device device, Texture2DDescription description) { return new TextureCube(device, description); } /// <summary> /// Creates a new texture from a <see cref="Direct3D11.Texture2D"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="texture">The native texture <see cref="Direct3D11.Texture2D"/>.</param> /// <returns> /// A new instance of <see cref="TextureCube"/> class. /// </returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static TextureCube New(Device device, Direct3D11.Texture2D texture) { return new TextureCube(device, texture); } /// <summary> /// Creates a new <see cref="TextureCube"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="size">The size (in pixels) of the top-level faces of the cube texture.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <returns> /// A new instance of <see cref="Texture2D"/> class. /// </returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static TextureCube New(Device device, int size, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Default) { return New(device, size, false, format, flags, usage); } /// <summary> /// Creates a new <see cref="TextureCube"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="size">The size (in pixels) of the top-level faces of the cube texture.</param> /// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <returns> /// A new instance of <see cref="Texture2D"/> class. /// </returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static TextureCube New(Device device, int size, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Default) { return new TextureCube(device, NewTextureCubeDescription(size, format, flags | TextureFlags.ShaderResource, mipCount, usage)); } /// <summary> /// Creates a new <see cref="TextureCube" /> from a initial data.. /// </summary> /// <typeparam name="T">Type of a pixel data</typeparam> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="size">The size (in pixels) of the top-level faces of the cube texture.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="textureData">an array of 6 textures. See remarks</param> /// <returns>A new instance of <see cref="TextureCube" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> /// <remarks> /// The first dimension of mipMapTextures describes the number of array (TextureCube Array), the second is the texture data for a particular cube face. /// </remarks> public unsafe static TextureCube New<T>(Device device, int size, PixelFormat format, T[][] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) where T : struct { if (textureData.Length != 6) throw new ArgumentException("Invalid texture data. First dimension must be equal to 6", "textureData"); DataBox dataBox1 = new DataBox(); DataBox dataBox2 = new DataBox(); DataBox dataBox3 = new DataBox(); DataBox dataBox4 = new DataBox(); DataBox dataBox5 = new DataBox(); DataBox dataBox6 = new DataBox(); Utilities.Pin(textureData[0], ptr => dataBox1 = GetDataBox(format, size, size, 1, textureData[0], ptr)); Utilities.Pin(textureData[1], ptr => dataBox2 = GetDataBox(format, size, size, 1, textureData[0], ptr)); Utilities.Pin(textureData[2], ptr => dataBox3 = GetDataBox(format, size, size, 1, textureData[0], ptr)); Utilities.Pin(textureData[3], ptr => dataBox4 = GetDataBox(format, size, size, 1, textureData[0], ptr)); Utilities.Pin(textureData[4], ptr => dataBox5 = GetDataBox(format, size, size, 1, textureData[0], ptr)); Utilities.Pin(textureData[5], ptr => dataBox6 = GetDataBox(format, size, size, 1, textureData[0], ptr)); return new TextureCube(device, NewTextureCubeDescription(size, format, flags | TextureFlags.ShaderResource, 1, usage), dataBox1, dataBox2, dataBox3, dataBox4, dataBox5, dataBox6); } /// <summary> /// Creates a new <see cref="TextureCube" /> from a initial data.. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="size">The size (in pixels) of the top-level faces of the cube texture.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="textureData">an array of 6 textures. See remarks</param> /// <returns>A new instance of <see cref="TextureCube" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> /// <remarks> /// The first dimension of mipMapTextures describes the number of array (TextureCube Array), the second is the texture data for a particular cube face. /// </remarks> public static TextureCube New(Device device, int size, PixelFormat format, DataBox[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { if (textureData.Length != 6) throw new ArgumentException("Invalid texture data. First dimension must be equal to 6", "textureData"); return new TextureCube(device, NewTextureCubeDescription(size, format, flags | TextureFlags.ShaderResource, 1, usage), textureData); } /// <summary> /// Creates a new <see cref="TextureCube" /> directly from an <see cref="Image"/>. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="image">An image in CPU memory.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">The usage.</param> /// <returns>A new instance of <see cref="TextureCube" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static TextureCube New(Device device, Image image, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { if (image == null) throw new ArgumentNullException("image"); if (image.Description.Dimension != TextureDimension.TextureCube) throw new ArgumentException("Invalid image. Must be Cube", "image"); return new TextureCube(device, CreateTextureDescriptionFromImage(image, flags | TextureFlags.ShaderResource, usage), image.ToDataBox()); } /// <summary> /// Loads a Cube texture from a stream. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="stream">The stream to load the texture from.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param> /// <exception cref="ArgumentException">If the texture is not of type Cube</exception> /// <returns>A texture</returns> public static new TextureCube Load(Device device, Stream stream, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { var texture = Texture.Load(device, stream, flags | TextureFlags.ShaderResource, usage); if (!(texture is TextureCube)) throw new ArgumentException(string.Format("Texture is not type of [TextureCube] but [{0}]", texture.GetType().Name)); return (TextureCube)texture; } /// <summary> /// Loads a Cube texture from a stream. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="filePath">The file to load the texture from.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param> /// <exception cref="ArgumentException">If the texture is not of type Cube</exception> /// <returns>A texture</returns> public static new TextureCube Load(Device device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read)) return Load(device, stream, flags | TextureFlags.ShaderResource, usage); } /// <summary> /// /// </summary> /// <param name="size"></param> /// <param name="format"></param> /// <param name="flags"></param> /// <param name="mipCount"></param> /// <param name="usage"></param> /// <returns></returns> protected static Texture2DDescription NewTextureCubeDescription(int size, PixelFormat format, TextureFlags flags, int mipCount, ResourceUsage usage) { var desc = NewDescription(size, size, format, flags, mipCount, 6, usage); desc.OptionFlags = ResourceOptionFlags.TextureCube; return desc; } } }
/* * 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.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.Land { public class LandChannel : ILandChannel { #region Constants //Land types set with flags in ParcelOverlay. //Only one of these can be used. public const float BAN_LINE_SAFETY_HIEGHT = 100; //RequestResults (I think these are right, they seem to work): public const int LAND_RESULT_MULTIPLE = 1; // The request they made contained more than a single peice of land public const int LAND_RESULT_SINGLE = 0; // The request they made contained only a single piece of land //ParcelSelectObjects public const int LAND_SELECT_OBJECTS_OWNER = 2; public const int LAND_SELECT_OBJECTS_GROUP = 4; public const int LAND_SELECT_OBJECTS_OTHER = 8; public const byte LAND_TYPE_PUBLIC = 0; //Equals 00000000 // types 1 to 7 are exclusive public const byte LAND_TYPE_OWNED_BY_OTHER = 1; //Equals 00000001 public const byte LAND_TYPE_OWNED_BY_GROUP = 2; //Equals 00000010 public const byte LAND_TYPE_OWNED_BY_REQUESTER = 3; //Equals 00000011 public const byte LAND_TYPE_IS_FOR_SALE = 4; //Equals 00000100 public const byte LAND_TYPE_IS_BEING_AUCTIONED = 5; //Equals 00000101 public const byte LAND_TYPE_unused6 = 6; public const byte LAND_TYPE_unused7 = 7; // next are flags public const byte LAND_FLAG_unused8 = 0x08; // this may become excluside in future public const byte LAND_FLAG_HIDEAVATARS = 0x10; public const byte LAND_FLAG_LOCALSOUND = 0x20; public const byte LAND_FLAG_PROPERTY_BORDER_WEST = 0x40; //Equals 01000000 public const byte LAND_FLAG_PROPERTY_BORDER_SOUTH = 0x80; //Equals 10000000 //These are other constants. Yay! public const int START_LAND_LOCAL_ID = 1; #endregion private readonly Scene m_scene; private readonly LandManagementModule m_landManagementModule; public LandChannel(Scene scene, LandManagementModule landManagementMod) { m_scene = scene; m_landManagementModule = landManagementMod; } #region ILandChannel Members public ILandObject GetLandObject(float x_float, float y_float) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(x_float, y_float); } ILandObject obj = new LandObject(UUID.Zero, false, m_scene); obj.LandData.Name = "NO LAND"; return obj; } public ILandObject GetLandObject(int localID) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(localID); } return null; } public ILandObject GetLandObject(Vector3 position) { return GetLandObject(position.X, position.Y); } public ILandObject GetLandObject(int x, int y) { if (m_landManagementModule != null) { return m_landManagementModule.GetLandObject(x, y); } ILandObject obj = new LandObject(UUID.Zero, false, m_scene); obj.LandData.Name = "NO LAND"; return obj; } public List<ILandObject> AllParcels() { if (m_landManagementModule != null) { return m_landManagementModule.AllParcels(); } return new List<ILandObject>(); } public void Clear(bool setupDefaultParcel) { if (m_landManagementModule != null) m_landManagementModule.Clear(setupDefaultParcel); } public List<ILandObject> ParcelsNearPoint(Vector3 position) { if (m_landManagementModule != null) { return m_landManagementModule.ParcelsNearPoint(position); } return new List<ILandObject>(); } public bool IsForcefulBansAllowed() { if (m_landManagementModule != null) { return m_landManagementModule.AllowedForcefulBans; } return false; } public void UpdateLandObject(int localID, LandData data) { if (m_landManagementModule != null) { m_landManagementModule.UpdateLandObject(localID, data); } } public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) { if (m_landManagementModule != null) { m_landManagementModule.Join(start_x, start_y, end_x, end_y, attempting_user_id); } } public void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) { if (m_landManagementModule != null) { m_landManagementModule.Subdivide(start_x, start_y, end_x, end_y, attempting_user_id); } } public void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient) { if (m_landManagementModule != null) { m_landManagementModule.ReturnObjectsInParcel(localID, returnType, agentIDs, taskIDs, remoteClient); } } public void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel) { if (m_landManagementModule != null) { m_landManagementModule.setParcelObjectMaxOverride(overrideDel); } } public void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel) { if (m_landManagementModule != null) { m_landManagementModule.setSimulatorObjectMaxOverride(overrideDel); } } public void SetParcelOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime) { if (m_landManagementModule != null) { m_landManagementModule.setParcelOtherCleanTime(remoteClient, localID, otherCleanTime); } } public void sendClientInitialLandInfo(IClientAPI remoteClient) { if (m_landManagementModule != null) { m_landManagementModule.sendClientInitialLandInfo(remoteClient); } } #endregion } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// PaymentDetails /// </summary> [DataContract] public partial class PaymentDetails : IEquatable<PaymentDetails>, IValidatableObject { public PaymentDetails() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="PaymentDetails" /> class. /// </summary> /// <param name="AllowedPaymentMethods">AllowedPaymentMethods.</param> /// <param name="ChargeId">ChargeId.</param> /// <param name="CurrencyCode">CurrencyCode.</param> /// <param name="CurrencyCodeMetadata">CurrencyCodeMetadata.</param> /// <param name="CustomerId">CustomerId.</param> /// <param name="CustomMetadata">CustomMetadata.</param> /// <param name="CustomMetadataRequired">CustomMetadataRequired.</param> /// <param name="GatewayAccountId">GatewayAccountId.</param> /// <param name="GatewayAccountIdMetadata">GatewayAccountIdMetadata.</param> /// <param name="GatewayDisplayName">GatewayDisplayName.</param> /// <param name="GatewayName">GatewayName.</param> /// <param name="LineItems">LineItems.</param> /// <param name="PaymentOption">PaymentOption.</param> /// <param name="PaymentSourceId">PaymentSourceId.</param> /// <param name="SignerValues">SignerValues.</param> /// <param name="Status">Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later..</param> /// <param name="Total">Total.</param> public PaymentDetails(List<string> AllowedPaymentMethods = default(List<string>), string ChargeId = default(string), string CurrencyCode = default(string), PropertyMetadata CurrencyCodeMetadata = default(PropertyMetadata), string CustomerId = default(string), string CustomMetadata = default(string), bool? CustomMetadataRequired = default(bool?), string GatewayAccountId = default(string), PropertyMetadata GatewayAccountIdMetadata = default(PropertyMetadata), string GatewayDisplayName = default(string), string GatewayName = default(string), List<PaymentLineItem> LineItems = default(List<PaymentLineItem>), string PaymentOption = default(string), string PaymentSourceId = default(string), PaymentSignerValues SignerValues = default(PaymentSignerValues), string Status = default(string), Money Total = default(Money)) { this.AllowedPaymentMethods = AllowedPaymentMethods; this.ChargeId = ChargeId; this.CurrencyCode = CurrencyCode; this.CurrencyCodeMetadata = CurrencyCodeMetadata; this.CustomerId = CustomerId; this.CustomMetadata = CustomMetadata; this.CustomMetadataRequired = CustomMetadataRequired; this.GatewayAccountId = GatewayAccountId; this.GatewayAccountIdMetadata = GatewayAccountIdMetadata; this.GatewayDisplayName = GatewayDisplayName; this.GatewayName = GatewayName; this.LineItems = LineItems; this.PaymentOption = PaymentOption; this.PaymentSourceId = PaymentSourceId; this.SignerValues = SignerValues; this.Status = Status; this.Total = Total; } /// <summary> /// Gets or Sets AllowedPaymentMethods /// </summary> [DataMember(Name="allowedPaymentMethods", EmitDefaultValue=false)] public List<string> AllowedPaymentMethods { get; set; } /// <summary> /// Gets or Sets ChargeId /// </summary> [DataMember(Name="chargeId", EmitDefaultValue=false)] public string ChargeId { get; set; } /// <summary> /// Gets or Sets CurrencyCode /// </summary> [DataMember(Name="currencyCode", EmitDefaultValue=false)] public string CurrencyCode { get; set; } /// <summary> /// Gets or Sets CurrencyCodeMetadata /// </summary> [DataMember(Name="currencyCodeMetadata", EmitDefaultValue=false)] public PropertyMetadata CurrencyCodeMetadata { get; set; } /// <summary> /// Gets or Sets CustomerId /// </summary> [DataMember(Name="customerId", EmitDefaultValue=false)] public string CustomerId { get; set; } /// <summary> /// Gets or Sets CustomMetadata /// </summary> [DataMember(Name="customMetadata", EmitDefaultValue=false)] public string CustomMetadata { get; set; } /// <summary> /// Gets or Sets CustomMetadataRequired /// </summary> [DataMember(Name="customMetadataRequired", EmitDefaultValue=false)] public bool? CustomMetadataRequired { get; set; } /// <summary> /// Gets or Sets GatewayAccountId /// </summary> [DataMember(Name="gatewayAccountId", EmitDefaultValue=false)] public string GatewayAccountId { get; set; } /// <summary> /// Gets or Sets GatewayAccountIdMetadata /// </summary> [DataMember(Name="gatewayAccountIdMetadata", EmitDefaultValue=false)] public PropertyMetadata GatewayAccountIdMetadata { get; set; } /// <summary> /// Gets or Sets GatewayDisplayName /// </summary> [DataMember(Name="gatewayDisplayName", EmitDefaultValue=false)] public string GatewayDisplayName { get; set; } /// <summary> /// Gets or Sets GatewayName /// </summary> [DataMember(Name="gatewayName", EmitDefaultValue=false)] public string GatewayName { get; set; } /// <summary> /// Gets or Sets LineItems /// </summary> [DataMember(Name="lineItems", EmitDefaultValue=false)] public List<PaymentLineItem> LineItems { get; set; } /// <summary> /// Gets or Sets PaymentOption /// </summary> [DataMember(Name="paymentOption", EmitDefaultValue=false)] public string PaymentOption { get; set; } /// <summary> /// Gets or Sets PaymentSourceId /// </summary> [DataMember(Name="paymentSourceId", EmitDefaultValue=false)] public string PaymentSourceId { get; set; } /// <summary> /// Gets or Sets SignerValues /// </summary> [DataMember(Name="signerValues", EmitDefaultValue=false)] public PaymentSignerValues SignerValues { get; set; } /// <summary> /// Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later. /// </summary> /// <value>Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.</value> [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; set; } /// <summary> /// Gets or Sets Total /// </summary> [DataMember(Name="total", EmitDefaultValue=false)] public Money Total { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PaymentDetails {\n"); sb.Append(" AllowedPaymentMethods: ").Append(AllowedPaymentMethods).Append("\n"); sb.Append(" ChargeId: ").Append(ChargeId).Append("\n"); sb.Append(" CurrencyCode: ").Append(CurrencyCode).Append("\n"); sb.Append(" CurrencyCodeMetadata: ").Append(CurrencyCodeMetadata).Append("\n"); sb.Append(" CustomerId: ").Append(CustomerId).Append("\n"); sb.Append(" CustomMetadata: ").Append(CustomMetadata).Append("\n"); sb.Append(" CustomMetadataRequired: ").Append(CustomMetadataRequired).Append("\n"); sb.Append(" GatewayAccountId: ").Append(GatewayAccountId).Append("\n"); sb.Append(" GatewayAccountIdMetadata: ").Append(GatewayAccountIdMetadata).Append("\n"); sb.Append(" GatewayDisplayName: ").Append(GatewayDisplayName).Append("\n"); sb.Append(" GatewayName: ").Append(GatewayName).Append("\n"); sb.Append(" LineItems: ").Append(LineItems).Append("\n"); sb.Append(" PaymentOption: ").Append(PaymentOption).Append("\n"); sb.Append(" PaymentSourceId: ").Append(PaymentSourceId).Append("\n"); sb.Append(" SignerValues: ").Append(SignerValues).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" Total: ").Append(Total).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as PaymentDetails); } /// <summary> /// Returns true if PaymentDetails instances are equal /// </summary> /// <param name="other">Instance of PaymentDetails to be compared</param> /// <returns>Boolean</returns> public bool Equals(PaymentDetails other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AllowedPaymentMethods == other.AllowedPaymentMethods || this.AllowedPaymentMethods != null && this.AllowedPaymentMethods.SequenceEqual(other.AllowedPaymentMethods) ) && ( this.ChargeId == other.ChargeId || this.ChargeId != null && this.ChargeId.Equals(other.ChargeId) ) && ( this.CurrencyCode == other.CurrencyCode || this.CurrencyCode != null && this.CurrencyCode.Equals(other.CurrencyCode) ) && ( this.CurrencyCodeMetadata == other.CurrencyCodeMetadata || this.CurrencyCodeMetadata != null && this.CurrencyCodeMetadata.Equals(other.CurrencyCodeMetadata) ) && ( this.CustomerId == other.CustomerId || this.CustomerId != null && this.CustomerId.Equals(other.CustomerId) ) && ( this.CustomMetadata == other.CustomMetadata || this.CustomMetadata != null && this.CustomMetadata.Equals(other.CustomMetadata) ) && ( this.CustomMetadataRequired == other.CustomMetadataRequired || this.CustomMetadataRequired != null && this.CustomMetadataRequired.Equals(other.CustomMetadataRequired) ) && ( this.GatewayAccountId == other.GatewayAccountId || this.GatewayAccountId != null && this.GatewayAccountId.Equals(other.GatewayAccountId) ) && ( this.GatewayAccountIdMetadata == other.GatewayAccountIdMetadata || this.GatewayAccountIdMetadata != null && this.GatewayAccountIdMetadata.Equals(other.GatewayAccountIdMetadata) ) && ( this.GatewayDisplayName == other.GatewayDisplayName || this.GatewayDisplayName != null && this.GatewayDisplayName.Equals(other.GatewayDisplayName) ) && ( this.GatewayName == other.GatewayName || this.GatewayName != null && this.GatewayName.Equals(other.GatewayName) ) && ( this.LineItems == other.LineItems || this.LineItems != null && this.LineItems.SequenceEqual(other.LineItems) ) && ( this.PaymentOption == other.PaymentOption || this.PaymentOption != null && this.PaymentOption.Equals(other.PaymentOption) ) && ( this.PaymentSourceId == other.PaymentSourceId || this.PaymentSourceId != null && this.PaymentSourceId.Equals(other.PaymentSourceId) ) && ( this.SignerValues == other.SignerValues || this.SignerValues != null && this.SignerValues.Equals(other.SignerValues) ) && ( this.Status == other.Status || this.Status != null && this.Status.Equals(other.Status) ) && ( this.Total == other.Total || this.Total != null && this.Total.Equals(other.Total) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.AllowedPaymentMethods != null) hash = hash * 59 + this.AllowedPaymentMethods.GetHashCode(); if (this.ChargeId != null) hash = hash * 59 + this.ChargeId.GetHashCode(); if (this.CurrencyCode != null) hash = hash * 59 + this.CurrencyCode.GetHashCode(); if (this.CurrencyCodeMetadata != null) hash = hash * 59 + this.CurrencyCodeMetadata.GetHashCode(); if (this.CustomerId != null) hash = hash * 59 + this.CustomerId.GetHashCode(); if (this.CustomMetadata != null) hash = hash * 59 + this.CustomMetadata.GetHashCode(); if (this.CustomMetadataRequired != null) hash = hash * 59 + this.CustomMetadataRequired.GetHashCode(); if (this.GatewayAccountId != null) hash = hash * 59 + this.GatewayAccountId.GetHashCode(); if (this.GatewayAccountIdMetadata != null) hash = hash * 59 + this.GatewayAccountIdMetadata.GetHashCode(); if (this.GatewayDisplayName != null) hash = hash * 59 + this.GatewayDisplayName.GetHashCode(); if (this.GatewayName != null) hash = hash * 59 + this.GatewayName.GetHashCode(); if (this.LineItems != null) hash = hash * 59 + this.LineItems.GetHashCode(); if (this.PaymentOption != null) hash = hash * 59 + this.PaymentOption.GetHashCode(); if (this.PaymentSourceId != null) hash = hash * 59 + this.PaymentSourceId.GetHashCode(); if (this.SignerValues != null) hash = hash * 59 + this.SignerValues.GetHashCode(); if (this.Status != null) hash = hash * 59 + this.Status.GetHashCode(); if (this.Total != null) hash = hash * 59 + this.Total.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Copyright 2016, Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api; using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Monitoring.V3; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Monitoring.V3.Snippets { public class GeneratedGroupServiceClientSnippets { public async Task GetGroupAsync() { // Snippet: GetGroupAsync(string,CallSettings) // Additional: GetGroupAsync(string,CancellationToken) // Create client GroupServiceClient groupServiceClient = GroupServiceClient.Create(); // Initialize request argument(s) string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]"); // Make the request Group response = await groupServiceClient.GetGroupAsync(formattedName); // End snippet } public void GetGroup() { // Snippet: GetGroup(string,CallSettings) // Create client GroupServiceClient groupServiceClient = GroupServiceClient.Create(); // Initialize request argument(s) string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]"); // Make the request Group response = groupServiceClient.GetGroup(formattedName); // End snippet } public async Task CreateGroupAsync() { // Snippet: CreateGroupAsync(string,Group,CallSettings) // Additional: CreateGroupAsync(string,Group,CancellationToken) // Create client GroupServiceClient groupServiceClient = GroupServiceClient.Create(); // Initialize request argument(s) string formattedName = GroupServiceClient.FormatProjectName("[PROJECT]"); Group group = new Group(); // Make the request Group response = await groupServiceClient.CreateGroupAsync(formattedName, group); // End snippet } public void CreateGroup() { // Snippet: CreateGroup(string,Group,CallSettings) // Create client GroupServiceClient groupServiceClient = GroupServiceClient.Create(); // Initialize request argument(s) string formattedName = GroupServiceClient.FormatProjectName("[PROJECT]"); Group group = new Group(); // Make the request Group response = groupServiceClient.CreateGroup(formattedName, group); // End snippet } public async Task UpdateGroupAsync() { // Snippet: UpdateGroupAsync(Group,CallSettings) // Additional: UpdateGroupAsync(Group,CancellationToken) // Create client GroupServiceClient groupServiceClient = GroupServiceClient.Create(); // Initialize request argument(s) Group group = new Group(); // Make the request Group response = await groupServiceClient.UpdateGroupAsync(group); // End snippet } public void UpdateGroup() { // Snippet: UpdateGroup(Group,CallSettings) // Create client GroupServiceClient groupServiceClient = GroupServiceClient.Create(); // Initialize request argument(s) Group group = new Group(); // Make the request Group response = groupServiceClient.UpdateGroup(group); // End snippet } public async Task DeleteGroupAsync() { // Snippet: DeleteGroupAsync(string,CallSettings) // Additional: DeleteGroupAsync(string,CancellationToken) // Create client GroupServiceClient groupServiceClient = GroupServiceClient.Create(); // Initialize request argument(s) string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]"); // Make the request await groupServiceClient.DeleteGroupAsync(formattedName); // End snippet } public void DeleteGroup() { // Snippet: DeleteGroup(string,CallSettings) // Create client GroupServiceClient groupServiceClient = GroupServiceClient.Create(); // Initialize request argument(s) string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]"); // Make the request groupServiceClient.DeleteGroup(formattedName); // End snippet } public async Task ListGroupMembersAsync() { // Snippet: ListGroupMembersAsync(string,string,int?,CallSettings) // Create client GroupServiceClient groupServiceClient = GroupServiceClient.Create(); // Initialize request argument(s) string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]"); // Make the request IPagedAsyncEnumerable<ListGroupMembersResponse,MonitoredResource> response = groupServiceClient.ListGroupMembersAsync(formattedName); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((MonitoredResource item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over fixed-sized pages, lazily performing RPCs as required int pageSize = 10; IAsyncEnumerable<FixedSizePage<MonitoredResource>> fixedSizePages = response.AsPages().WithFixedSize(pageSize); await fixedSizePages.ForEachAsync((FixedSizePage<MonitoredResource> page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MonitoredResource item in page) { Console.WriteLine(item); } }); // End snippet } public void ListGroupMembers() { // Snippet: ListGroupMembers(string,string,int?,CallSettings) // Create client GroupServiceClient groupServiceClient = GroupServiceClient.Create(); // Initialize request argument(s) string formattedName = GroupServiceClient.FormatGroupName("[PROJECT]", "[GROUP]"); // Make the request IPagedEnumerable<ListGroupMembersResponse,MonitoredResource> response = groupServiceClient.ListGroupMembers(formattedName); // Iterate over all response items, lazily performing RPCs as required foreach (MonitoredResource item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over fixed-sized pages, lazily performing RPCs as required int pageSize = 10; foreach (FixedSizePage<MonitoredResource> page in response.AsPages().WithFixedSize(pageSize)) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MonitoredResource item in page) { Console.WriteLine(item); } } // End snippet } } }
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This is a Keyboard Subclass that runs on device only. It displays the // full VR Keyboard. using UnityEngine; using UnityEngine.VR; using System; using System.Runtime.InteropServices; /// @cond namespace Gvr.Internal { public class AndroidNativeKeyboardProvider : IKeyboardProvider { private IntPtr renderEventFunction; #if UNITY_ANDROID && !UNITY_EDITOR private float currentDistance = 0.0f; #endif // UNITY_ANDROID && !UNITY_EDITOR // Android method names. private const string METHOD_NAME_GET_PACKAGE_MANAGER = "getPackageManager"; private const string METHOD_NAME_GET_PACKAGE_INFO = "getPackageInfo"; private const string PACKAGE_NAME_VRINPUTMETHOD = "com.google.android.vr.inputmethod"; private const string FIELD_NAME_VERSION_CODE = "versionCode"; // Min version for VrInputMethod. private const int MIN_VERSION_VRINPUTMETHOD = 170509062; // Library name. private const string dllName = "gvr_keyboard_shim_unity"; // Enum gvr_trigger_state. private const int TRIGGER_NONE = 0; private const int TRIGGER_PRESSED = 1; [StructLayout (LayoutKind.Sequential)] private struct gvr_clock_time_point { public long monotonic_system_time_nanos; } [StructLayout (LayoutKind.Sequential)] private struct gvr_recti { public int left; public int right; public int bottom; public int top; } [DllImport (GvrActivityHelper.GVR_DLL_NAME)] private static extern gvr_clock_time_point gvr_get_time_point_now(); [DllImport (dllName)] private static extern GvrKeyboardInputMode gvr_keyboard_get_input_mode(IntPtr keyboard_context); [DllImport (dllName)] private static extern void gvr_keyboard_set_input_mode(IntPtr keyboard_context, GvrKeyboardInputMode mode); #if UNITY_ANDROID [DllImport(dllName)] private static extern IntPtr gvr_keyboard_initialize(AndroidJavaObject app_context, AndroidJavaObject class_loader); #endif [DllImport (dllName)] private static extern IntPtr gvr_keyboard_create(IntPtr closure, GvrKeyboard.KeyboardCallback callback); // Gets a recommended world space matrix. [DllImport (dllName)] private static extern void gvr_keyboard_get_recommended_world_from_keyboard_matrix(float distance_from_eye, IntPtr matrix); // Sets the recommended world space matrix. The matrix may // contain a combination of translation/rotation/scaling information. [DllImport(dllName)] private static extern void gvr_keyboard_set_world_from_keyboard_matrix(IntPtr keyboard_context, IntPtr matrix); // Shows the keyboard [DllImport (dllName)] private static extern void gvr_keyboard_show(IntPtr keyboard_context); // Updates the keyboard with the controller's button state. [DllImport(dllName)] private static extern void gvr_keyboard_update_button_state(IntPtr keyboard_context, int buttonIndex, bool pressed); // Updates the controller ray on the keyboard. [DllImport(dllName)] private static extern bool gvr_keyboard_update_controller_ray(IntPtr keyboard_context, IntPtr vector3Start, IntPtr vector3End, IntPtr vector3Hit); // Returns the EditText with for the keyboard. [DllImport (dllName)] private static extern IntPtr gvr_keyboard_get_text(IntPtr keyboard_context); // Sets the edit_text for the keyboard. // @return 1 if the edit text could be set. 0 if it cannot be set. [DllImport (dllName)] private static extern int gvr_keyboard_set_text(IntPtr keyboard_context, IntPtr edit_text); // Hides the keyboard. [DllImport (dllName)] private static extern void gvr_keyboard_hide(IntPtr keyboard_context); // Destroys the keyboard. Resources related to the keyboard is released. [DllImport (dllName)] private static extern void gvr_keyboard_destroy(IntPtr keyboard_context); // Called once per frame to set the time index. [DllImport(dllName)] private static extern void GvrKeyboardSetFrameData(IntPtr keyboard_context, gvr_clock_time_point t); // Sets VR eye data in preparation for rendering a single eye's view. [DllImport(dllName)] private static extern void GvrKeyboardSetEyeData(int eye_type, Matrix4x4 modelview, Matrix4x4 projection, gvr_recti viewport); [DllImport(dllName)] private static extern IntPtr GetKeyboardRenderEventFunc(); // Private class data. private IntPtr keyboard_context = IntPtr.Zero; // Used in the GVR Unity C++ shim layer. private const int advanceID = 0x5DAC793B; private const int renderLeftID = 0x3CF97A3D; private const int renderRightID = 0x3CF97A3E; private const string KEYBOARD_JAVA_CLASS = "com.google.vr.keyboard.GvrKeyboardUnity"; private const long kPredictionTimeWithoutVsyncNanos = 50000000; private const int kGvrControllerButtonClick = 1; private GvrKeyboardInputMode mode = GvrKeyboardInputMode.DEFAULT; private string editorText = string.Empty; private Matrix4x4 worldMatrix; private bool isValid = false; private bool isReady = false; public string EditorText { get { IntPtr text = gvr_keyboard_get_text(keyboard_context); editorText = Marshal.PtrToStringAnsi(text); return editorText; } set { editorText = value; IntPtr text = Marshal.StringToHGlobalAnsi(editorText); gvr_keyboard_set_text(keyboard_context, text); } } public void SetInputMode(GvrKeyboardInputMode mode) { Debug.Log("Calling set input mode: " + mode); gvr_keyboard_set_input_mode(keyboard_context, mode); this.mode = mode; } public void OnPause() { } public void OnResume() { } public void ReadState(KeyboardState outState) { outState.editorText = editorText; outState.mode = mode; outState.worldMatrix = worldMatrix; outState.isValid = isValid; outState.isReady = isReady; } // Initialization function. public AndroidNativeKeyboardProvider() { #if UNITY_ANDROID && !UNITY_EDITOR // Running on Android device. AndroidJavaObject activity = GvrActivityHelper.GetActivity(); if (activity == null) { Debug.Log("Failed to get activity for keyboard."); return; } AndroidJavaObject context = GvrActivityHelper.GetApplicationContext(activity); if (context == null) { Debug.Log("Failed to get context for keyboard."); return; } AndroidJavaObject plugin = new AndroidJavaObject(KEYBOARD_JAVA_CLASS); if (plugin != null) { plugin.Call("initializeKeyboard", context); isValid = true; } #endif // UNITY_ANDROID && !UNITY_EDITOR UnityEngine.XR.InputTracking.disablePositionalTracking = true; renderEventFunction = GetKeyboardRenderEventFunc(); } ~AndroidNativeKeyboardProvider() { if (keyboard_context != IntPtr.Zero) gvr_keyboard_destroy(keyboard_context); } public bool Create(GvrKeyboard.KeyboardCallback keyboardEvent) { if (!IsVrInputMethodAppMinVersion(keyboardEvent)) { return false; } keyboard_context = gvr_keyboard_create(IntPtr.Zero, keyboardEvent); isReady = keyboard_context != IntPtr.Zero; return isReady; } public void Show(Matrix4x4 userMatrix, bool useRecommended, float distance, Matrix4x4 model) { #if UNITY_ANDROID && !UNITY_EDITOR currentDistance = distance; #endif // UNITY_ANDROID && !UNITY_EDITOR if (useRecommended) { worldMatrix = getRecommendedMatrix(distance); } else { // Convert to GVR coordinates. worldMatrix = Pose3D.FlipHandedness(userMatrix).transpose; } Matrix4x4 matToSet = worldMatrix * model.transpose; IntPtr mat_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(matToSet)); Marshal.StructureToPtr(matToSet, mat_ptr, true); gvr_keyboard_set_world_from_keyboard_matrix(keyboard_context, mat_ptr); gvr_keyboard_show(keyboard_context); } public void UpdateData() { #if UNITY_ANDROID && !UNITY_EDITOR // Running on Android device. // Update controller state. GvrBasePointer pointer = GvrPointerInputModule.Pointer; bool isPointerAvailable = pointer != null && pointer.IsAvailable; if (isPointerAvailable && GvrControllerInput.State == GvrConnectionState.Connected) { bool pressed = GvrControllerInput.ClickButton; gvr_keyboard_update_button_state(keyboard_context, kGvrControllerButtonClick, pressed); GvrBasePointer.PointerRay pointerRay = pointer.GetRayForDistance(currentDistance); Vector3 startPoint = pointerRay.ray.origin; // Need to flip Z for native library startPoint.z *= -1; IntPtr start_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(startPoint)); Marshal.StructureToPtr(startPoint, start_ptr, true); Vector3 endPoint = pointerRay.ray.GetPoint(pointerRay.distance); // Need to flip Z for native library endPoint.z *= -1; IntPtr end_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(endPoint)); Marshal.StructureToPtr(endPoint, end_ptr, true); Vector3 hit = Vector3.one; IntPtr hit_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(Vector3.zero)); Marshal.StructureToPtr(Vector3.zero, hit_ptr, true); gvr_keyboard_update_controller_ray(keyboard_context, start_ptr, end_ptr, hit_ptr); hit = (Vector3)Marshal.PtrToStructure(hit_ptr, typeof(Vector3)); hit.z *= -1; } #endif // UNITY_ANDROID && !UNITY_EDITOR // Get time stamp. gvr_clock_time_point time = gvr_get_time_point_now(); time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos; // Update frame data. GvrKeyboardSetFrameData(keyboard_context, time); GL.IssuePluginEvent(renderEventFunction, advanceID); } public void Render(int eye, Matrix4x4 modelview, Matrix4x4 projection, Rect viewport) { gvr_recti rect = new gvr_recti(); rect.left = (int)viewport.x; rect.top = (int)viewport.y + (int)viewport.height; rect.right = (int)viewport.x + (int)viewport.width; rect.bottom = (int)viewport.y; // For the modelview matrix, we need to convert it to a world-to-camera // matrix for GVR keyboard, hence the inverse. We need to convert left // handed to right handed, hence the multiply by flipZ. // Unity projection matrices are already in a form GVR needs. // Unity stores matrices row-major, so both get a final transpose to get // them column-major for GVR. GvrKeyboardSetEyeData(eye, (Pose3D.FLIP_Z * modelview.inverse).transpose.inverse, projection.transpose, rect); GL.IssuePluginEvent(renderEventFunction, eye == 0 ? renderLeftID : renderRightID); } public void Hide() { gvr_keyboard_hide(keyboard_context); } // Return the recommended keyboard local to world space // matrix given a distance value by the user. This value should // be between 1 and 5 and will get clamped to that range. private Matrix4x4 getRecommendedMatrix(float inputDistance) { float distance = Mathf.Clamp(inputDistance, 1.0f, 5.0f); Matrix4x4 result = new Matrix4x4(); IntPtr mat_ptr = Marshal.AllocHGlobal(Marshal.SizeOf (result)); Marshal.StructureToPtr(result, mat_ptr, true); gvr_keyboard_get_recommended_world_from_keyboard_matrix(distance, mat_ptr); result = (Matrix4x4) Marshal.PtrToStructure(mat_ptr, typeof(Matrix4x4)); return result; } // Returns true if the VrInputMethod APK is at least as high as MIN_VERSION_VRINPUTMETHOD. private bool IsVrInputMethodAppMinVersion(GvrKeyboard.KeyboardCallback keyboardEvent) { #if UNITY_ANDROID && !UNITY_EDITOR // Running on Android device. AndroidJavaObject activity = GvrActivityHelper.GetActivity(); if (activity == null) { Debug.Log("Failed to get activity for keyboard."); return false; } AndroidJavaObject packageManager = activity.Call<AndroidJavaObject>(METHOD_NAME_GET_PACKAGE_MANAGER); if (packageManager == null) { Debug.Log("Failed to get activity package manager"); return false; } AndroidJavaObject info = packageManager.Call<AndroidJavaObject>(METHOD_NAME_GET_PACKAGE_INFO, PACKAGE_NAME_VRINPUTMETHOD, 0); if (info == null) { Debug.Log("Failed to get package info for com.google.android.apps.vr.inputmethod"); return false; } int versionCode = info.Get<int>(FIELD_NAME_VERSION_CODE); if (versionCode < MIN_VERSION_VRINPUTMETHOD) { keyboardEvent(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SDK_LOAD_FAILED); return false; } return true; #else return true; #endif // UNITY_ANDROID && !UNITY_EDITOR } } }
// // UnityOSC - Open Sound Control interface for the Unity3d game engine // // Copyright (c) 2012 Jorge Garcia Martin // // 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.Diagnostics; using System.Collections.Generic; using System.Text; namespace UnityOSC { /// <summary> /// Models a OSC Packet over an OSC stream. /// </summary> abstract public class OSCPacket { #region Member Variables protected List<object> _data; protected byte[] _binaryData; protected string _address; protected long _timeStamp; #endregion #region Properties public string Address { get { return _address; } set { Trace.Assert(string.IsNullOrEmpty(_address) == false); _address = value; } } public List<object> Data { get { return _data; } } public byte[] BinaryData { get { Pack(); return _binaryData; } } public long TimeStamp { get { return _timeStamp; } set { _timeStamp = value; } } #endregion #region Methods abstract public bool IsBundle(); abstract public void Pack(); abstract public void Append<T>(T msgvalue); /// <summary> /// OSC Packet initialization. /// </summary> public OSCPacket () { this._data = new List<object>(); } /// <summary> /// Swap endianess given a data set. /// </summary> /// <param name="data"> /// A <see cref="System.Byte[]"/> /// </param> /// <returns> /// A <see cref="System.Byte[]"/> /// </returns> protected static byte[] SwapEndian(byte[] data) { byte[] swapped = new byte[data.Length]; for(int i = data.Length - 1, j = 0 ; i >= 0 ; i--, j++) { swapped[j] = data[i]; } return swapped; } /// <summary> /// Packs a value in a byte stream. Accepted types: Int32, Int64, Single, Double, String and Byte[]. /// </summary> /// <param name="value"> /// A <see cref="T"/> /// </param> /// <returns> /// A <see cref="System.Byte[]"/> /// </returns> protected static byte[] PackValue<T>(T value) { object valueObject = value; Type type = value.GetType(); byte[] data = null; switch (type.Name) { case "Int32": data = BitConverter.GetBytes((int)valueObject); if (BitConverter.IsLittleEndian) data = SwapEndian(data); break; case "Int64": data = BitConverter.GetBytes((long)valueObject); if (BitConverter.IsLittleEndian) data = SwapEndian(data); break; case "Single": data = BitConverter.GetBytes((float)valueObject); if (BitConverter.IsLittleEndian) data = SwapEndian(data); break; case "Double": data = BitConverter.GetBytes((double)valueObject); if (BitConverter.IsLittleEndian) data = SwapEndian(data); break; case "String": data = Encoding.ASCII.GetBytes((string)valueObject); break; case "Byte[]": byte[] valueData = ((byte[])valueObject); List<byte> bytes = new List<byte>(); bytes.AddRange(PackValue(valueData.Length)); bytes.AddRange(valueData); data = bytes.ToArray(); break; default: throw new Exception("Unsupported data type."); } return data; } /// <summary> /// Unpacks a value from a byte stream. Accepted types: Int32, Int64, Single, Double, String and Byte[]. /// </summary> /// <param name="data"> /// A <see cref="System.Byte[]"/> /// </param> /// <param name="start"> /// A <see cref="System.Int32"/> /// </param> /// <returns> /// A <see cref="T"/> /// </returns> /// this was protected protected static T UnpackValue<T>(byte[] data, ref int start) { object msgvalue; //msgvalue is casted and returned by the function Type type = typeof(T); byte[] buffername; if (type.Name == "String") { int count = 0; for (int index = start; data[index] != 0; index++) count++; msgvalue = Encoding.ASCII.GetString(data, start, count); start += count + 1; start = ((start + 3) / 4) * 4; } else if (type.Name == "Byte[]") { int length = UnpackValue<int>(data, ref start); byte[] buffer = new byte[length]; Array.Copy(data, start, buffer, 0, buffer.Length); start += buffer.Length; start = ((start + 3) / 4) * 4; msgvalue = buffer; } else { switch (type.Name) { case "Int32": case "Single"://this also serves for float numbers buffername = new byte[4]; break; case "Int64": case "Double": buffername = new byte[8]; break; default: throw new Exception("Unsupported data type."); } Array.Copy(data, start, buffername, 0, buffername.Length); start += buffername.Length; if (BitConverter.IsLittleEndian) { buffername = SwapEndian(buffername); } switch (type.Name) { case "Int32": msgvalue = BitConverter.ToInt32(buffername, 0); break; case "Int64": msgvalue = BitConverter.ToInt64(buffername, 0); break; case "Single": msgvalue = BitConverter.ToSingle(buffername, 0); break; case "Double": msgvalue = BitConverter.ToDouble(buffername, 0); break; default: throw new Exception("Unsupported data type."); } } return (T)msgvalue; } /// <summary> /// Unpacks an array of binary data. /// </summary> /// <param name="data"> /// A <see cref="System.Byte[]"/> /// </param> /// <returns> /// A <see cref="OSCPacket"/> /// </returns> public static OSCPacket Unpack(byte[] data) { int start = 0; return Unpack(data, ref start, data.Length); } /// <summary> /// Unpacks an array of binary data given reference start and end pointers. /// </summary> /// <param name="data"> /// A <see cref="System.Byte[]"/> /// </param> /// <param name="start"> /// A <see cref="System.Int32"/> /// </param> /// <param name="end"> /// A <see cref="System.Int32"/> /// </param> /// <returns> /// A <see cref="OSCPacket"/> /// </returns> public static OSCPacket Unpack(byte[] data, ref int start, int end) { if (data[start] == '#') { return OSCBundle.Unpack(data, ref start, end); } else return OSCMessage.Unpack(data, ref start); } /// <summary> /// Pads null a list of bytes. /// </summary> /// <param name="data"> /// A <see cref="List<System.Byte>"/> /// </param> protected static void PadNull(List<byte> data) { byte nullvalue = 0; int pad = 4 - (data.Count % 4); for(int i = 0; i < pad; i++) data.Add(nullvalue); } #endregion } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; using Dapper; using Microsoft.Extensions.Configuration; using TeamBins.Common.ViewModels; namespace TeamBins.DataAccessCore { public interface IUserRepository { Task<IEnumerable<TeamDto>> GetTeams(int userId); Task<UserAccountDto> GetUser(int id); Task<UserAccountDto> GetUser(string email); Task SetDefaultTeam(int userId, int teamId); Task SaveUserProfile(EditProfileVm userProfileVm); Task SaveDefaultIssueSettings(DefaultIssueSettings model); Task<int> CreateAccount(UserAccountDto userAccount); Task<IEnumerable<EmailSubscriptionVM>> EmailSubscriptions(int userId, int teamId); Task SaveNotificationSettings(UserEmailNotificationSettingsVM model); Task UpdateLastLoginTime(int userId); Task SavePasswordResetRequest(PasswordResetRequest passwordResetRequest); Task<PasswordResetRequest> GetPasswordResetRequest(string activationCode); Task UpdatePassword(string password,byte[] salt, int userId); Task<IEnumerable<UserDto>> GetAllUsers(); } public class UserRepository : BaseRepo, IUserRepository { public UserRepository(IConfiguration configuration) : base(configuration) { } public async Task SetDefaultTeam(int userId, int teamId) { var q = @"UPDATE [User] SET DefaultTeamId=@teamId WHERE ID=@userId"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); await con.ExecuteAsync(q, new { @userId = userId, @teamId = teamId }); } } public async Task SaveDefaultIssueSettings(DefaultIssueSettings model) { using (var con = new SqlConnection(ConnectionString)) { con.Open(); con.Query<int>("UPDATE TEAMMEMBER SET DEFAULTPROJECTID=@projectId WHERE TEAMID=@teamId AND MEMBERID=@userId", new { @projectId = model.SelectedProject.Value, @teamId = model.TeamId, @userId = model.UserId }); } } public async Task<UserAccountDto> GetUser(string email) { var q = @"SELECT [ID],[FirstName] as Name ,[EmailAddress],Password,Salt,[Avatar] as GravatarUrl ,[DefaultTeamID] FROM [dbo].[User] WHERE EmailAddress=@id"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); var com = await con.QueryAsync<UserAccountDto>(q, new { @id = email }); return com.FirstOrDefault(); } } public async Task UpdateLastLoginTime(int userId) { var q = @"UPDATE [User] SET LastLoginDate=@date WHERE Id=@userId"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); var com = await con.ExecuteAsync(q, new { @date = DateTime.UtcNow,userId }); } } public async Task<UserAccountDto> GetUser(int id) { var q = @"SELECT [ID] ,[FirstName] as Name ,[EmailAddress] ,[Avatar] as GravatarUrl ,[DefaultTeamID] FROM [dbo].[User] WHERE Id=@id"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); var com = await con.QueryAsync<UserAccountDto>(q, new { @id = id }); return com.FirstOrDefault(); } } public async Task UpdatePassword(string password,byte[] salt, int userId) { var q = @"UPDATE [User] SET Password=@password, Salt=@salt WHERE ID=@userId"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); await con.ExecuteAsync(q, new { password,salt, userId }); } } public async Task<IEnumerable<UserDto>> GetAllUsers() { var q = @"SELECT [ID],[FirstName] as Name ,[EmailAddress],[Avatar] as GravatarUrl ,[DefaultTeamID],LastLoginDate,CreatedDate FROM [dbo].[User] WITH (NOLOCK) ORDER BY CreatedDate desc"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); return await con.QueryAsync<UserAccountDto>(q); } } public async Task SaveUserProfile(EditProfileVm userProfileVm) { var q = @"UPDATE [User] SET FirstName=@name WHERE ID=@userId"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); await con.ExecuteAsync(q, new { @userId = userProfileVm.Id, @name = userProfileVm.Name }); } } public async Task<IEnumerable<TeamDto>> GetTeams(int userId) { var q = @"SELECT T.ID,T.Name FROM [dbo].[TeamMember] TM INNER JOIN TEAM T ON TM.TeamId=T.ID WHERE TM.MemberID=@id"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); return await con.QueryAsync<TeamDto>(q, new { @id = userId }); } } public async Task<int> CreateAccount(UserAccountDto userAccount) { var q = @"INSERT INTO [dbo].[User](FirstName,EmailAddress,Password,Salt,CreatedDate) VALUES(@n,@e,@p,@s,@dt);SELECT CAST(SCOPE_IDENTITY() as int)"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); var ss = await con.QueryAsync<int> (q, new { @n = userAccount.Name, @e = userAccount.EmailAddress, @p = userAccount.Password, @s= userAccount.Salt, @dt = DateTime.Now }); return ss.Single(); } } public async Task<IEnumerable<EmailSubscriptionVM>> EmailSubscriptions(int userId, int teamId) { var q = @"SELECT NT.ID as NotificationTypeId ,[Code] ,[Name], ISNULL(UNS.Subscribed,0) as IsSelected FROM [dbo].[NotificationType] NT WITH (NOLOCK) LEFT JOIN UserNotificationSubscription UNS WITH (NOLOCK) ON NT.ID=UNS.NotificationTypeID AND UNS.UserID=@userId and UNS.TeamId=@teamId"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); return await con.QueryAsync<EmailSubscriptionVM>(q, new { userId, teamId }); } } public async Task<PasswordResetRequest> GetPasswordResetRequest(string activationCode) { var q = @"SELECT PR.[ID],[UserID] ,[ActivationCode], U.Id, U.FirstName Name FROM [dbo].[PasswordResetRequest] PR WITH (NOLOCK) JOIN dbo.[User] U WITH (NOLOCK) ON U.ID =Pr.ID WHERE PR.ActivationCode=@activationCode"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); var com = await con.QueryAsync<PasswordResetRequest>(q, new { activationCode }); return com.FirstOrDefault(); } } public async Task SavePasswordResetRequest(PasswordResetRequest passwordResetRequest) { const string q = @"INSERT INTO [dbo].[PasswordResetRequest](UserId,ActivationCode,CreatedDate) VALUES(@UserId,@ActivationCode,@CreatedDate)"; passwordResetRequest.CreatedDate = DateTime.UtcNow; using (var con = new SqlConnection(ConnectionString)) { await con.ExecuteAsync(q,passwordResetRequest); } } public async Task SaveNotificationSettings(UserEmailNotificationSettingsVM model) { //DELETE EXISTING var q = @"DELETE FROM UserNotificationSubscription WHERE UserId=@userId and TeamId=@teamId;"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); await con.ExecuteAsync(q, new { @userId = model.UserId, @teamId = model.TeamId }); } //Insert new foreach (var setting in model.EmailSubscriptions.Where(s => s.IsSelected)) { var q2 = @"INSERT INTO UserNotificationSubscription(UserID,NotificationTypeID,TeamId,Subscribed,ModifiedDate) VALUES (@userId,@notificationTypeId,@teamId,@subscibed,@dt)"; using (var con = new SqlConnection(ConnectionString)) { con.Open(); await con.ExecuteAsync(q2, new { @userId = model.UserId, @subscibed = true, @notificationTypeId = setting.NotificationTypeId, @dt = DateTime.Now, @teamId = model.TeamId }); } } } } }
using System; using System.ComponentModel; using System.Drawing.Design; using System.IO; using System.Xml.Serialization; using CslaGenerator.Attributes; using CslaGenerator.Design; namespace CslaGenerator.Metadata { public delegate void ChildPropertyNameChanged(ChildProperty sender, PropertyNameChangedEventArgs e); /// <summary> /// Summary description for ChildProperty. /// </summary> [Serializable] public class ChildProperty : Property, IHaveBusinessRules, IComparable { #region Private Fields private string _friendlyName = String.Empty; private LoadingScheme _loadingScheme = LoadingScheme.ParentLoad; private PropertyDeclaration _declarationMode; private string _interfaces = string.Empty; private readonly BusinessRuleCollection _businessRules; private string[] _attributes = {}; private AuthorizationProvider _authzProvider; private readonly AuthorizationRuleCollection _authzRules; private string _readRoles = string.Empty; private string _writeRoles = string.Empty; private bool _lazyLoad; private string _typeName = String.Empty; private bool _undoable = true; private PropertyCollection _parentLoadProperties = new PropertyCollection(); private ParameterCollection _loadParameters = new ParameterCollection(); private PropertyAccess _access = PropertyAccess.IsPublic; private int _childUpdateOrder; private bool _isCollection; #endregion #region Constructor public ChildProperty() { _businessRules = new BusinessRuleCollection(); NameChanged += _businessRules.OnParentChanged; _authzRules = new AuthorizationRuleCollection(); _authzRules.Add(new AuthorizationRule()); _authzRules.Add(new AuthorizationRule()); NameChanged += _authzRules.OnParentChanged; } #endregion #region 01. Definition [Category("01. Definition")] [Description("The property name.")] public override string Name { get { return base.Name; } set { value = PropertyHelper.Tidy(value); var e = new PropertyNameChangedEventArgs(base.Name, value); base.Name = value; if (NameChanged != null) NameChanged(this, e); } } [Category("01. Definition")] [Description("Human readable friendly display name of the property.")] [UserFriendlyName("Friendly Name")] public string FriendlyName { get { if (string.IsNullOrEmpty(_friendlyName)) return PropertyHelper.SplitOnCaps(base.Name); return _friendlyName; } set { if (value != null && !value.Equals(PropertyHelper.SplitOnCaps(base.Name))) _friendlyName = value; else _friendlyName = string.Empty; } } [Category("01. Definition")] [Description("This is a description.")] [Editor(typeof(ChildTypeEditor), typeof(UITypeEditor))] [UserFriendlyName("Type Name")] public string TypeName { get { return _typeName; } set { _typeName = value; } } [Category("01. Definition")] [Description("Property Declaration Mode. For child collections this must be \"ClassicProperty\", \"AutoProperty\" or \"Managed\".\r\n" + "For lazy loaded child collections this must be \"ClassicProperty\" or \"Managed\".")] [UserFriendlyName("Declaration Mode")] public PropertyDeclaration DeclarationMode { get { return _declarationMode; } set { if (LoadingScheme == LoadingScheme.SelfLoad && LazyLoad) { if (value == PropertyDeclaration.ClassicProperty || value == PropertyDeclaration.Managed) _declarationMode = value; } else if (value == PropertyDeclaration.ClassicProperty || value == PropertyDeclaration.AutoProperty || value == PropertyDeclaration.Managed) _declarationMode = value; } } [Category("01. Definition")] [Description("Whether this property can be changed by other classes.")] public override bool ReadOnly { get { return base.ReadOnly; } set { base.ReadOnly = value; } } [Category("01. Definition")] [Description("Specify the order in which the child updates occur. Set to 0 on all chilren to ignore it.")] [UserFriendlyName("Child Update Order")] public int ChildUpdateOrder { get { return _childUpdateOrder; } set { _childUpdateOrder = value; } } #endregion #region 02. Advanced [Category("02. Advanced")] [Description("The attributes you want to add to this property.")] public virtual string[] Attributes { get { return _attributes; } set { _attributes = PropertyHelper.TidyAllowSpaces(value); } } [Category("02. Advanced")] [Description("The interface this property explicitly implements.")] public virtual string Interfaces { get { return _interfaces; } set { value = PropertyHelper.Tidy(value); if (!string.IsNullOrEmpty(value)) { var namePostfix = '.' + Name; if (value.LastIndexOf(namePostfix, StringComparison.Ordinal) != value.Length - namePostfix.Length) { if (GeneratorController.Current.CurrentUnit != null) { if (GeneratorController.Current.CurrentUnit.GenerationParams.OutputLanguage == CodeLanguage.CSharp || _interfaces == string.Empty) value = value + namePostfix; } } } _interfaces = value; } } #endregion #region 03. Business Rules & Authorization [Category("03. Business Rules & Authorization")] [Description("Collection of business rules (transformation, validation, etc).")] [Editor(typeof(PropertyCollectionForm), typeof(UITypeEditor))] [UserFriendlyName("Business Rules Collection")] public virtual BusinessRuleCollection BusinessRules { get { return _businessRules; } } [Category("03. Business Rules & Authorization")] [Description("The Authorization Provider for this property.")] [UserFriendlyName("Authorization Provider")] public virtual AuthorizationProvider AuthzProvider { get { return _authzProvider; } set { _authzProvider = value; } } [Category("03. Business Rules & Authorization")] [Description("Roles allowed to read the property. Use a comma to separate multiple roles.")] [UserFriendlyName("Read Roles")] public virtual string ReadRoles { get { return _readRoles; } set { _readRoles = PropertyHelper.TidyAllowSpaces(value).Replace(';', ',').Trim(new[] {','}); } } [Category("03. Business Rules & Authorization")] [Description("Roles allowed to write to the property. Use a comma to separate multiple roles.")] [UserFriendlyName("Write Roles")] public virtual string WriteRoles { get { return _writeRoles; } set { _writeRoles = PropertyHelper.TidyAllowSpaces(value).Replace(';', ',').Trim(new[] {','}); } } [Category("03. Business Rules & Authorization")] [Description("The Authorization Type that controls read action. You can either select an object defined in the current project or an object defined in another assembly.")] [Editor(typeof(ObjectEditor), typeof(UITypeEditor))] [TypeConverter(typeof(AuthorizationRuleTypeConverter))] [UserFriendlyName("Read Authorization Type")] public virtual AuthorizationRule ReadAuthzRuleType { get { return _authzRules[0]; } set { if (!ReferenceEquals(value, _authzRules[0])) { if (_authzRules[0] != null) { _authzRules[0] = value; _authzRules[0].Parent = Name; } } } } [Category("03. Business Rules & Authorization")] [Description("The Authorization Type that controls write action. You can either select an object defined in the current project or an object defined in another assembly.")] [Editor(typeof(ObjectEditor), typeof(UITypeEditor))] [TypeConverter(typeof(AuthorizationRuleTypeConverter))] [UserFriendlyName("Write Authorization Type")] public virtual AuthorizationRule WriteAuthzRuleType { get { return _authzRules[1]; } set { if (!ReferenceEquals(value, _authzRules[1])) { if (_authzRules[1] != null) { _authzRules[1] = value; _authzRules[1].Parent = Name; } } } } #endregion #region 05. Options [Category("05. Options")] [Description("The Loading Scheme for the child." + "If set to ParentLoad, data for both the parent and the child will be fetched at the same time. " + "If set to SelfLoad, the child will fetch its own data. " + "None option is discontinued and the setting will be reset to ParentLoad.")] [UserFriendlyName("Loading Scheme")] public LoadingScheme LoadingScheme { get { if (_loadingScheme == LoadingScheme.None) return LoadingScheme.ParentLoad; return _loadingScheme; } set { _loadingScheme = value; } } [Category("05. Options")] [Description("Whether or not this object should be lazy loaded.\r\n" + "If Loading Scheme is set to ParentLoad, Lazy Load is forced to False.\r\n" + "If set to True, loading of child data is defered until the child object is referenced.\r\n" + "If set to False, the child data is loaded when the parent is instantiated.")] [UserFriendlyName("Lazy Load")] public bool LazyLoad { get { if (_loadingScheme == LoadingScheme.SelfLoad) return _lazyLoad; return false; } set { _lazyLoad = value; } } [Category("05. Options")] [Description("The parent properties that are used to load the child object.")] [Editor(typeof(PropertyCollectionEditor), typeof(UITypeEditor))] [TypeConverter(typeof(PropertyCollectionConverter))] [UserFriendlyName("Parent Properties")] public PropertyCollection ParentLoadProperties { get { return _parentLoadProperties; } set { _parentLoadProperties = value; } } [Category("05. Options")] [Editor(typeof(ParameterCollectionEditor), typeof(UITypeEditor))] [TypeConverter(typeof(ParameterCollectionConverter))] [Description("The parent get criteria parameters that are used to load the child object.")] [UserFriendlyName("Parent Criteria Parameters")] public ParameterCollection LoadParameters { get { return _loadParameters; } set { _loadParameters = value; } } [Category("05. Options")] [Description("Accessibility for the property as a whole.\r\nDefaults to IsPublic.")] [UserFriendlyName("Property Accessibility")] public PropertyAccess Access { get { return _access; } set { _access = value; } } [Category("05. Options")] [Description("Setting to false will cause the n-level undo process to ignore that property's value.")] public bool Undoable { get { return _undoable; } set { _undoable = value; } } #endregion #region Hidden Properties [Browsable(false)] [XmlIgnore] public bool IsCollection { get { return _isCollection; } internal set { _isCollection = value; } } [Browsable(false)] public override TypeCodeEx PropertyType { get { return TypeCodeEx.Empty; } } [Browsable(false)] public override bool Nullable { get { return base.Nullable; } } #endregion [field: NonSerialized] public event ChildPropertyNameChanged NameChanged; public override object Clone() { using (var buffer = new MemoryStream()) { var ser = new XmlSerializer(typeof(ChildProperty)); ser.Serialize(buffer, this); buffer.Position = 0; return ser.Deserialize(buffer); } } public int CompareTo(object other) { return ChildUpdateOrder.CompareTo(((ChildProperty) other).ChildUpdateOrder); } } }
using System.Collections.Generic; using BlackBox.Service; using IFC2X3; using EbInstanceModel; namespace BlackBox.Predefined { /// <summary> /// Weld. /// </summary> public class BbWeld : BbFastener { IfcFastener _ifcElement; [EarlyBindingInstance] public override IfcObject IfcObject { get { return _ifcElement; } protected set { base.IfcObject = _ifcElement = value as IfcFastener; } } public BbElement MainElement { get; private set; } public BbElement AttachedElement { get; private set; } public BbPropertySet BbPropertySet { get; private set; } private BbCurveGeometry _weldingPath; public BbCurveGeometry WeldingPath { get { return _weldingPath; } private set { _weldingPath = value; _ifcElement.Representation = _weldingPath.IfcProductDefinitionShape; } } BbWeld(BbElement mainElement, BbElement attachedElement) { _ifcElement = new IfcFastener { GlobalId = IfcGloballyUniqueId.NewGuid(), OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory, ObjectType = "Weld", }; MainElement = mainElement; AttachedElement = attachedElement; IfcRelConnectsElements = new IfcRelConnectsWithRealizingElements { GlobalId = IfcGloballyUniqueId.NewGuid(), OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory, RelatingElement = MainElement.IfcObject as IfcElement, RelatedElement = AttachedElement.IfcObject as IfcElement, RealizingElements = new List<IfcElement> { _ifcElement }, }; } private BbWeld() { } public static BbWeld Create(BbElement mainElement, BbElement attchedElement) { var weld = new BbWeld(mainElement, attchedElement); BbInstanceDB.AddToExport(weld); return weld; } public static ICollection<BbWeld> Retrieve(BbElement mainPiece) { var ret = new List<BbWeld>(); //if (!EarlyBindingInstanceModel.TheModel.DataByType.ContainsKey("IfcRelConnectsWithRealizingElements")) return null; var collection = EarlyBindingInstanceModel.GetDataByType("IfcRelConnectsWithRealizingElements").Values; foreach (var theItem in collection) { var rel = theItem as IfcRelConnectsWithRealizingElements; if (rel == null) continue; if (rel.RelatingElement.EIN == mainPiece.IfcObject.EIN) { //if (!EarlyBindingInstanceModel.TheModel.DataByType.ContainsKey("IfcFastener")) return null; var collection1 = EarlyBindingInstanceModel.GetDataByType("IfcFastener").Values; foreach (var item in collection1) { var relElements = rel.RealizingElements; foreach (var relElement in relElements) { if (relElement.EIN == item.EIN) { var fastener = item as IfcFastener; if (fastener == null) continue; var weld = new BbWeld { _ifcElement = fastener, IfcRelConnectsElements = rel }; //BbInstanceDB.Add(weld); ret.Add(weld); // Retrieve MainElement weld.MainElement = mainPiece; // Retrieve AttachedElement var relatedElement = weld.IfcRelConnectsElements.RelatedElement as IfcElement; // wrong implementation, need to revise, donghoon 20131205 //weld.AttachedElement = new BbElement { IfcElement = relatedElement }; } } } } } return ret; } public void AddWeldingPath(BbCurveGeometry weldingPath, BbCoordinate3D position) { WeldingPath = weldingPath; var pos = BbPosition3D.Create(position, BbHeaderSetting.Setting3D.ZAxis, BbHeaderSetting.Setting3D.XAxis); ObjectBbLocalPlacement = BbLocalPlacement3D.Create( MainElement.ObjectBbLocalPlacement, pos); _ifcElement.ObjectPlacement = ObjectBbLocalPlacement.IfcLocalPlacement; } public double WeldThickness { get; set; } public double WeldLegSize { get; set; } public double WeldThroatSize { get; set; } public List<string> WeldGrade { get { return _weldGrade; } } private readonly List<string> _weldGrade = new List<string>(); public string WeldID { get; set; } public string WeldDescription { get; set; } public string WPSCode { get; set; } public string WeldCategory { get; set; } public double WeldLength { get; set; } public bool FieldWeld { get; set; } public string WeldType1 { get; set; } public string WeldType2 { get; set; } public string WeldSurface1 { get; set; } public string WeldSurface2 { get; set; } public int WeldProcess { get; set; } public string WeldProcessName { get; set; } public double WeldA { get; set; } public double WeldC { get; set; } public double WeldD { get; set; } public double WeldE { get; set; } public double WeldL { get; set; } public double WeldN { get; set; } public double WeldS { get; set; } public double WeldZ { get; set; } public bool WeldIntermittent { get; set; } public bool WeldStaggered { get; set; } public void AddProperties( BbPropertySet bbPropertySet, string weldId, string weldDescription, string wpsCode, string weldCategory, string weldGrade, double? weldLength, bool? fieldWeld) { if (BbPropertySet == null) BbPropertySet = bbPropertySet; if (!string.IsNullOrWhiteSpace(weldId)) { WeldID = weldId; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldID", WeldID, true)); } if (!string.IsNullOrWhiteSpace(weldDescription)) { WeldDescription = weldDescription; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldDescription", WeldDescription, true)); } if (!string.IsNullOrWhiteSpace(wpsCode)) { WPSCode = wpsCode; bbPropertySet.AddProperty(BbSingleProperty.Create("WPSCode", WPSCode, true)); } if (!string.IsNullOrWhiteSpace(weldCategory)) { WeldCategory = weldCategory; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldCategory", WeldCategory, true)); } if (!string.IsNullOrEmpty(weldGrade)) { WeldGrade.Add(weldGrade); bbPropertySet.AddProperty(BbListProperty.Create("WeldGrade", weldGrade, typeof(IfcLabel))); } if (weldLength != null) { WeldLength = weldLength.Value; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldLength", WeldLength, typeof(IfcPositiveLengthMeasure))); } else { WeldLength = 0.0; } if (fieldWeld != null) { FieldWeld = fieldWeld.Value; bbPropertySet.AddProperty(BbSingleProperty.Create("FieldWeld", FieldWeld)); } else { WeldLength = 0.0; } } public void AddProperties( BbPropertySet bbPropertySet, string weldType1, string weldType2, string weldSurface1, string weldSurface2, int? weldProcess, string weldProcessName, double? weldA, double? weldC, double? weldD, double? weldE, double? weldL, double? weldN, double? weldS, double? weldZ, bool? weldIntermittent, bool? weldStaggered) { if (BbPropertySet == null) BbPropertySet = bbPropertySet; if (!string.IsNullOrWhiteSpace(weldType1)) { WeldType1 = weldType1; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldType1", WeldType1, true)); } if (!string.IsNullOrWhiteSpace(weldType2)) { WeldType2 = weldType2; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldType2", WeldType2, true)); } if (!string.IsNullOrWhiteSpace(weldSurface1)) { WeldSurface1 = weldSurface1; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldSurface1", WeldSurface1, true)); } if (!string.IsNullOrWhiteSpace(weldSurface2)) { WeldSurface2 = weldSurface2; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldSurface2", WeldSurface2, true)); } if (weldProcess != null) { WeldProcess = weldProcess.Value; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldProcess", WeldProcess, typeof(IfcInteger))); } else { WeldProcess = 0; } if (!string.IsNullOrWhiteSpace(weldProcessName)) { WeldProcessName = weldProcessName; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldProcessName", WeldProcessName, true)); } if (weldA != null) { WeldA = weldA.Value; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldA", WeldA, typeof(IfcPositiveLengthMeasure))); } else { WeldA = 0.0; } if (weldC != null) { WeldC = weldC.Value; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldC", WeldC, typeof(IfcPositiveLengthMeasure))); } else { WeldC = 0.0; } if (weldD != null) { WeldD = weldD.Value; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldD", WeldD, typeof(IfcPositiveLengthMeasure))); } else { WeldD = 0.0; } if (weldE != null) { WeldE = weldE.Value; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldE", WeldE, typeof(IfcPositiveLengthMeasure))); } else { WeldE = 0.0; } if (weldL != null) { WeldL = weldL.Value; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldL", WeldL, typeof(IfcPositiveLengthMeasure))); } else { WeldL = 0.0; } if (weldN != null) { WeldN = weldN.Value; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldN", WeldN, typeof(IfcPositiveLengthMeasure))); } else { WeldN = 0.0; } if (weldS != null) { WeldS = weldS.Value; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldS", WeldN, typeof(IfcPositiveLengthMeasure))); } else { WeldS = 0.0; } if (weldZ != null) { WeldZ = weldZ.Value; bbPropertySet.AddProperty(BbSingleProperty.Create("WeldZ", WeldZ, typeof(IfcPositiveLengthMeasure))); } else { WeldZ = 0.0; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Concurrent; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using Microsoft.Extensions.Internal; #nullable enable namespace Microsoft.AspNetCore.Http { internal sealed class ParameterBindingMethodCache { private static readonly MethodInfo ConvertValueTaskMethod = typeof(ParameterBindingMethodCache).GetMethod(nameof(ConvertValueTask), BindingFlags.NonPublic | BindingFlags.Static)!; private static readonly MethodInfo ConvertValueTaskOfNullableResultMethod = typeof(ParameterBindingMethodCache).GetMethod(nameof(ConvertValueTaskOfNullableResult), BindingFlags.NonPublic | BindingFlags.Static)!; internal static readonly ParameterExpression TempSourceStringExpr = Expression.Variable(typeof(string), "tempSourceString"); internal static readonly ParameterExpression HttpContextExpr = Expression.Parameter(typeof(HttpContext), "httpContext"); private readonly MethodInfo _enumTryParseMethod; // Since this is shared source, the cache won't be shared between RequestDelegateFactory and the ApiDescriptionProvider sadly :( private readonly ConcurrentDictionary<Type, Func<ParameterExpression, Expression>?> _stringMethodCallCache = new(); private readonly ConcurrentDictionary<Type, (Func<ParameterInfo, Expression>?, int)> _bindAsyncMethodCallCache = new(); // If IsDynamicCodeSupported is false, we can't use the static Enum.TryParse<T> since there's no easy way for // this code to generate the specific instantiation for any enums used public ParameterBindingMethodCache() : this(preferNonGenericEnumParseOverload: !RuntimeFeature.IsDynamicCodeSupported) { } // This is for testing public ParameterBindingMethodCache(bool preferNonGenericEnumParseOverload) { _enumTryParseMethod = GetEnumTryParseMethod(preferNonGenericEnumParseOverload); } public bool HasTryParseMethod(ParameterInfo parameter) { var nonNullableParameterType = Nullable.GetUnderlyingType(parameter.ParameterType) ?? parameter.ParameterType; return FindTryParseMethod(nonNullableParameterType) is not null; } public bool HasBindAsyncMethod(ParameterInfo parameter) => FindBindAsyncMethod(parameter).Expression is not null; public Func<ParameterExpression, Expression>? FindTryParseMethod(Type type) { Func<ParameterExpression, Expression>? Finder(Type type) { MethodInfo? methodInfo; if (type.IsEnum) { if (_enumTryParseMethod.IsGenericMethod) { methodInfo = _enumTryParseMethod.MakeGenericMethod(type); return (expression) => Expression.Call(methodInfo!, TempSourceStringExpr, expression); } return (expression) => { var enumAsObject = Expression.Variable(typeof(object), "enumAsObject"); var success = Expression.Variable(typeof(bool), "success"); // object enumAsObject; // bool success; // success = Enum.TryParse(type, tempSourceString, out enumAsObject); // parsedValue = success ? (Type)enumAsObject : default; // return success; return Expression.Block(new[] { success, enumAsObject }, Expression.Assign(success, Expression.Call(_enumTryParseMethod, Expression.Constant(type), TempSourceStringExpr, enumAsObject)), Expression.Assign(expression, Expression.Condition(success, Expression.Convert(enumAsObject, type), Expression.Default(type))), success); }; } if (TryGetDateTimeTryParseMethod(type, out methodInfo)) { // We generate `DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces ` to // support parsing types into the UTC timezone for DateTime. We don't assume the timezone // on the original value which will cause the parser to set the `Kind` property on the // `DateTime` as `Unspecified` indicating that it was parsed from an ambiguous timezone. // // `DateTimeOffset`s are always in UTC and don't allow specifying an `Unspecific` kind. // For this, we always assume that the original value is already in UTC to avoid resolving // the offset incorrectly depending on the timezone of the machine. We don't bother mapping // it to UTC in this case. In the event that the original timestamp is not in UTC, it's offset // value will be maintained. // // DateOnly and TimeOnly types do not support conversion to Utc so we // default to `DateTimeStyles.AllowWhiteSpaces`. var dateTimeStyles = type switch { Type t when t == typeof(DateTime) => DateTimeStyles.AdjustToUniversal | DateTimeStyles.AllowWhiteSpaces, Type t when t == typeof(DateTimeOffset) => DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowWhiteSpaces, _ => DateTimeStyles.AllowWhiteSpaces }; return (expression) => Expression.Call( methodInfo!, TempSourceStringExpr, Expression.Constant(CultureInfo.InvariantCulture), Expression.Constant(dateTimeStyles), expression); } if (TryGetNumberStylesTryGetMethod(type, out methodInfo, out var numberStyle)) { return (expression) => Expression.Call( methodInfo!, TempSourceStringExpr, Expression.Constant(numberStyle), Expression.Constant(CultureInfo.InvariantCulture), expression); } methodInfo = GetStaticMethodFromHierarchy(type, "TryParse", new[] { typeof(string), typeof(IFormatProvider), type.MakeByRefType() }, ValidateReturnType); if (methodInfo is not null) { return (expression) => Expression.Call( methodInfo, TempSourceStringExpr, Expression.Constant(CultureInfo.InvariantCulture), expression); } methodInfo = GetStaticMethodFromHierarchy(type, "TryParse", new[] { typeof(string), type.MakeByRefType() }, ValidateReturnType); if (methodInfo is not null) { return (expression) => Expression.Call(methodInfo, TempSourceStringExpr, expression); } if (GetAnyMethodFromHierarchy(type, "TryParse") is MethodInfo invalidMethod) { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine(CultureInfo.InvariantCulture, $"TryParse method found on {TypeNameHelper.GetTypeDisplayName(type, fullName: false)} with incorrect format. Must be a static method with format"); stringBuilder.AppendLine(CultureInfo.InvariantCulture, $"bool TryParse(string, IFormatProvider, out {TypeNameHelper.GetTypeDisplayName(type, fullName: false)})"); stringBuilder.AppendLine(CultureInfo.InvariantCulture, $"bool TryParse(string, out {TypeNameHelper.GetTypeDisplayName(type, fullName: false)})"); stringBuilder.AppendLine("but found"); stringBuilder.Append(invalidMethod.IsStatic ? "static " : "not-static "); stringBuilder.Append(invalidMethod.ToString()); throw new InvalidOperationException(stringBuilder.ToString()); } return null; static bool ValidateReturnType(MethodInfo methodInfo) { return methodInfo.ReturnType.Equals(typeof(bool)); } } return _stringMethodCallCache.GetOrAdd(type, Finder); } public (Expression? Expression, int ParamCount) FindBindAsyncMethod(ParameterInfo parameter) { static (Func<ParameterInfo, Expression>?, int) Finder(Type nonNullableParameterType) { var hasParameterInfo = true; // There should only be one BindAsync method with these parameters since C# does not allow overloading on return type. var methodInfo = GetStaticMethodFromHierarchy(nonNullableParameterType, "BindAsync", new[] { typeof(HttpContext), typeof(ParameterInfo) }, ValidateReturnType); if (methodInfo is null) { hasParameterInfo = false; methodInfo = GetStaticMethodFromHierarchy(nonNullableParameterType, "BindAsync", new[] { typeof(HttpContext) }, ValidateReturnType); } // We're looking for a method with the following signatures: // public static ValueTask<{type}> BindAsync(HttpContext context, ParameterInfo parameter) // public static ValueTask<Nullable<{type}>> BindAsync(HttpContext context, ParameterInfo parameter) if (methodInfo is not null) { var valueTaskResultType = methodInfo.ReturnType.GetGenericArguments()[0]; // ValueTask<{type}>? if (valueTaskResultType == nonNullableParameterType) { return ((parameter) => { MethodCallExpression typedCall; if (hasParameterInfo) { // parameter is being intentionally shadowed. We never want to use the outer ParameterInfo inside // this Func because the ParameterInfo varies after it's been cached for a given parameter type. typedCall = Expression.Call(methodInfo, HttpContextExpr, Expression.Constant(parameter)); } else { typedCall = Expression.Call(methodInfo, HttpContextExpr); } return Expression.Call(ConvertValueTaskMethod.MakeGenericMethod(nonNullableParameterType), typedCall); }, hasParameterInfo ? 2 : 1); } // ValueTask<Nullable<{type}>>? else if (valueTaskResultType.IsGenericType && valueTaskResultType.GetGenericTypeDefinition() == typeof(Nullable<>) && valueTaskResultType.GetGenericArguments()[0] == nonNullableParameterType) { return ((parameter) => { MethodCallExpression typedCall; if (hasParameterInfo) { // parameter is being intentionally shadowed. We never want to use the outer ParameterInfo inside // this Func because the ParameterInfo varies after it's been cached for a given parameter type. typedCall = Expression.Call(methodInfo, HttpContextExpr, Expression.Constant(parameter)); } else { typedCall = Expression.Call(methodInfo, HttpContextExpr); } return Expression.Call(ConvertValueTaskOfNullableResultMethod.MakeGenericMethod(nonNullableParameterType), typedCall); }, hasParameterInfo ? 2 : 1); } } if (GetAnyMethodFromHierarchy(nonNullableParameterType, "BindAsync") is MethodInfo invalidBindMethod) { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine(CultureInfo.InvariantCulture, $"BindAsync method found on {TypeNameHelper.GetTypeDisplayName(nonNullableParameterType, fullName: false)} with incorrect format. Must be a static method with format"); stringBuilder.AppendLine(CultureInfo.InvariantCulture, $"ValueTask<{TypeNameHelper.GetTypeDisplayName(nonNullableParameterType, fullName: false)}> BindAsync(HttpContext context, ParameterInfo parameter)"); stringBuilder.AppendLine(CultureInfo.InvariantCulture, $"ValueTask<{TypeNameHelper.GetTypeDisplayName(nonNullableParameterType, fullName: false)}> BindAsync(HttpContext context)"); stringBuilder.AppendLine(CultureInfo.InvariantCulture, $"ValueTask<{TypeNameHelper.GetTypeDisplayName(nonNullableParameterType, fullName: false)}?> BindAsync(HttpContext context, ParameterInfo parameter)"); stringBuilder.AppendLine(CultureInfo.InvariantCulture, $"ValueTask<{TypeNameHelper.GetTypeDisplayName(nonNullableParameterType, fullName: false)}?> BindAsync(HttpContext context)"); stringBuilder.AppendLine("but found"); stringBuilder.Append(invalidBindMethod.IsStatic ? "static " : "not-static"); stringBuilder.Append(invalidBindMethod.ToString()); throw new InvalidOperationException(stringBuilder.ToString()); } return (null, 0); } var nonNullableParameterType = Nullable.GetUnderlyingType(parameter.ParameterType) ?? parameter.ParameterType; var (method, paramCount) = _bindAsyncMethodCallCache.GetOrAdd(nonNullableParameterType, Finder); return (method?.Invoke(parameter), paramCount); static bool ValidateReturnType(MethodInfo methodInfo) { return methodInfo.ReturnType.IsGenericType && methodInfo.ReturnType.GetGenericTypeDefinition() == typeof(ValueTask<>); } } private static MethodInfo? GetStaticMethodFromHierarchy(Type type, string name, Type[] parameterTypes, Func<MethodInfo, bool> validateReturnType) { bool IsMatch(MethodInfo? method) => method is not null && !method.IsAbstract && validateReturnType(method); var methodInfo = type.GetMethod(name, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy, parameterTypes); if (IsMatch(methodInfo)) { return methodInfo; } var candidateInterfaceMethodInfo = default(MethodInfo); // Check all interfaces for implementations. Fail if there are duplicates. foreach (var implementedInterface in type.GetInterfaces()) { var interfaceMethod = implementedInterface.GetMethod(name, BindingFlags.Public | BindingFlags.Static, parameterTypes); if (IsMatch(interfaceMethod)) { if (candidateInterfaceMethodInfo is not null) { throw new InvalidOperationException($"{TypeNameHelper.GetTypeDisplayName(type, fullName: false)} implements multiple interfaces defining a static {interfaceMethod} method causing ambiguity."); } candidateInterfaceMethodInfo = interfaceMethod; } } return candidateInterfaceMethodInfo; } private static MethodInfo? GetAnyMethodFromHierarchy(Type type, string name) { // Find first incorrectly formatted method var methodInfo = type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy) .FirstOrDefault(methodInfo => methodInfo.Name == name); if (methodInfo is not null) { return methodInfo; } foreach (var implementedInterface in type.GetInterfaces()) { var interfaceMethod = implementedInterface.GetMethod(name, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); if (interfaceMethod is not null) { return interfaceMethod; } } return null; } private static MethodInfo GetEnumTryParseMethod(bool preferNonGenericEnumParseOverload) { MethodInfo? methodInfo = null; if (preferNonGenericEnumParseOverload) { methodInfo = typeof(Enum).GetMethod( nameof(Enum.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(Type), typeof(string), typeof(object).MakeByRefType() }); } else { methodInfo = typeof(Enum).GetMethod( nameof(Enum.TryParse), genericParameterCount: 1, new[] { typeof(string), Type.MakeGenericMethodParameter(0).MakeByRefType() }); } if (methodInfo is null) { Debug.Fail("No suitable System.Enum.TryParse method found."); throw new MissingMethodException("No suitable System.Enum.TryParse method found."); } return methodInfo!; } private static bool TryGetDateTimeTryParseMethod(Type type, [NotNullWhen(true)] out MethodInfo? methodInfo) { methodInfo = null; if (type == typeof(DateTime)) { methodInfo = typeof(DateTime).GetMethod( nameof(DateTime.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(IFormatProvider), typeof(DateTimeStyles), typeof(DateTime).MakeByRefType() }); } else if (type == typeof(DateTimeOffset)) { methodInfo = typeof(DateTimeOffset).GetMethod( nameof(DateTimeOffset.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(IFormatProvider), typeof(DateTimeStyles), typeof(DateTimeOffset).MakeByRefType() }); } else if (type == typeof(DateOnly)) { methodInfo = typeof(DateOnly).GetMethod( nameof(DateOnly.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(IFormatProvider), typeof(DateTimeStyles), typeof(DateOnly).MakeByRefType() }); } else if (type == typeof(TimeOnly)) { methodInfo = typeof(TimeOnly).GetMethod( nameof(TimeOnly.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(IFormatProvider), typeof(DateTimeStyles), typeof(TimeOnly).MakeByRefType() }); } return methodInfo != null; } private static bool TryGetNumberStylesTryGetMethod(Type type, [NotNullWhen(true)] out MethodInfo? method, [NotNullWhen(true)] out NumberStyles? numberStyles) { method = null; numberStyles = NumberStyles.Integer; if (type == typeof(long)) { method = typeof(long).GetMethod( nameof(long.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(long).MakeByRefType() }); } else if (type == typeof(ulong)) { method = typeof(ulong).GetMethod( nameof(ulong.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(ulong).MakeByRefType() }); } else if (type == typeof(int)) { method = typeof(int).GetMethod( nameof(int.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(int).MakeByRefType() }); } else if (type == typeof(uint)) { method = typeof(uint).GetMethod( nameof(uint.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(uint).MakeByRefType() }); } else if (type == typeof(short)) { method = typeof(short).GetMethod( nameof(short.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(short).MakeByRefType() }); } else if (type == typeof(ushort)) { method = typeof(ushort).GetMethod( nameof(ushort.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(ushort).MakeByRefType() }); } else if (type == typeof(byte)) { method = typeof(byte).GetMethod( nameof(byte.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(byte).MakeByRefType() }); } else if (type == typeof(sbyte)) { method = typeof(sbyte).GetMethod( nameof(sbyte.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(sbyte).MakeByRefType() }); } else if (type == typeof(double)) { method = typeof(double).GetMethod( nameof(double.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(double).MakeByRefType() }); numberStyles = NumberStyles.AllowThousands | NumberStyles.Float; } else if (type == typeof(float)) { method = typeof(float).GetMethod( nameof(float.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(float).MakeByRefType() }); numberStyles = NumberStyles.AllowThousands | NumberStyles.Float; } else if (type == typeof(Half)) { method = typeof(Half).GetMethod( nameof(Half.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(Half).MakeByRefType() }); numberStyles = NumberStyles.AllowThousands | NumberStyles.Float; } else if (type == typeof(decimal)) { method = typeof(decimal).GetMethod( nameof(decimal.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(decimal).MakeByRefType() }); numberStyles = NumberStyles.Number; } else if (type == typeof(IntPtr)) { method = typeof(IntPtr).GetMethod( nameof(IntPtr.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(IntPtr).MakeByRefType() }); } else if (type == typeof(BigInteger)) { method = typeof(BigInteger).GetMethod( nameof(BigInteger.TryParse), BindingFlags.Public | BindingFlags.Static, new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), typeof(BigInteger).MakeByRefType() }); } return method != null; } private static ValueTask<object?> ConvertValueTask<T>(ValueTask<T> typedValueTask) { if (typedValueTask.IsCompletedSuccessfully) { var result = typedValueTask.GetAwaiter().GetResult(); return new ValueTask<object?>(result); } static async ValueTask<object?> ConvertAwaited(ValueTask<T> typedValueTask) => await typedValueTask; return ConvertAwaited(typedValueTask); } private static ValueTask<object?> ConvertValueTaskOfNullableResult<T>(ValueTask<Nullable<T>> typedValueTask) where T : struct { if (typedValueTask.IsCompletedSuccessfully) { var result = typedValueTask.GetAwaiter().GetResult(); return new ValueTask<object?>(result); } static async ValueTask<object?> ConvertAwaited(ValueTask<Nullable<T>> typedValueTask) => await typedValueTask; return ConvertAwaited(typedValueTask); } } }
// ----------------------------------------------------------------------------------------- // <copyright file="ResourceBinder.cs" company="Microsoft"> // Copyright 2013 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- namespace Sandboxable.Microsoft.WindowsAzure.Storage.Table.Queryable { #region Namespaces. using Sandboxable.Microsoft.WindowsAzure.Storage.Core; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; #endregion Namespaces. internal class ResourceBinder : DataServiceALinqExpressionVisitor { internal static Expression Bind(Expression e) { Debug.Assert(e != null, "e != null"); ResourceBinder rb = new ResourceBinder(); Expression boundExpression = rb.Visit(e); VerifyKeyPredicates(boundExpression); VerifyNotSelectManyProjection(boundExpression); return boundExpression; } internal static bool IsMissingKeyPredicates(Expression expression) { ResourceExpression re = expression as ResourceExpression; if (re != null) { if (IsMissingKeyPredicates(re.Source)) { return true; } if (re.Source != null) { ResourceSetExpression rse = re.Source as ResourceSetExpression; if ((rse != null) && !rse.HasKeyPredicate) { return true; } } } return false; } internal static void VerifyKeyPredicates(Expression e) { if (IsMissingKeyPredicates(e)) { throw new NotSupportedException(SR.ALinqCantNavigateWithoutKeyPredicate); } } internal static void VerifyNotSelectManyProjection(Expression expression) { Debug.Assert(expression != null, "expression != null"); ResourceSetExpression resourceSet = expression as ResourceSetExpression; if (resourceSet != null) { ProjectionQueryOptionExpression projection = resourceSet.Projection; if (projection != null) { Debug.Assert(projection.Selector != null, "projection.Selector != null -- otherwise incorrectly constructed"); MethodCallExpression call = StripTo<MethodCallExpression>(projection.Selector.Body); if (call != null && call.Method.Name == "SelectMany") { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqUnsupportedExpression, call)); } } else if (resourceSet.HasTransparentScope) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqUnsupportedExpression, resourceSet)); } } } private static Expression AnalyzePredicate(MethodCallExpression mce) { Debug.Assert(mce != null, "mce != null -- caller couldn't have know the expression kind otherwise"); Debug.Assert(mce.Method.Name == "Where", "mce.Method.Name == 'Where' -- otherwise this isn't a predicate"); ResourceSetExpression input; LambdaExpression le; if (!TryGetResourceSetMethodArguments(mce, out input, out le)) { ValidationRules.RequireNonSingleton(mce.Arguments[0]); return mce; } List<Expression> conjuncts = new List<Expression>(); AddConjuncts(le.Body, conjuncts); Dictionary<ResourceSetExpression, List<Expression>> predicatesByTarget = new Dictionary<ResourceSetExpression, List<Expression>>(ReferenceEqualityComparer<ResourceSetExpression>.Instance); List<ResourceExpression> referencedInputs = new List<ResourceExpression>(); foreach (Expression e in conjuncts) { Expression reboundPredicate = InputBinder.Bind(e, input, le.Parameters[0], referencedInputs); if (referencedInputs.Count > 1) { return mce; } ResourceSetExpression boundTarget = referencedInputs.Count == 0 ? input : referencedInputs[0] as ResourceSetExpression; if (boundTarget == null) { return mce; } List<Expression> targetPredicates = null; if (!predicatesByTarget.TryGetValue(boundTarget, out targetPredicates)) { targetPredicates = new List<Expression>(); predicatesByTarget[boundTarget] = targetPredicates; } targetPredicates.Add(reboundPredicate); referencedInputs.Clear(); } conjuncts = null; List<Expression> inputPredicates; if (predicatesByTarget.TryGetValue(input, out inputPredicates)) { predicatesByTarget.Remove(input); } else { inputPredicates = null; } if (inputPredicates != null) { if (inputPredicates.Count > 0) { if (input.KeyPredicate != null) { Expression predicateFilter = BuildKeyPredicateFilter(input.CreateReference(), input.KeyPredicate); inputPredicates.Add(predicateFilter); input.KeyPredicate = null; } int start; Expression newFilter; if (input.Filter != null) { start = 0; newFilter = input.Filter.Predicate; } else { start = 1; newFilter = inputPredicates[0]; } for (int idx = start; idx < inputPredicates.Count; idx++) { newFilter = Expression.And(newFilter, inputPredicates[idx]); } AddSequenceQueryOption(input, new FilterQueryOptionExpression(mce.Method.ReturnType, newFilter)); } } return input; } private static Expression BuildKeyPredicateFilter(InputReferenceExpression input, Dictionary<PropertyInfo, ConstantExpression> keyValuesDictionary) { Debug.Assert(input != null, "input != null"); Debug.Assert(keyValuesDictionary != null, "keyValuesDictionary != null"); Debug.Assert(keyValuesDictionary.Count > 0, "At least one key property is required in a key predicate"); Expression retExpr = null; foreach (KeyValuePair<PropertyInfo, ConstantExpression> keyValue in keyValuesDictionary) { Expression clause = Expression.Equal(Expression.Property(input, keyValue.Key), keyValue.Value); if (retExpr == null) { retExpr = clause; } else { retExpr = Expression.And(retExpr, clause); } } return retExpr; } private static void AddConjuncts(Expression e, List<Expression> conjuncts) { Debug.Assert(conjuncts != null, "conjuncts != null"); if (PatternRules.MatchAnd(e)) { BinaryExpression be = (BinaryExpression)e; AddConjuncts(be.Left, conjuncts); AddConjuncts(be.Right, conjuncts); } else { conjuncts.Add(e); } } internal bool AnalyzeProjection(MethodCallExpression mce, SequenceMethod sequenceMethod, out Expression e) { Debug.Assert(mce != null, "mce != null"); Debug.Assert( sequenceMethod == SequenceMethod.Select || sequenceMethod == SequenceMethod.SelectManyResultSelector, "sequenceMethod == SequenceMethod.Select(ManyResultSelector)"); e = mce; bool matchMembers = true; // TODO is this right? -> this allows us to match a single property projection i.e. ent = ent.Prop // sequenceMethod == SequenceMethod.SelectManyResultSelector; ResourceExpression source = this.Visit(mce.Arguments[0]) as ResourceExpression; if (source == null) { return false; } if (sequenceMethod == SequenceMethod.SelectManyResultSelector) { Expression collectionSelector = mce.Arguments[1]; if (!PatternRules.MatchParameterMemberAccess(collectionSelector)) { return false; } Expression resultSelector = mce.Arguments[2]; LambdaExpression resultLambda; if (!PatternRules.MatchDoubleArgumentLambda(resultSelector, out resultLambda)) { return false; } if (ExpressionPresenceVisitor.IsExpressionPresent(resultLambda.Parameters[0], resultLambda.Body)) { return false; } List<ResourceExpression> referencedExpressions = new List<ResourceExpression>(); LambdaExpression collectionLambda = StripTo<LambdaExpression>(collectionSelector); Expression collectorReference = InputBinder.Bind(collectionLambda.Body, source, collectionLambda.Parameters[0], referencedExpressions); collectorReference = StripCastMethodCalls(collectorReference); MemberExpression navigationMember; if (!PatternRules.MatchPropertyProjectionSet(source, collectorReference, out navigationMember)) { return false; } collectorReference = navigationMember; ResourceExpression resultSelectorSource = CreateResourceSetExpression(mce.Method.ReturnType, source, collectorReference, TypeSystem.GetElementType(collectorReference.Type)); if (!PatternRules.MatchMemberInitExpressionWithDefaultConstructor(resultSelectorSource, resultLambda) && !PatternRules.MatchNewExpression(resultSelectorSource, resultLambda)) { return false; } #if ASTORIA_LIGHT resultLambda = ExpressionHelpers.CreateLambda(resultLambda.Body, new ParameterExpression[] { resultLambda.Parameters[1] }); #else resultLambda = Expression.Lambda(resultLambda.Body, new ParameterExpression[] { resultLambda.Parameters[1] }); #endif ResourceExpression resultWithProjection = resultSelectorSource.CreateCloneWithNewType(mce.Type); bool isProjection; try { isProjection = ProjectionAnalyzer.Analyze(resultLambda, resultWithProjection, false); } catch (NotSupportedException) { isProjection = false; } if (!isProjection) { return false; } e = resultWithProjection; ValidationRules.RequireCanProject(resultSelectorSource); } else { LambdaExpression lambda; if (!PatternRules.MatchSingleArgumentLambda(mce.Arguments[1], out lambda)) { return false; } lambda = ProjectionRewriter.TryToRewrite(lambda, source.ResourceType); ResourceExpression re = source.CreateCloneWithNewType(mce.Type); if (!ProjectionAnalyzer.Analyze(lambda, re, matchMembers)) { return false; } ValidationRules.RequireCanProject(source); e = re; } return true; } internal static Expression AnalyzeNavigation(MethodCallExpression mce) { Debug.Assert(mce != null, "mce != null"); Expression input = mce.Arguments[0]; LambdaExpression le; ResourceExpression navSource; Expression boundProjection; MemberExpression navigationMember; if (!PatternRules.MatchSingleArgumentLambda(mce.Arguments[1], out le)) { return mce; } else if (PatternRules.MatchIdentitySelector(le)) { return input; } else if (PatternRules.MatchTransparentIdentitySelector(input, le)) { return RemoveTransparentScope(mce.Method.ReturnType, (ResourceSetExpression)input); } else if (IsValidNavigationSource(input, out navSource) && TryBindToInput(navSource, le, out boundProjection) && PatternRules.MatchPropertyProjectionSingleton(navSource, boundProjection, out navigationMember)) { boundProjection = navigationMember; return CreateNavigationPropertySingletonExpression(mce.Method.ReturnType, navSource, boundProjection); } return mce; } private static bool IsValidNavigationSource(Expression input, out ResourceExpression sourceExpression) { ValidationRules.RequireCanNavigate(input); sourceExpression = input as ResourceExpression; return sourceExpression != null; } #if !ASTORIA_LIGHT private static Expression LimitCardinality(MethodCallExpression mce, int maxCardinality) { Debug.Assert(mce != null, "mce != null"); Debug.Assert(maxCardinality > 0, "Cardinality must be at least 1"); if (mce.Arguments.Count != 1) { return mce; } ResourceSetExpression rse = mce.Arguments[0] as ResourceSetExpression; if (rse != null) { if (!rse.HasKeyPredicate && (ResourceExpressionType)rse.NodeType != ResourceExpressionType.ResourceNavigationProperty) { if (rse.Take == null || (int)rse.Take.TakeAmount.Value > maxCardinality) { AddSequenceQueryOption(rse, new TakeQueryOptionExpression(mce.Type, Expression.Constant(maxCardinality))); } } return mce.Arguments[0]; } else if (mce.Arguments[0] is NavigationPropertySingletonExpression) { return mce.Arguments[0]; } return mce; } #endif private static Expression AnalyzeCast(MethodCallExpression mce) { ResourceExpression re = mce.Arguments[0] as ResourceExpression; if (re != null) { return re.CreateCloneWithNewType(mce.Method.ReturnType); } return mce; } private static ResourceSetExpression CreateResourceSetExpression(Type type, ResourceExpression source, Expression memberExpression, Type resourceType) { Debug.Assert(type != null, "type != null"); Debug.Assert(source != null, "source != null"); Debug.Assert(memberExpression != null, "memberExpression != null"); Debug.Assert(resourceType != null, "resourceType != null"); Type elementType = TypeSystem.GetElementType(type); Debug.Assert(elementType != null, "elementType != null -- otherwise the set isn't going to act like a collection"); Type expressionType = typeof(IOrderedQueryable<>).MakeGenericType(elementType); ResourceSetExpression newResource = new ResourceSetExpression(expressionType, source, memberExpression, resourceType, source.ExpandPaths.ToList(), source.CountOption, source.CustomQueryOptions.ToDictionary(kvp => kvp.Key, kvp => kvp.Value), null); source.ExpandPaths.Clear(); source.CountOption = CountOption.None; source.CustomQueryOptions.Clear(); return newResource; } private static NavigationPropertySingletonExpression CreateNavigationPropertySingletonExpression(Type type, ResourceExpression source, Expression memberExpression) { NavigationPropertySingletonExpression newResource = new NavigationPropertySingletonExpression(type, source, memberExpression, memberExpression.Type, source.ExpandPaths.ToList(), source.CountOption, source.CustomQueryOptions.ToDictionary(kvp => kvp.Key, kvp => kvp.Value), null); source.ExpandPaths.Clear(); source.CountOption = CountOption.None; source.CustomQueryOptions.Clear(); return newResource; } private static ResourceSetExpression RemoveTransparentScope(Type expectedResultType, ResourceSetExpression input) { ResourceSetExpression newResource = new ResourceSetExpression(expectedResultType, input.Source, input.MemberExpression, input.ResourceType, input.ExpandPaths, input.CountOption, input.CustomQueryOptions, input.Projection); newResource.KeyPredicate = input.KeyPredicate; foreach (QueryOptionExpression queryOption in input.SequenceQueryOptions) { newResource.AddSequenceQueryOption(queryOption); } newResource.OverrideInputReference(input); return newResource; } internal static Expression StripConvertToAssignable(Expression e) { Debug.Assert(e != null, "e != null"); Expression result; UnaryExpression unary = e as UnaryExpression; if (unary != null && PatternRules.MatchConvertToAssignable(unary)) { result = unary.Operand; } else { result = e; } return result; } internal static T StripTo<T>(Expression expression) where T : Expression { Debug.Assert(expression != null, "expression != null"); Expression result; do { result = expression; expression = expression.NodeType == ExpressionType.Quote ? ((UnaryExpression)expression).Operand : expression; expression = StripConvertToAssignable(expression); } while (result != expression); return result as T; } internal override Expression VisitResourceSetExpression(ResourceSetExpression rse) { Debug.Assert(rse != null, "rse != null"); if ((ResourceExpressionType)rse.NodeType == ResourceExpressionType.RootResourceSet) { return new ResourceSetExpression(rse.Type, rse.Source, rse.MemberExpression, rse.ResourceType, null, CountOption.None, null, null); } return rse; } private static bool TryGetResourceSetMethodArguments(MethodCallExpression mce, out ResourceSetExpression input, out LambdaExpression lambda) { input = null; lambda = null; input = mce.Arguments[0] as ResourceSetExpression; if (input != null && PatternRules.MatchSingleArgumentLambda(mce.Arguments[1], out lambda)) { return true; } return false; } private static bool TryBindToInput(ResourceExpression input, LambdaExpression le, out Expression bound) { List<ResourceExpression> referencedInputs = new List<ResourceExpression>(); bound = InputBinder.Bind(le.Body, input, le.Parameters[0], referencedInputs); if (referencedInputs.Count > 1 || (referencedInputs.Count == 1 && referencedInputs[0] != input)) { bound = null; } return bound != null; } /* private static Expression AnalyzeResourceSetMethod(MethodCallExpression mce, Func<MethodCallExpression, ResourceSetExpression, Expression, Expression> sequenceMethodAnalyzer) { ResourceSetExpression input; LambdaExpression le; if (!TryGetResourceSetMethodArguments(mce, out input, out le)) { return mce; } Expression lambdaBody; if (!TryBindToInput(input, le, out lambdaBody)) { return mce; } return sequenceMethodAnalyzer(mce, input, lambdaBody); } */ private static Expression AnalyzeResourceSetConstantMethod(MethodCallExpression mce, Func<MethodCallExpression, ResourceExpression, ConstantExpression, Expression> constantMethodAnalyzer) { ResourceExpression input = (ResourceExpression)mce.Arguments[0]; ConstantExpression constantArg = StripTo<ConstantExpression>(mce.Arguments[1]); if (null == constantArg) { return mce; } return constantMethodAnalyzer(mce, input, constantArg); } private static Expression AnalyzeCountMethod(MethodCallExpression mce) { ResourceExpression re = (ResourceExpression)mce.Arguments[0]; if (re == null) { return mce; } ValidationRules.RequireCanAddCount(re); ValidationRules.RequireNonSingleton(re); re.CountOption = CountOption.ValueOnly; return re; } private static void AddSequenceQueryOption(ResourceExpression target, QueryOptionExpression qoe) { ValidationRules.RequireNonSingleton(target); ResourceSetExpression rse = (ResourceSetExpression)target; if (qoe.NodeType == (ExpressionType)ResourceExpressionType.FilterQueryOption) { if (rse.Take != null) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqQueryOptionOutOfOrder, "filter", "top")); } else if (rse.Projection != null) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.ALinqQueryOptionOutOfOrder, "filter", "select")); } } rse.AddSequenceQueryOption(qoe); } internal override Expression VisitBinary(BinaryExpression b) { Expression e = base.VisitBinary(b); if (PatternRules.MatchStringAddition(e)) { BinaryExpression be = StripTo<BinaryExpression>(e); MethodInfo mi = typeof(string).GetMethod("Concat", new Type[] { typeof(string), typeof(string) }); return Expression.Call(mi, new Expression[] { be.Left, be.Right }); } return e; } internal override Expression VisitMemberAccess(MemberExpression m) { Expression e = base.VisitMemberAccess(m); MemberExpression me = StripTo<MemberExpression>(e); PropertyInfo pi; MethodInfo mi; if (me != null && PatternRules.MatchNonPrivateReadableProperty(me, out pi) && TypeSystem.TryGetPropertyAsMethod(pi, out mi)) { return Expression.Call(me.Expression, mi); } return e; } internal override Expression VisitMethodCall(MethodCallExpression mce) { Expression e; SequenceMethod sequenceMethod; if (ReflectionUtil.TryIdentifySequenceMethod(mce.Method, out sequenceMethod)) { if (sequenceMethod == SequenceMethod.Select || sequenceMethod == SequenceMethod.SelectManyResultSelector) { if (this.AnalyzeProjection(mce, sequenceMethod, out e)) { return e; } } } e = base.VisitMethodCall(mce); mce = e as MethodCallExpression; if (mce != null) { if (ReflectionUtil.TryIdentifySequenceMethod(mce.Method, out sequenceMethod)) { switch (sequenceMethod) { case SequenceMethod.Where: return AnalyzePredicate(mce); case SequenceMethod.Select: return AnalyzeNavigation(mce); case SequenceMethod.Take: return AnalyzeResourceSetConstantMethod(mce, (callExp, resource, takeCount) => { AddSequenceQueryOption(resource, new TakeQueryOptionExpression(callExp.Type, takeCount)); return resource; }); #if !ASTORIA_LIGHT case SequenceMethod.First: case SequenceMethod.FirstOrDefault: return LimitCardinality(mce, 1); case SequenceMethod.Single: case SequenceMethod.SingleOrDefault: return LimitCardinality(mce, 2); #endif case SequenceMethod.Cast: return AnalyzeCast(mce); case SequenceMethod.LongCount: case SequenceMethod.Count: return AnalyzeCountMethod(mce); default: throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "The method '{0}' is not supported", mce.Method.Name)); } } else if (mce.Method.DeclaringType == typeof(TableQueryableExtensions)) { Type[] types = mce.Method.GetGenericArguments(); Type t = types[0]; if (mce.Method == TableQueryableExtensions.WithOptionsMethodInfo.MakeGenericMethod(t)) { return AnalyzeResourceSetConstantMethod(mce, (callExp, resource, options) => { AddSequenceQueryOption(resource, new RequestOptionsQueryOptionExpression(callExp.Type, options)); return resource; }); } else if (mce.Method == TableQueryableExtensions.WithContextMethodInfo.MakeGenericMethod(t)) { return AnalyzeResourceSetConstantMethod(mce, (callExp, resource, ctx) => { AddSequenceQueryOption(resource, new OperationContextQueryOptionExpression(callExp.Type, ctx)); return resource; }); } else if (types.Length > 1 && mce.Method == TableQueryableExtensions.ResolveMethodInfo.MakeGenericMethod(t, types[1])) { return AnalyzeResourceSetConstantMethod(mce, (callExp, resource, resolver) => { AddSequenceQueryOption(resource, new EntityResolverQueryOptionExpression(callExp.Type, resolver)); return resource; }); } else { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "The method '{0}' is not supported", mce.Method.Name)); } } return mce; } return e; } private static Expression StripCastMethodCalls(Expression expression) { Debug.Assert(expression != null, "expression != null"); MethodCallExpression call = StripTo<MethodCallExpression>(expression); while (call != null && ReflectionUtil.IsSequenceMethod(call.Method, SequenceMethod.Cast)) { expression = call.Arguments[0]; call = StripTo<MethodCallExpression>(expression); } return expression; } internal static class PatternRules { internal static bool MatchConvertToAssignable(UnaryExpression expression) { Debug.Assert(expression != null, "expression != null"); if (expression.NodeType != ExpressionType.Convert && expression.NodeType != ExpressionType.ConvertChecked && expression.NodeType != ExpressionType.TypeAs) { return false; } return expression.Type.IsAssignableFrom(expression.Operand.Type); } internal static bool MatchParameterMemberAccess(Expression expression) { Debug.Assert(expression != null, "lambda != null"); LambdaExpression lambda = StripTo<LambdaExpression>(expression); if (lambda == null || lambda.Parameters.Count != 1) { return false; } ParameterExpression parameter = lambda.Parameters[0]; Expression body = StripCastMethodCalls(lambda.Body); MemberExpression memberAccess = StripTo<MemberExpression>(body); while (memberAccess != null) { if (memberAccess.Expression == parameter) { return true; } memberAccess = StripTo<MemberExpression>(memberAccess.Expression); } return false; } internal static bool MatchPropertyAccess(Expression e, out MemberExpression member, out Expression instance, out List<string> propertyPath) { instance = null; propertyPath = null; MemberExpression me = StripTo<MemberExpression>(e); member = me; while (me != null) { PropertyInfo pi; if (MatchNonPrivateReadableProperty(me, out pi)) { if (propertyPath == null) { propertyPath = new List<string>(); } propertyPath.Insert(0, pi.Name); e = me.Expression; me = StripTo<MemberExpression>(e); } else { me = null; } } if (propertyPath != null) { instance = e; return true; } return false; } internal static bool MatchConstant(Expression e, out ConstantExpression constExpr) { constExpr = e as ConstantExpression; return constExpr != null; } internal static bool MatchAnd(Expression e) { BinaryExpression be = e as BinaryExpression; return be != null && (be.NodeType == ExpressionType.And || be.NodeType == ExpressionType.AndAlso); } internal static bool MatchNonPrivateReadableProperty(Expression e, out PropertyInfo propInfo) { MemberExpression me = e as MemberExpression; if (me == null) { propInfo = null; return false; } return MatchNonPrivateReadableProperty(me, out propInfo); } internal static bool MatchNonPrivateReadableProperty(MemberExpression me, out PropertyInfo propInfo) { Debug.Assert(me != null, "me != null"); propInfo = null; if (me.Member.MemberType == MemberTypes.Property) { PropertyInfo pi = (PropertyInfo)me.Member; if (pi.CanRead && !TypeSystem.IsPrivate(pi)) { propInfo = pi; return true; } } return false; } /* internal static bool MatchKeyProperty(Expression expression, out PropertyInfo property) { property = null; PropertyInfo pi; if (!PatternRules.MatchNonPrivateReadableProperty(expression, out pi)) { return false; } if (GetKeyProperties(pi.ReflectedType).Contains(pi, PropertyInfoEqualityComparer.Instance)) { property = pi; return true; } return false; } internal static List<PropertyInfo> GetKeyProperties(Type type) { Debug.Assert(type != null, "type != null"); ClientType clientType = ClientType.Create(type, false); var result = new List<PropertyInfo>(); foreach (var property in clientType.Properties) { if (property.KeyProperty) { result.Add(property.DeclaringType.GetProperty(property.PropertyName)); } } return result; } internal static bool MatchKeyComparison(Expression e, out PropertyInfo keyProperty, out ConstantExpression keyValue) { if (PatternRules.MatchBinaryEquality(e)) { BinaryExpression be = (BinaryExpression)e; if ((PatternRules.MatchKeyProperty(be.Left, out keyProperty) && PatternRules.MatchConstant(be.Right, out keyValue)) || (PatternRules.MatchKeyProperty(be.Right, out keyProperty) && PatternRules.MatchConstant(be.Left, out keyValue))) { return keyValue.Value != null; } } keyProperty = null; keyValue = null; return false; } */ internal static bool MatchReferenceEquals(Expression expression) { Debug.Assert(expression != null, "expression != null"); MethodCallExpression call = expression as MethodCallExpression; if (call == null) { return false; } #if WINDOWS_DESKTOP return call.Method == typeof(object).GetMethod("ReferenceEquals"); #elif WINDOWS_RT return call.Method == typeof(object).GetRuntimeMethod("ReferenceEquals", new Type[]{}); #endif } internal static bool MatchResource(Expression expression, out ResourceExpression resource) { resource = expression as ResourceExpression; return resource != null; } internal static bool MatchDoubleArgumentLambda(Expression expression, out LambdaExpression lambda) { return MatchNaryLambda(expression, 2, out lambda); } internal static bool MatchIdentitySelector(LambdaExpression lambda) { Debug.Assert(lambda != null, "lambda != null"); ParameterExpression parameter = lambda.Parameters[0]; return parameter == StripTo<ParameterExpression>(lambda.Body); } internal static bool MatchSingleArgumentLambda(Expression expression, out LambdaExpression lambda) { return MatchNaryLambda(expression, 1, out lambda); } internal static bool MatchTransparentIdentitySelector(Expression input, LambdaExpression selector) { if (selector.Parameters.Count != 1) { return false; } ResourceSetExpression rse = input as ResourceSetExpression; if (rse == null || rse.TransparentScope == null) { return false; } Expression potentialRef = selector.Body; ParameterExpression expectedTarget = selector.Parameters[0]; MemberExpression propertyMember; Expression paramRef; List<string> refPath; if (!MatchPropertyAccess(potentialRef, out propertyMember, out paramRef, out refPath)) { return false; } Debug.Assert(refPath != null, "refPath != null -- otherwise MatchPropertyAccess should not have returned true"); return paramRef == expectedTarget && refPath.Count == 1 && refPath[0] == rse.TransparentScope.Accessor; } internal static bool MatchIdentityProjectionResultSelector(Expression e) { LambdaExpression le = (LambdaExpression)e; return le.Body == le.Parameters[1]; } internal static bool MatchTransparentScopeSelector(ResourceSetExpression input, LambdaExpression resultSelector, out ResourceSetExpression.TransparentAccessors transparentScope) { transparentScope = null; if (resultSelector.Body.NodeType != ExpressionType.New) { return false; } NewExpression ne = (NewExpression)resultSelector.Body; if (ne.Arguments.Count < 2) { return false; } if (ne.Type.BaseType != typeof(object)) { return false; } ParameterInfo[] constructorParams = ne.Constructor.GetParameters(); if (ne.Members.Count != constructorParams.Length) { return false; } ResourceSetExpression inputSourceSet = input.Source as ResourceSetExpression; int introducedMemberIndex = -1; ParameterExpression collectorSourceParameter = resultSelector.Parameters[0]; ParameterExpression introducedRangeParameter = resultSelector.Parameters[1]; MemberInfo[] memberProperties = new MemberInfo[ne.Members.Count]; PropertyInfo[] properties = ne.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance); Dictionary<string, Expression> sourceAccessors = new Dictionary<string, Expression>(constructorParams.Length - 1, StringComparer.Ordinal); for (int i = 0; i < ne.Arguments.Count; i++) { Expression argument = ne.Arguments[i]; MemberInfo member = ne.Members[i]; if (!ExpressionIsSimpleAccess(argument, resultSelector.Parameters)) { return false; } if (member.MemberType == MemberTypes.Method) { member = properties.Where(property => property.GetGetMethod() == member).FirstOrDefault(); if (member == null) { return false; } } if (member.Name != constructorParams[i].Name) { return false; } memberProperties[i] = member; ParameterExpression argumentAsParameter = StripTo<ParameterExpression>(argument); if (introducedRangeParameter == argumentAsParameter) { if (introducedMemberIndex != -1) { return false; } introducedMemberIndex = i; } else if (collectorSourceParameter == argumentAsParameter) { sourceAccessors[member.Name] = inputSourceSet.CreateReference(); } else { List<ResourceExpression> referencedInputs = new List<ResourceExpression>(); InputBinder.Bind(argument, inputSourceSet, resultSelector.Parameters[0], referencedInputs); if (referencedInputs.Count != 1) { return false; } sourceAccessors[member.Name] = referencedInputs[0].CreateReference(); } } if (introducedMemberIndex == -1) { return false; } string resultAccessor = memberProperties[introducedMemberIndex].Name; transparentScope = new ResourceSetExpression.TransparentAccessors(resultAccessor, sourceAccessors); return true; } internal static bool MatchPropertyProjectionSet(ResourceExpression input, Expression potentialPropertyRef, out MemberExpression navigationMember) { return MatchNavigationPropertyProjection(input, potentialPropertyRef, true, out navigationMember); } internal static bool MatchPropertyProjectionSingleton(ResourceExpression input, Expression potentialPropertyRef, out MemberExpression navigationMember) { return MatchNavigationPropertyProjection(input, potentialPropertyRef, false, out navigationMember); } private static bool MatchNavigationPropertyProjection(ResourceExpression input, Expression potentialPropertyRef, bool requireSet, out MemberExpression navigationMember) { if (PatternRules.MatchNonSingletonProperty(potentialPropertyRef) == requireSet) { Expression foundInstance; List<string> propertyNames; if (MatchPropertyAccess(potentialPropertyRef, out navigationMember, out foundInstance, out propertyNames)) { if (foundInstance == input.CreateReference()) { return true; } } } navigationMember = null; return false; } internal static bool MatchMemberInitExpressionWithDefaultConstructor(Expression source, LambdaExpression e) { MemberInitExpression mie = StripTo<MemberInitExpression>(e.Body); ResourceExpression resource; return MatchResource(source, out resource) && (mie != null) && (mie.NewExpression.Arguments.Count == 0); } internal static bool MatchNewExpression(Expression source, LambdaExpression e) { ResourceExpression resource; return MatchResource(source, out resource) && (e.Body is NewExpression); } internal static bool MatchNot(Expression expression) { Debug.Assert(expression != null, "expression != null"); return expression.NodeType == ExpressionType.Not; } internal static bool MatchNonSingletonProperty(Expression e) { return (TypeSystem.FindIEnumerable(e.Type) != null) && e.Type != typeof(char[]) && e.Type != typeof(byte[]); } internal static MatchNullCheckResult MatchNullCheck(Expression entityInScope, ConditionalExpression conditional) { Debug.Assert(conditional != null, "conditional != null"); MatchNullCheckResult result = new MatchNullCheckResult(); MatchEqualityCheckResult equalityCheck = MatchEquality(conditional.Test); if (!equalityCheck.Match) { return result; } Expression assignedCandidate; if (equalityCheck.EqualityYieldsTrue) { if (!MatchNullConstant(conditional.IfTrue)) { return result; } assignedCandidate = conditional.IfFalse; } else { if (!MatchNullConstant(conditional.IfFalse)) { return result; } assignedCandidate = conditional.IfTrue; } Expression memberCandidate; if (MatchNullConstant(equalityCheck.TestLeft)) { memberCandidate = equalityCheck.TestRight; } else if (MatchNullConstant(equalityCheck.TestRight)) { memberCandidate = equalityCheck.TestLeft; } else { return result; } Debug.Assert(assignedCandidate != null, "assignedCandidate != null"); Debug.Assert(memberCandidate != null, "memberCandidate != null"); MemberAssignmentAnalysis assignedAnalysis = MemberAssignmentAnalysis.Analyze(entityInScope, assignedCandidate); if (assignedAnalysis.MultiplePathsFound) { return result; } MemberAssignmentAnalysis memberAnalysis = MemberAssignmentAnalysis.Analyze(entityInScope, memberCandidate); if (memberAnalysis.MultiplePathsFound) { return result; } Expression[] assignedExpressions = assignedAnalysis.GetExpressionsToTargetEntity(); Expression[] memberExpressions = memberAnalysis.GetExpressionsToTargetEntity(); if (memberExpressions.Length > assignedExpressions.Length) { return result; } for (int i = 0; i < memberExpressions.Length; i++) { Expression assigned = assignedExpressions[i]; Expression member = memberExpressions[i]; if (assigned == member) { continue; } if (assigned.NodeType != member.NodeType || assigned.NodeType != ExpressionType.MemberAccess) { return result; } if (((MemberExpression)assigned).Member != ((MemberExpression)member).Member) { return result; } } result.AssignExpression = assignedCandidate; result.Match = true; result.TestToNullExpression = memberCandidate; return result; } internal static bool MatchNullConstant(Expression expression) { Debug.Assert(expression != null, "expression != null"); ConstantExpression constant = expression as ConstantExpression; if (constant != null && constant.Value == null) { return true; } return false; } internal static bool MatchBinaryExpression(Expression e) { return e is BinaryExpression; } internal static bool MatchBinaryEquality(Expression e) { return PatternRules.MatchBinaryExpression(e) && ((BinaryExpression)e).NodeType == ExpressionType.Equal; } internal static bool MatchStringAddition(Expression e) { if (e.NodeType == ExpressionType.Add) { BinaryExpression be = e as BinaryExpression; return be != null && be.Left.Type == typeof(string) && be.Right.Type == typeof(string); } return false; } internal static MatchEqualityCheckResult MatchEquality(Expression expression) { Debug.Assert(expression != null, "expression != null"); MatchEqualityCheckResult result = new MatchEqualityCheckResult(); result.Match = false; result.EqualityYieldsTrue = true; while (true) { if (MatchReferenceEquals(expression)) { MethodCallExpression call = (MethodCallExpression)expression; result.Match = true; result.TestLeft = call.Arguments[0]; result.TestRight = call.Arguments[1]; break; } else if (MatchNot(expression)) { result.EqualityYieldsTrue = !result.EqualityYieldsTrue; expression = ((UnaryExpression)expression).Operand; } else { BinaryExpression test = expression as BinaryExpression; if (test == null) { break; } if (test.NodeType == ExpressionType.NotEqual) { result.EqualityYieldsTrue = !result.EqualityYieldsTrue; } else if (test.NodeType != ExpressionType.Equal) { break; } result.TestLeft = test.Left; result.TestRight = test.Right; result.Match = true; break; } } return result; } private static bool ExpressionIsSimpleAccess(Expression argument, ReadOnlyCollection<ParameterExpression> expressions) { Debug.Assert(argument != null, "argument != null"); Debug.Assert(expressions != null, "expressions != null"); Expression source = argument; MemberExpression member; do { member = source as MemberExpression; if (member != null) { source = member.Expression; } } while (member != null); ParameterExpression parameter = source as ParameterExpression; if (parameter == null) { return false; } return expressions.Contains(parameter); } private static bool MatchNaryLambda(Expression expression, int parameterCount, out LambdaExpression lambda) { lambda = null; LambdaExpression le = StripTo<LambdaExpression>(expression); if (le != null && le.Parameters.Count == parameterCount) { lambda = le; } return lambda != null; } internal struct MatchNullCheckResult { internal Expression AssignExpression; internal bool Match; internal Expression TestToNullExpression; } internal struct MatchEqualityCheckResult { internal bool EqualityYieldsTrue; internal bool Match; internal Expression TestLeft; internal Expression TestRight; } } private static class ValidationRules { internal static void RequireCanNavigate(Expression e) { ResourceSetExpression resourceSet = e as ResourceSetExpression; if (resourceSet != null && resourceSet.HasSequenceQueryOptions) { throw new NotSupportedException(SR.ALinqQueryOptionsOnlyAllowedOnLeafNodes); } ResourceExpression resource; if (PatternRules.MatchResource(e, out resource) && resource.Projection != null) { throw new NotSupportedException(SR.ALinqQueryOptionsOnlyAllowedOnLeafNodes); } } internal static void RequireCanProject(Expression e) { ResourceExpression re = (ResourceExpression)e; if (!PatternRules.MatchResource(e, out re)) { throw new NotSupportedException("Can only project the last entity type in the query being translated."); } if (re.Projection != null) { throw new NotSupportedException("Cannot translate multiple Linq Select operations in a single 'select' query option."); } if (re.ExpandPaths.Count > 0) { throw new NotSupportedException("Cannot create projection while there is an explicit expansion specified on the same query."); } } internal static void RequireCanAddCount(Expression e) { ResourceExpression re = (ResourceExpression)e; if (!PatternRules.MatchResource(e, out re)) { throw new NotSupportedException("Cannot add count option to the resource set."); } if (re.CountOption != CountOption.None) { throw new NotSupportedException("Cannot add count option to the resource set because it would conflict with existing count options."); } } internal static void RequireNonSingleton(Expression e) { ResourceExpression re = e as ResourceExpression; if (re != null && re.IsSingleton) { throw new NotSupportedException("Cannot specify query options (orderby, where, take, skip) on single resource."); } } } private sealed class PropertyInfoEqualityComparer : IEqualityComparer<PropertyInfo> { private PropertyInfoEqualityComparer() { } internal static readonly PropertyInfoEqualityComparer Instance = new PropertyInfoEqualityComparer(); #region IEqualityComparer<TypeUsage> Members public bool Equals(PropertyInfo left, PropertyInfo right) { if (object.ReferenceEquals(left, right)) { return true; } if (null == left || null == right) { return false; } return object.ReferenceEquals(left.DeclaringType, right.DeclaringType) && left.Name.Equals(right.Name); } public int GetHashCode(PropertyInfo obj) { Debug.Assert(obj != null, "obj != null"); return (null != obj) ? obj.GetHashCode() : 0; } #endregion } private sealed class ExpressionPresenceVisitor : DataServiceALinqExpressionVisitor { #region Private fields. private readonly Expression target; private bool found; #endregion Private fields. private ExpressionPresenceVisitor(Expression target) { Debug.Assert(target != null, "target != null"); this.target = target; } internal static bool IsExpressionPresent(Expression target, Expression tree) { Debug.Assert(target != null, "target != null"); Debug.Assert(tree != null, "tree != null"); ExpressionPresenceVisitor visitor = new ExpressionPresenceVisitor(target); visitor.Visit(tree); return visitor.found; } internal override Expression Visit(Expression exp) { Expression result; if (this.found || object.ReferenceEquals(this.target, exp)) { this.found = true; result = exp; } else { result = base.Visit(exp); } return result; } } } }
using System; using System.Globalization; ///<summary> ///System.Globalization.CharUnicodeInfo.GetUnicodeCategory(System.Char) ///</summary> public class CharUnicodeInfoGetUnicodeCategory { public static int Main() { CharUnicodeInfoGetUnicodeCategory testObj = new CharUnicodeInfoGetUnicodeCategory(); TestLibrary.TestFramework.BeginTestCase("for method of System.Globalization.CharUnicodeInfo.GetUnicodeCategory"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; retVal = PosTest10() && retVal; retVal = PosTest11() && retVal; retVal = PosTest12() && retVal; retVal = PosTest13() && retVal; retVal = PosTest14() && retVal; retVal = PosTest15() && retVal; retVal = PosTest16() && retVal; retVal = PosTest17() && retVal; retVal = PosTest18() && retVal; retVal = PosTest19() && retVal; retVal = PosTest20() && retVal; retVal = PosTest21() && retVal; retVal = PosTest22() && retVal; retVal = PosTest23() && retVal; retVal = PosTest24() && retVal; retVal = PosTest25() && retVal; retVal = PosTest26() && retVal; retVal = PosTest27() && retVal; retVal = PosTest28() && retVal; retVal = PosTest29() && retVal; retVal = PosTest30() && retVal; return retVal; } #region Test Logic public bool PosTest1() { bool retVal = true; Char ch = 'A'; int expectedValue = (int)UnicodeCategory.UppercaseLetter; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with upper letter"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ") when char is '" + ch + "'" ); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; Char ch = 'a'; int expectedValue = (int)UnicodeCategory.LowercaseLetter; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest2:Test the method with low case char"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; Char ch = '\u1fa8'; //this char is a TitlecaseLetter char int expectedValue = (int)UnicodeCategory.TitlecaseLetter; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest3:Test the method with '\\0'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("005", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; Char ch = '\u02b0'; int expectedValue = (int)UnicodeCategory.ModifierLetter; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest4:Test the method with '\\u02b0'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("007", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; Char ch = '\u404e'; int expectedValue = (int)UnicodeCategory.OtherLetter; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest5:Test the method with '\\u404e'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("009", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; Char ch = '\u0300'; int expectedValue = (int)UnicodeCategory.NonSpacingMark; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest6:Test the method with '\\u0300'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("011", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; Char ch = '\u0903'; int expectedValue = (int)UnicodeCategory.SpacingCombiningMark; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest7:Test the method with '\\u0903'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("013", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; Char ch = '\u0488'; int expectedValue = (int)UnicodeCategory.EnclosingMark; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest8:Test the method with '\\u0488'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("017", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest9() { bool retVal = true; Char ch = '0'; int expectedValue = (int)UnicodeCategory.DecimalDigitNumber; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest9:Test the method with '0'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("017", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest10() { bool retVal = true; Char ch = '\u16ee'; int expectedValue = (int)UnicodeCategory.LetterNumber; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest10:Test the method with '\\u16ee'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("019", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("020", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest11() { bool retVal = true; Char ch = '\u00b2'; int expectedValue = (int)UnicodeCategory.OtherNumber; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest11:Test the method with '\\u00b2'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("021", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("022", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest12() { bool retVal = true; Char ch = '\u0020'; int expectedValue = (int)UnicodeCategory.SpaceSeparator; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest12:Test the method with '\\u0020'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("023", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("024", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest13() { bool retVal = true; Char ch = '\u2028'; int expectedValue = (int)UnicodeCategory.LineSeparator; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest13:Test the method with '\\u2028'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("025", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("026", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest14() { bool retVal = true; Char ch = '\u2029'; int expectedValue = (int)UnicodeCategory.ParagraphSeparator; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest14:Test the method with '\\u2029'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("027", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("028", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest15() { bool retVal = true; Char ch = '\0'; int expectedValue = (int)UnicodeCategory.Control; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest15:Test the method with '\\0'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("029", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("030", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest16() { bool retVal = true; Char ch = '\u00ad'; int expectedValue = (int)UnicodeCategory.Format; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest16:Test the method with '\\u00ad'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("031", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("032", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest17() { bool retVal = true; Char ch = '\ud800'; int expectedValue = (int)UnicodeCategory.Surrogate; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest17:Test the method with '\\ud800'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("033", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("034", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest18() { bool retVal = true; Char ch = '\ue000'; int expectedValue = (int)UnicodeCategory.PrivateUse; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest18:Test the method with '\\ue000'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("035", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("036", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest19() { bool retVal = true; Char ch = '\u005f'; int expectedValue = (int)UnicodeCategory.ConnectorPunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest19:Test the method with '\\u005f'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("037", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("038", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest20() { bool retVal = true; Char ch = '-'; int expectedValue = (int)UnicodeCategory.DashPunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest20:Test the method with '-'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("039", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("040", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest21() { bool retVal = true; Char ch = '('; int expectedValue = (int)UnicodeCategory.OpenPunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest21:Test the method with '('"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("041", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("042", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest22() { bool retVal = true; Char ch = ')'; int expectedValue = (int)UnicodeCategory.ClosePunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest22:Test the method with ')'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("043", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("044", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest23() { bool retVal = true; Char ch = '\u00ab'; int expectedValue = (int)UnicodeCategory.InitialQuotePunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest23:Test the method with '\\u00ab'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("045", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("046", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest24() { bool retVal = true; Char ch = '\u00bb'; int expectedValue = (int)UnicodeCategory.FinalQuotePunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest24:Test the method with '\\u00bb'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("047", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("048", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest25() { bool retVal = true; Char ch = '!'; int expectedValue = (int)UnicodeCategory.OtherPunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest25:Test the method with '!'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("049", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("050", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest26() { bool retVal = true; Char ch = '+'; int expectedValue = (int)UnicodeCategory.MathSymbol; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest26:Test the method with '+'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("051", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("052", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest27() { bool retVal = true; Char ch = '$'; int expectedValue = (int)UnicodeCategory.CurrencySymbol; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest27:Test the method with '$'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("053", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("054", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest28() { bool retVal = true; Char ch = '^'; int expectedValue = (int)UnicodeCategory.ModifierSymbol; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest28:Test the method with '^'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("055", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("056", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest29() { bool retVal = true; Char ch = '\u00a6'; int expectedValue = (int)UnicodeCategory.OtherSymbol; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest29:Test the method with '\\u00a6'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("057", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("058", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest30() { bool retVal = true; Char ch = '\u0242'; int expectedValue = (int)UnicodeCategory.LowercaseLetter; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest30:Test the method with '\\u0242'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(ch)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("059", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("060", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestZInt16() { var test = new BooleanBinaryOpTest__TestZInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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 (Avx.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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } 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 BooleanBinaryOpTest__TestZInt16 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int16); private const int Op2ElementCount = VectorSize / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private BooleanBinaryOpTest__DataTable<Int16, Int16> _dataTable; static BooleanBinaryOpTest__TestZInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); } public BooleanBinaryOpTest__TestZInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } _dataTable = new BooleanBinaryOpTest__DataTable<Int16, Int16>(_data1, _data2, VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.TestZ( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Avx.TestZ( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Avx.TestZ( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() { var method = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Avx.TestZ( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanBinaryOpTest__TestZInt16(); var result = Avx.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Avx.TestZ(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "") { var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((left[i] & right[i]) == 0); } if (expectedResult != result) { Succeeded = false; Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.TestZ)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace System.Diagnostics { public partial class Process : IDisposable { /// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary> public TimeSpan PrivilegedProcessorTime { get { return TicksToTimeSpan(GetStat().stime); } } /// <summary>Gets the time the associated process was started.</summary> public DateTime StartTime { get { return BootTimeToDateTime(GetStat().starttime); } } /// <summary> /// Gets the amount of time the associated process has spent utilizing the CPU. /// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and /// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>. /// </summary> public TimeSpan TotalProcessorTime { get { Interop.procfs.ParsedStat stat = GetStat(); return TicksToTimeSpan(stat.utime + stat.stime); } } /// <summary> /// Gets the amount of time the associated process has spent running code /// inside the application portion of the process (not the operating system core). /// </summary> public TimeSpan UserProcessorTime { get { return TicksToTimeSpan(GetStat().utime); } } /// <summary> /// Gets or sets which processors the threads in this process can be scheduled to run on. /// </summary> private unsafe IntPtr ProcessorAffinityCore { get { EnsureState(State.HaveId); Interop.libc.cpu_set_t set = default(Interop.libc.cpu_set_t); if (Interop.libc.sched_getaffinity(_processId, (IntPtr)sizeof(Interop.libc.cpu_set_t), &set) != 0) { throw new Win32Exception(); // match Windows exception } ulong bits = 0; int maxCpu = IntPtr.Size == 4 ? 32 : 64; for (int cpu = 0; cpu < maxCpu; cpu++) { if (Interop.libc.CPU_ISSET(cpu, &set)) bits |= (1u << cpu); } return (IntPtr)bits; } set { EnsureState(State.HaveId); Interop.libc.cpu_set_t set = default(Interop.libc.cpu_set_t); long bits = (long)value; int maxCpu = IntPtr.Size == 4 ? 32 : 64; for (int cpu = 0; cpu < maxCpu; cpu++) { if ((bits & (1u << cpu)) != 0) Interop.libc.CPU_SET(cpu, &set); } if (Interop.libc.sched_setaffinity(_processId, (IntPtr)sizeof(Interop.libc.cpu_set_t), &set) != 0) { throw new Win32Exception(); // match Windows exception } } } /// <summary> /// Make sure we have obtained the min and max working set limits. /// </summary> private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet) { minWorkingSet = IntPtr.Zero; // no defined limit available ulong rsslim = GetStat().rsslim; // rsslim is a ulong, but maxWorkingSet is an IntPtr, so we need to cap rsslim // at the max size of IntPtr. This often happens when there is no configured // rsslim other than ulong.MaxValue, which without these checks would show up // as a maxWorkingSet == -1. switch (IntPtr.Size) { case 4: if (rsslim > int.MaxValue) rsslim = int.MaxValue; break; case 8: if (rsslim > long.MaxValue) rsslim = long.MaxValue; break; } maxWorkingSet = (IntPtr)rsslim; } /// <summary>Sets one or both of the minimum and maximum working set limits.</summary> /// <param name="newMin">The new minimum working set limit, or null not to change it.</param> /// <param name="newMax">The new maximum working set limit, or null not to change it.</param> /// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param> /// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param> private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) { // RLIMIT_RSS with setrlimit not supported on Linux > 2.4.30. throw new PlatformNotSupportedException(); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Gets the path to the current executable, or null if it could not be retrieved.</summary> private static string GetExePath() { // Determine the maximum size of a path int maxPath = -1; Interop.libc.GetPathConfValue(ref maxPath, Interop.libc.PathConfNames._PC_PATH_MAX, Interop.libc.DEFAULT_PC_PATH_MAX); // Start small with a buffer allocation, and grow only up to the max path for (int pathLen = 256; pathLen < maxPath; pathLen *= 2) { // Read from procfs the symbolic link to this process' executable byte[] buffer = new byte[pathLen + 1]; // +1 for null termination int resultLength = (int)Interop.libc.readlink(Interop.procfs.SelfExeFilePath, buffer, (IntPtr)pathLen); // If we got one, null terminate it (readlink doesn't do this) and return the string if (resultLength > 0) { buffer[resultLength] = (byte)'\0'; return Encoding.UTF8.GetString(buffer, 0, resultLength); } // If the buffer was too small, loop around again and try with a larger buffer. // Otherwise, bail. if (resultLength == 0 || Marshal.GetLastWin32Error() != Interop.Errors.ENAMETOOLONG) { break; } } // Could not get a path return null; } // ---------------------------------- // ---- Unix PAL layer ends here ---- // ---------------------------------- /// <summary>Computes a time based on a number of ticks since boot.</summary> /// <param name="ticksAfterBoot">The number of ticks since boot.</param> /// <returns>The converted time.</returns> internal static DateTime BootTimeToDateTime(ulong ticksAfterBoot) { // Read procfs to determine the system's uptime, aka how long ago it booted string uptimeStr = File.ReadAllText(Interop.procfs.ProcUptimeFilePath, Encoding.UTF8); int spacePos = uptimeStr.IndexOf(' '); double uptime; if (spacePos < 1 || !double.TryParse(uptimeStr.Substring(0, spacePos), out uptime)) { throw new Win32Exception(); } // Use the uptime and the current time to determine the absolute boot time DateTime bootTime = DateTime.UtcNow - TimeSpan.FromSeconds(uptime); // And use that to determine the absolute time for ticksStartedAfterBoot DateTime dt = bootTime + TicksToTimeSpan(ticksAfterBoot); // The return value is expected to be in the local time zone. // It is converted here (rather than starting with DateTime.Now) to avoid DST issues. return dt.ToLocalTime(); } /// <summary>Reads the stats information for this process from the procfs file system.</summary> private Interop.procfs.ParsedStat GetStat() { EnsureState(State.HaveId); return Interop.procfs.ReadStatFile(_processId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.IO.Tests { public partial class StreamReaderTests { protected virtual Stream CreateStream() { return new MemoryStream(); } protected virtual Stream GetSmallStream() { byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; return new MemoryStream(testData); } protected virtual Stream GetLargeStream() { byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; // System.Collections.Generic. List<byte> data = new List<byte>(); for (int i = 0; i < 1000; i++) { data.AddRange(testData); } return new MemoryStream(data.ToArray()); } protected Tuple<char[], StreamReader> GetCharArrayStream() { var chArr = new char[]{ char.MinValue ,char.MaxValue ,'\t' ,' ' ,'$' ,'@' ,'#' ,'\0' ,'\v' ,'\'' ,'\u3190' ,'\uC3A0' ,'A' ,'5' ,'\r' ,'\uFE70' ,'-' ,';' ,'\r' ,'\n' ,'T' ,'3' ,'\n' ,'K' ,'\u00E6' }; var ms = CreateStream(); var sw = new StreamWriter(ms); for (int i = 0; i < chArr.Length; i++) sw.Write(chArr[i]); sw.Flush(); ms.Position = 0; return new Tuple<char[], StreamReader>(chArr, new StreamReader(ms)); } [Fact] public void EndOfStream() { var sw = new StreamReader(GetSmallStream()); var result = sw.ReadToEnd(); Assert.Equal("HELLO", result); Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); } [Fact] public void EndOfStreamSmallDataLargeBuffer() { var sw = new StreamReader(GetSmallStream(), Encoding.UTF8, true, 1024); var result = sw.ReadToEnd(); Assert.Equal("HELLO", result); Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); } [Fact] public void EndOfStreamLargeDataSmallBuffer() { var sw = new StreamReader(GetLargeStream(), Encoding.UTF8, true, 1); var result = sw.ReadToEnd(); Assert.Equal(5000, result.Length); Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); } [Fact] public void EndOfStreamLargeDataLargeBuffer() { var sw = new StreamReader(GetLargeStream(), Encoding.UTF8, true, 1 << 16); var result = sw.ReadToEnd(); Assert.Equal(5000, result.Length); Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); } [Fact] public async Task ReadToEndAsync() { var sw = new StreamReader(GetLargeStream()); var result = await sw.ReadToEndAsync(); Assert.Equal(5000, result.Length); } [Fact] public void GetBaseStream() { var ms = GetSmallStream(); var sw = new StreamReader(ms); Assert.Same(sw.BaseStream, ms); } [Fact] public void TestRead() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; for (int i = 0; i < baseInfo.Item1.Length; i++) { int tmp = sr.Read(); Assert.Equal((int)baseInfo.Item1[i], tmp); } sr.Dispose(); } [Fact] public void TestPeek() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; for (int i = 0; i < baseInfo.Item1.Length; i++) { var peek = sr.Peek(); Assert.Equal((int)baseInfo.Item1[i], peek); sr.Read(); } } [Fact] public void ArgumentNullOnNullArray() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; Assert.Throws<ArgumentNullException>(() => sr.Read(null, 0, 0)); } [Fact] public void ArgumentOutOfRangeOnInvalidOffset() { var sr = GetCharArrayStream().Item2; Assert.Throws<ArgumentOutOfRangeException>(() => sr.Read(new char[0], -1, 0)); } [Fact] public void ArgumentOutOfRangeOnNegativCount() { var sr = GetCharArrayStream().Item2; AssertExtensions.Throws<ArgumentException>(null, () => sr.Read(new char[0], 0, 1)); } [Fact] public void ArgumentExceptionOffsetAndCount() { var sr = GetCharArrayStream().Item2; AssertExtensions.Throws<ArgumentException>(null, () => sr.Read(new char[0], 2, 0)); } [Fact] public void ObjectDisposedExceptionDisposedStream() { var sr = GetCharArrayStream().Item2; sr.Dispose(); Assert.Throws<ObjectDisposedException>(() => sr.Read(new char[1], 0, 1)); } [Fact] public void ObjectDisposedExceptionDisposedBaseStream() { var ms = GetSmallStream(); var sr = new StreamReader(ms); ms.Dispose(); Assert.Throws<ObjectDisposedException>(() => sr.Read(new char[1], 0, 1)); } [Fact] public void EmptyStream() { var ms = CreateStream(); var sr = new StreamReader(ms); var buffer = new char[10]; int read = sr.Read(buffer, 0, 1); Assert.Equal(0, read); } [Fact] public void VanillaReads1() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; var chArr = new char[baseInfo.Item1.Length]; var read = sr.Read(chArr, 0, chArr.Length); Assert.Equal(chArr.Length, read); for (int i = 0; i < baseInfo.Item1.Length; i++) { Assert.Equal(baseInfo.Item1[i], chArr[i]); } } [Fact] public async Task VanillaReads2WithAsync() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; var chArr = new char[baseInfo.Item1.Length]; var read = await sr.ReadAsync(chArr, 4, 3); Assert.Equal(read, 3); for (int i = 0; i < 3; i++) { Assert.Equal(baseInfo.Item1[i], chArr[i + 4]); } } [Fact] public void ObjectDisposedReadLine() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; sr.Dispose(); Assert.Throws<ObjectDisposedException>(() => sr.ReadLine()); } [Fact] public void ObjectDisposedReadLineBaseStream() { var ms = GetLargeStream(); var sr = new StreamReader(ms); ms.Dispose(); Assert.Throws<ObjectDisposedException>(() => sr.ReadLine()); } [Fact] public void VanillaReadLines() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; string valueString = new string(baseInfo.Item1); var data = sr.ReadLine(); Assert.Equal(valueString.Substring(0, valueString.IndexOf('\r')), data); data = sr.ReadLine(); Assert.Equal(valueString.Substring(valueString.IndexOf('\r') + 1, 3), data); data = sr.ReadLine(); Assert.Equal(valueString.Substring(valueString.IndexOf('\n') + 1, 2), data); data = sr.ReadLine(); Assert.Equal((valueString.Substring(valueString.LastIndexOf('\n') + 1)), data); } [Fact] public void VanillaReadLines2() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; string valueString = new string(baseInfo.Item1); var temp = new char[10]; sr.Read(temp, 0, 1); var data = sr.ReadLine(); Assert.Equal(valueString.Substring(1, valueString.IndexOf('\r') - 1), data); } [Fact] public async Task ContinuousNewLinesAndTabsAsync() { var ms = CreateStream(); var sw = new StreamWriter(ms); sw.Write("\n\n\r\r\n"); sw.Flush(); ms.Position = 0; var sr = new StreamReader(ms); for (int i = 0; i < 4; i++) { var data = await sr.ReadLineAsync(); Assert.Equal(string.Empty, data); } var eol = await sr.ReadLineAsync(); Assert.Null(eol); } [Fact] public void CurrentEncoding() { var ms = CreateStream(); var sr = new StreamReader(ms); Assert.Equal(Encoding.UTF8, sr.CurrentEncoding); sr = new StreamReader(ms, Encoding.Unicode); Assert.Equal(Encoding.Unicode, sr.CurrentEncoding); } } }
namespace java.awt.font { [global::MonoJavaBridge.JavaClass()] public sealed partial class NumericShaper : java.lang.Object, java.io.Serializable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal NumericShaper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public sealed override bool equals(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.awt.font.NumericShaper.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::java.awt.font.NumericShaper._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public sealed override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.awt.font.NumericShaper.staticClass, "toString", "()Ljava/lang/String;", ref global::java.awt.font.NumericShaper._m1) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m2; public sealed override int hashCode() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.awt.font.NumericShaper.staticClass, "hashCode", "()I", ref global::java.awt.font.NumericShaper._m2); } private static global::MonoJavaBridge.MethodId _m3; public void shape(char[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.awt.font.NumericShaper.staticClass, "shape", "([CII)V", ref global::java.awt.font.NumericShaper._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m4; public void shape(char[] arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.awt.font.NumericShaper.staticClass, "shape", "([CIII)V", ref global::java.awt.font.NumericShaper._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m5; public static global::java.awt.font.NumericShaper getShaper(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.awt.font.NumericShaper._m5.native == global::System.IntPtr.Zero) global::java.awt.font.NumericShaper._m5 = @__env.GetStaticMethodIDNoThrow(global::java.awt.font.NumericShaper.staticClass, "getShaper", "(I)Ljava/awt/font/NumericShaper;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.awt.font.NumericShaper>(@__env.CallStaticObjectMethod(java.awt.font.NumericShaper.staticClass, global::java.awt.font.NumericShaper._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.awt.font.NumericShaper; } private static global::MonoJavaBridge.MethodId _m6; public static global::java.awt.font.NumericShaper getContextualShaper(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.awt.font.NumericShaper._m6.native == global::System.IntPtr.Zero) global::java.awt.font.NumericShaper._m6 = @__env.GetStaticMethodIDNoThrow(global::java.awt.font.NumericShaper.staticClass, "getContextualShaper", "(I)Ljava/awt/font/NumericShaper;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.awt.font.NumericShaper>(@__env.CallStaticObjectMethod(java.awt.font.NumericShaper.staticClass, global::java.awt.font.NumericShaper._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.awt.font.NumericShaper; } private static global::MonoJavaBridge.MethodId _m7; public static global::java.awt.font.NumericShaper getContextualShaper(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.awt.font.NumericShaper._m7.native == global::System.IntPtr.Zero) global::java.awt.font.NumericShaper._m7 = @__env.GetStaticMethodIDNoThrow(global::java.awt.font.NumericShaper.staticClass, "getContextualShaper", "(II)Ljava/awt/font/NumericShaper;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.awt.font.NumericShaper>(@__env.CallStaticObjectMethod(java.awt.font.NumericShaper.staticClass, global::java.awt.font.NumericShaper._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.awt.font.NumericShaper; } private static global::MonoJavaBridge.MethodId _m8; public bool isContextual() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.awt.font.NumericShaper.staticClass, "isContextual", "()Z", ref global::java.awt.font.NumericShaper._m8); } public new int Ranges { get { return getRanges(); } } private static global::MonoJavaBridge.MethodId _m9; public int getRanges() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.awt.font.NumericShaper.staticClass, "getRanges", "()I", ref global::java.awt.font.NumericShaper._m9); } public static int EUROPEAN { get { return 1; } } public static int ARABIC { get { return 2; } } public static int EASTERN_ARABIC { get { return 4; } } public static int DEVANAGARI { get { return 8; } } public static int BENGALI { get { return 16; } } public static int GURMUKHI { get { return 32; } } public static int GUJARATI { get { return 64; } } public static int ORIYA { get { return 128; } } public static int TAMIL { get { return 256; } } public static int TELUGU { get { return 512; } } public static int KANNADA { get { return 1024; } } public static int MALAYALAM { get { return 2048; } } public static int THAI { get { return 4096; } } public static int LAO { get { return 8192; } } public static int TIBETAN { get { return 16384; } } public static int MYANMAR { get { return 32768; } } public static int ETHIOPIC { get { return 65536; } } public static int KHMER { get { return 131072; } } public static int MONGOLIAN { get { return 262144; } } public static int ALL_RANGES { get { return 524287; } } static NumericShaper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.awt.font.NumericShaper.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/awt/font/NumericShaper")); } } }
//--------------------------------------------------------------------- // <copyright file="ODataJsonLightContextUriParser.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.JsonLight { #region Namespaces using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; using Microsoft.OData.Core.UriParser; using Microsoft.OData.Core.UriParser.Semantic; using Microsoft.OData.Edm; using Microsoft.OData.Core.Metadata; using ODataErrorStrings = Microsoft.OData.Core.Strings; using UriUtils = Microsoft.OData.Core.UriUtils; #endregion Namespaces /// <summary> /// Parser for odata context URIs used in JSON Lite. /// </summary> internal sealed class ODataJsonLightContextUriParser { /// <summary> /// Pattern for key segments, Examples: /// Customer(1), Customer('foo'), /// Customer(baf04077-a3c0-454b-ac6f-9fec00b8e170), Message(FromUsername='1',MessageId=-10) /// Message(geography'SRID=0;Collection(LineString(142.1 64.1,3.14 2.78))'),Message(duration'P6DT23H59M59.9999S') /// </summary> private static readonly Regex KeyPattern = new Regex(@"^(?:-{0,1}\d+?|\w*'.+?'|[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}|.+?=.+?)$", RegexOptions.IgnoreCase); /// <summary>The model to use when resolving the target of the URI.</summary> private readonly IEdmModel model; /// <summary>The result of parsing the context URI.</summary> private readonly ODataJsonLightContextUriParseResult parseResult; /// <summary> /// Initializes a new instance of the <see cref="ODataJsonLightContextUriParseResult"/> class. /// </summary> /// <param name="model">The model to use when resolving the target of the URI.</param> /// <param name="contextUriFromPayload">The context URI read from the payload.</param> private ODataJsonLightContextUriParser(IEdmModel model, Uri contextUriFromPayload) { Debug.Assert(model != null, "model != null"); if (!model.IsUserModel()) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_NoModel); } this.model = model; this.parseResult = new ODataJsonLightContextUriParseResult(contextUriFromPayload); } /// <summary> /// Creates a context URI parser and parses the context URI read from the payload. /// </summary> /// <param name="model">The model to use when resolving the target of the URI.</param> /// <param name="contextUriFromPayload">The string value of the odata.metadata annotation read from the payload.</param> /// <param name="payloadKind">The payload kind we expect the context URI to conform to.</param> /// <param name="readerBehavior">Reader behavior if the caller is a reader, null if no reader behavior is available.</param> /// <param name="needParseFragment">Whether the fragment after $metadata should be parsed, if set to false, only MetadataDocumentUri is parsed.</param> /// <returns>The result from parsing the context URI.</returns> internal static ODataJsonLightContextUriParseResult Parse( IEdmModel model, string contextUriFromPayload, ODataPayloadKind payloadKind, ODataReaderBehavior readerBehavior, bool needParseFragment) { if (contextUriFromPayload == null) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_NullMetadataDocumentUri); } // Create an absolute URI from the payload string // TODO: Support relative context uri and resolving other relative uris Uri contextUri; if (!Uri.TryCreate(contextUriFromPayload, UriKind.Absolute, out contextUri)) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_TopLevelContextUrlShouldBeAbsolute(contextUriFromPayload)); } ODataJsonLightContextUriParser parser = new ODataJsonLightContextUriParser(model, contextUri); parser.TokenizeContextUri(); if (needParseFragment) { parser.ParseContextUri(payloadKind, readerBehavior); } return parser.parseResult; } /// <summary> /// Extracts the value of the $select query option from the specified fragment. /// </summary> /// <param name="fragment">The fragment to extract the $select query option from.</param> /// <returns>The value of the $select query option or null if none exists.</returns> private static string ExtractSelectQueryOption(string fragment) { return fragment; } /// <summary> /// Parses a context URI read from the payload into its parts. /// </summary> private void TokenizeContextUri() { Uri contextUriFromPayload = this.parseResult.ContextUri; Debug.Assert(contextUriFromPayload != null && contextUriFromPayload.IsAbsoluteUri, "contextUriFromPayload != null && contextUriFromPayload.IsAbsoluteUri"); // Remove the fragment from the URI read from the payload UriBuilder uriBuilderWithoutFragment = new UriBuilder(contextUriFromPayload) { Fragment = null, }; // Make sure the metadata document URI from the settings matches the context URI in the payload. this.parseResult.MetadataDocumentUri = uriBuilderWithoutFragment.Uri; // Get the fragment of the context URI this.parseResult.Fragment = contextUriFromPayload.GetComponents(UriComponents.Fragment, UriFormat.Unescaped); } /// <summary> /// Applies the model and validates the context URI against it. /// </summary> /// <param name="expectedPayloadKind">The payload kind we expect the context URI to conform to.</param> /// <param name="readerBehavior">Reader behavior if the caller is a reader, null if no reader behavior is available.</param> private void ParseContextUri(ODataPayloadKind expectedPayloadKind, ODataReaderBehavior readerBehavior) { ODataPayloadKind detectedPayloadKind = this.ParseContextUriFragment(this.parseResult.Fragment, readerBehavior); // unsupported payload kind indicates that this is during payload kind detection, so we should not fail. bool detectedPayloadKindMatchesExpectation = detectedPayloadKind == expectedPayloadKind || expectedPayloadKind == ODataPayloadKind.Unsupported; if (detectedPayloadKind == ODataPayloadKind.Collection) { // If the detected payload kind is 'collection' it can always also be treated as a property. this.parseResult.DetectedPayloadKinds = new[] { ODataPayloadKind.Collection, ODataPayloadKind.Property }; if (expectedPayloadKind == ODataPayloadKind.Property) { detectedPayloadKindMatchesExpectation = true; } } else if (detectedPayloadKind == ODataPayloadKind.Entry) { this.parseResult.DetectedPayloadKinds = new[] { ODataPayloadKind.Entry, ODataPayloadKind.Delta }; if (expectedPayloadKind == ODataPayloadKind.Delta) { this.parseResult.DeltaKind = ODataDeltaKind.Entry; detectedPayloadKindMatchesExpectation = true; } } else { this.parseResult.DetectedPayloadKinds = new[] { detectedPayloadKind }; } // If the expected and detected payload kinds don't match and we are not running payload kind detection // right now (payloadKind == ODataPayloadKind.Unsupported) and we did not detect a collection kind for // an expected property kind (which is allowed), fail. if (!detectedPayloadKindMatchesExpectation) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_ContextUriDoesNotMatchExpectedPayloadKind(UriUtils.UriToString(this.parseResult.ContextUri), expectedPayloadKind.ToString())); } // NOTE: we interpret an empty select query option to mean that nothing should be projected // (whereas a missing select query option means everything should be projected). string selectQueryOption = this.parseResult.SelectQueryOption; if (selectQueryOption != null) { if (detectedPayloadKind != ODataPayloadKind.Feed && detectedPayloadKind != ODataPayloadKind.Entry && detectedPayloadKind != ODataPayloadKind.Delta) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidPayloadKindWithSelectQueryOption(expectedPayloadKind.ToString())); } } } /// <summary> /// Parses the fragment of a context URI. /// </summary> /// <param name="fragment">The fragment to parse</param> /// <param name="readerBehavior">Reader behavior if the caller is a reader, null if no reader behavior is available.</param> /// <returns>The detected payload kind based on parsing the fragment.</returns> [SuppressMessage("Microsoft.Maintainability", "CA1502", Justification = "Will be moving to non case statements later, no point in investing in reducing this now")] private ODataPayloadKind ParseContextUriFragment(string fragment, ODataReaderBehavior readerBehavior) { bool hasItemSelector = false; ODataDeltaKind kind = ODataDeltaKind.None; // Deal with /$entity if (fragment.EndsWith(ODataConstants.ContextUriFragmentItemSelector, StringComparison.Ordinal)) { hasItemSelector = true; fragment = fragment.Substring(0, fragment.Length - ODataConstants.ContextUriFragmentItemSelector.Length); } else if (fragment.EndsWith(ODataConstants.ContextUriDeltaFeed, StringComparison.Ordinal)) { kind = ODataDeltaKind.Feed; fragment = fragment.Substring(0, fragment.Length - ODataConstants.ContextUriDeltaFeed.Length); } else if (fragment.EndsWith(ODataConstants.ContextUriDeletedEntry, StringComparison.Ordinal)) { kind = ODataDeltaKind.DeletedEntry; fragment = fragment.Substring(0, fragment.Length - ODataConstants.ContextUriDeletedEntry.Length); } else if (fragment.EndsWith(ODataConstants.ContextUriDeltaLink, StringComparison.Ordinal)) { kind = ODataDeltaKind.Link; fragment = fragment.Substring(0, fragment.Length - ODataConstants.ContextUriDeltaLink.Length); } else if (fragment.EndsWith(ODataConstants.ContextUriDeletedLink, StringComparison.Ordinal)) { kind = ODataDeltaKind.DeletedLink; fragment = fragment.Substring(0, fragment.Length - ODataConstants.ContextUriDeletedLink.Length); } this.parseResult.DeltaKind = kind; // Deal with query option if (fragment.EndsWith(")", StringComparison.Ordinal)) { int index = fragment.Length - 2; for (int rcount = 1; rcount > 0 && index > 0; --index) { switch (fragment[index]) { case '(': rcount--; break; case ')': rcount++; break; } } if (index == 0) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidContextUrl(UriUtils.UriToString(this.parseResult.ContextUri))); } string previous = fragment.Substring(0, index + 1); // Don't treat Collection(Edm.Type) as SelectExpand segment if (!previous.Equals("Collection")) { string selectExpandStr = fragment.Substring(index + 2); selectExpandStr = selectExpandStr.Substring(0, selectExpandStr.Length - 1); // Do not treat Key as SelectExpand segment if (KeyPattern.IsMatch(selectExpandStr)) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_LastSegmentIsKeySegment(UriUtils.UriToString(this.parseResult.ContextUri))); } this.parseResult.SelectQueryOption = ExtractSelectQueryOption(selectExpandStr); fragment = previous; } } ODataPayloadKind detectedPayloadKind = ODataPayloadKind.Unsupported; EdmTypeResolver edmTypeResolver = new EdmTypeReaderResolver(this.model, readerBehavior); if (!fragment.Contains(ODataConstants.UriSegmentSeparator) && !hasItemSelector && kind == ODataDeltaKind.None) { // Service document: no fragment if (fragment.Length == 0) { detectedPayloadKind = ODataPayloadKind.ServiceDocument; } else if (fragment.Equals(ODataConstants.ContextUriFragmentNull, StringComparison.OrdinalIgnoreCase)) { detectedPayloadKind = ODataPayloadKind.Property; this.parseResult.IsNullProperty = true; } else if (fragment.Equals(ODataConstants.EntityReferenceCollectionSegmentName + "(" + ODataConstants.EntityReferenceSegmentName + ")")) { detectedPayloadKind = ODataPayloadKind.EntityReferenceLinks; } else if (fragment.Equals(ODataConstants.EntityReferenceSegmentName)) { detectedPayloadKind = ODataPayloadKind.EntityReferenceLink; } else { var foundNavigationSource = this.model.FindDeclaredNavigationSource(fragment); if (foundNavigationSource != null) { // Feed: {schema.entity-container.entity-set} or Singleton: {schema.entity-container.singleton} this.parseResult.NavigationSource = foundNavigationSource; this.parseResult.EdmType = edmTypeResolver.GetElementType(foundNavigationSource); detectedPayloadKind = foundNavigationSource is IEdmSingleton ? ODataPayloadKind.Entry : ODataPayloadKind.Feed; } else { // Property: {schema.type} or Collection({schema.type}) where schema.type is primitive or complex. detectedPayloadKind = this.ResolveType(fragment, readerBehavior); Debug.Assert( this.parseResult.EdmType.TypeKind == EdmTypeKind.Primitive || this.parseResult.EdmType.TypeKind == EdmTypeKind.Enum || this.parseResult.EdmType.TypeKind == EdmTypeKind.TypeDefinition || this.parseResult.EdmType.TypeKind == EdmTypeKind.Complex || this.parseResult.EdmType.TypeKind == EdmTypeKind.Collection || this.parseResult.EdmType.TypeKind == EdmTypeKind.Entity, "The first context URI segment must be a set or a non-entity type."); } } } else { Debug.Assert(this.parseResult.MetadataDocumentUri.IsAbsoluteUri, "this.parseResult.MetadataDocumentUri.IsAbsoluteUri"); string metadataDocumentStr = UriUtils.UriToString(this.parseResult.MetadataDocumentUri); if (!metadataDocumentStr.EndsWith(ODataConstants.UriMetadataSegment, StringComparison.Ordinal)) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidContextUrl(UriUtils.UriToString(this.parseResult.ContextUri))); } Uri serviceRoot = new Uri(metadataDocumentStr.Substring(0, metadataDocumentStr.Length - ODataConstants.UriMetadataSegment.Length)); ODataUriParser odataUriParser = new ODataUriParser(this.model, serviceRoot, new Uri(serviceRoot, fragment)); ODataPath path; try { path = odataUriParser.ParsePath(); } catch (ODataException) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidContextUrl(UriUtils.UriToString(this.parseResult.ContextUri))); } if (path.Count == 0) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidContextUrl(UriUtils.UriToString(this.parseResult.ContextUri))); } this.parseResult.Path = path; parseResult.NavigationSource = path.NavigationSource(); parseResult.EdmType = path.LastSegment.EdmType; ODataPathSegment lastSegment = path.TrimEndingTypeSegment().LastSegment; if (lastSegment is EntitySetSegment || lastSegment is NavigationPropertySegment) { if (kind != ODataDeltaKind.None) { detectedPayloadKind = ODataPayloadKind.Delta; } else { detectedPayloadKind = hasItemSelector ? ODataPayloadKind.Entry : ODataPayloadKind.Feed; } if (this.parseResult.EdmType is IEdmCollectionType) { var collectionTypeReference = this.parseResult.EdmType.ToTypeReference().AsCollection(); if (collectionTypeReference != null) { this.parseResult.EdmType = collectionTypeReference.ElementType().Definition; } } } else if (lastSegment is SingletonSegment) { detectedPayloadKind = ODataPayloadKind.Entry; } else if (path.IsIndividualProperty()) { detectedPayloadKind = ODataPayloadKind.Property; IEdmCollectionType collectionType = parseResult.EdmType as IEdmCollectionType; if (collectionType != null) { detectedPayloadKind = ODataPayloadKind.Collection; } } else { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidContextUrl(UriUtils.UriToString(this.parseResult.ContextUri))); } } return detectedPayloadKind; } /// <summary> /// Resolves a type. /// </summary> /// <param name="typeName">The type name.</param> /// <param name="readerBehavior">Reader behavior if the caller is a reader, null if no reader behavior is available.</param> /// <returns>The resolved Edm type.</returns> private ODataPayloadKind ResolveType(string typeName, ODataReaderBehavior readerBehavior) { string typeNameToResolve = EdmLibraryExtensions.GetCollectionItemTypeName(typeName) ?? typeName; bool isCollection = typeNameToResolve != typeName; EdmTypeKind typeKind; IEdmType resolvedType = MetadataUtils.ResolveTypeNameForRead(this.model, /*expectedType*/ null, typeNameToResolve, readerBehavior, out typeKind); if (resolvedType == null || resolvedType.TypeKind != EdmTypeKind.Primitive && resolvedType.TypeKind != EdmTypeKind.Enum && resolvedType.TypeKind != EdmTypeKind.Complex && resolvedType.TypeKind != EdmTypeKind.Entity && resolvedType.TypeKind != EdmTypeKind.TypeDefinition) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidEntitySetNameOrTypeName(UriUtils.UriToString(this.parseResult.ContextUri), typeName)); } if (resolvedType.TypeKind == EdmTypeKind.Entity) { this.parseResult.EdmType = resolvedType; return isCollection ? ODataPayloadKind.Feed : ODataPayloadKind.Entry; } resolvedType = isCollection ? EdmLibraryExtensions.GetCollectionType(resolvedType.ToTypeReference(true /*nullable*/)) : resolvedType; this.parseResult.EdmType = resolvedType; return isCollection ? ODataPayloadKind.Collection : ODataPayloadKind.Property; } } }
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> /// BPAY Receipts Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class DFBDataSet : EduHubDataSet<DFB> { /// <inheritdoc /> public override string Name { get { return "DFB"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal DFBDataSet(EduHubContext Context) : base(Context) { Index_FAM_CODE = new Lazy<Dictionary<string, IReadOnlyList<DFB>>>(() => this.ToGroupedDictionary(i => i.FAM_CODE)); Index_REFERENCE_NO = new Lazy<NullDictionary<string, IReadOnlyList<DFB>>>(() => this.ToGroupedNullDictionary(i => i.REFERENCE_NO)); Index_TID = new Lazy<Dictionary<int, DFB>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="DFB" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="DFB" /> fields for each CSV column header</returns> internal override Action<DFB, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<DFB, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "FAM_CODE": mapper[i] = (e, v) => e.FAM_CODE = v; break; case "REFERENCE_NO": mapper[i] = (e, v) => e.REFERENCE_NO = v; break; case "CUST_REFERENCE": mapper[i] = (e, v) => e.CUST_REFERENCE = v; break; case "RECORD_TYPE": mapper[i] = (e, v) => e.RECORD_TYPE = v; break; case "BILLER_CODE": mapper[i] = (e, v) => e.BILLER_CODE = v; break; case "PAYMENT_TYPE": mapper[i] = (e, v) => e.PAYMENT_TYPE = v; break; case "AMOUNT": mapper[i] = (e, v) => e.AMOUNT = v == null ? (decimal?)null : decimal.Parse(v); break; case "PAYMENT_DATE": mapper[i] = (e, v) => e.PAYMENT_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "DELETE_FLAG": mapper[i] = (e, v) => e.DELETE_FLAG = v; break; case "INVOICE_TID": mapper[i] = (e, v) => e.INVOICE_TID = v == null ? (int?)null : int.Parse(v); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="DFB" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="DFB" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="DFB" /> entities</param> /// <returns>A merged <see cref="IEnumerable{DFB}"/> of entities</returns> internal override IEnumerable<DFB> ApplyDeltaEntities(IEnumerable<DFB> Entities, List<DFB> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.FAM_CODE; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.FAM_CODE.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<DFB>>> Index_FAM_CODE; private Lazy<NullDictionary<string, IReadOnlyList<DFB>>> Index_REFERENCE_NO; private Lazy<Dictionary<int, DFB>> Index_TID; #endregion #region Index Methods /// <summary> /// Find DFB by FAM_CODE field /// </summary> /// <param name="FAM_CODE">FAM_CODE value used to find DFB</param> /// <returns>List of related DFB entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<DFB> FindByFAM_CODE(string FAM_CODE) { return Index_FAM_CODE.Value[FAM_CODE]; } /// <summary> /// Attempt to find DFB by FAM_CODE field /// </summary> /// <param name="FAM_CODE">FAM_CODE value used to find DFB</param> /// <param name="Value">List of related DFB entities</param> /// <returns>True if the list of related DFB entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByFAM_CODE(string FAM_CODE, out IReadOnlyList<DFB> Value) { return Index_FAM_CODE.Value.TryGetValue(FAM_CODE, out Value); } /// <summary> /// Attempt to find DFB by FAM_CODE field /// </summary> /// <param name="FAM_CODE">FAM_CODE value used to find DFB</param> /// <returns>List of related DFB entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<DFB> TryFindByFAM_CODE(string FAM_CODE) { IReadOnlyList<DFB> value; if (Index_FAM_CODE.Value.TryGetValue(FAM_CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find DFB by REFERENCE_NO field /// </summary> /// <param name="REFERENCE_NO">REFERENCE_NO value used to find DFB</param> /// <returns>List of related DFB entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<DFB> FindByREFERENCE_NO(string REFERENCE_NO) { return Index_REFERENCE_NO.Value[REFERENCE_NO]; } /// <summary> /// Attempt to find DFB by REFERENCE_NO field /// </summary> /// <param name="REFERENCE_NO">REFERENCE_NO value used to find DFB</param> /// <param name="Value">List of related DFB entities</param> /// <returns>True if the list of related DFB entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByREFERENCE_NO(string REFERENCE_NO, out IReadOnlyList<DFB> Value) { return Index_REFERENCE_NO.Value.TryGetValue(REFERENCE_NO, out Value); } /// <summary> /// Attempt to find DFB by REFERENCE_NO field /// </summary> /// <param name="REFERENCE_NO">REFERENCE_NO value used to find DFB</param> /// <returns>List of related DFB entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<DFB> TryFindByREFERENCE_NO(string REFERENCE_NO) { IReadOnlyList<DFB> value; if (Index_REFERENCE_NO.Value.TryGetValue(REFERENCE_NO, out value)) { return value; } else { return null; } } /// <summary> /// Find DFB by TID field /// </summary> /// <param name="TID">TID value used to find DFB</param> /// <returns>Related DFB entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public DFB FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find DFB by TID field /// </summary> /// <param name="TID">TID value used to find DFB</param> /// <param name="Value">Related DFB entity</param> /// <returns>True if the related DFB entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out DFB Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find DFB by TID field /// </summary> /// <param name="TID">TID value used to find DFB</param> /// <returns>Related DFB entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public DFB TryFindByTID(int TID) { DFB value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a DFB 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].[DFB]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[DFB]( [TID] int IDENTITY NOT NULL, [FAM_CODE] varchar(10) NOT NULL, [REFERENCE_NO] varchar(21) NULL, [CUST_REFERENCE] varchar(20) NULL, [RECORD_TYPE] varchar(2) NULL, [BILLER_CODE] varchar(10) NULL, [PAYMENT_TYPE] varchar(2) NULL, [AMOUNT] money NULL, [PAYMENT_DATE] datetime NULL, [DELETE_FLAG] varchar(1) NULL, [INVOICE_TID] int NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [DFB_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [DFB_Index_FAM_CODE] ON [dbo].[DFB] ( [FAM_CODE] ASC ); CREATE NONCLUSTERED INDEX [DFB_Index_REFERENCE_NO] ON [dbo].[DFB] ( [REFERENCE_NO] 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].[DFB]') AND name = N'DFB_Index_REFERENCE_NO') ALTER INDEX [DFB_Index_REFERENCE_NO] ON [dbo].[DFB] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[DFB]') AND name = N'DFB_Index_TID') ALTER INDEX [DFB_Index_TID] ON [dbo].[DFB] 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].[DFB]') AND name = N'DFB_Index_REFERENCE_NO') ALTER INDEX [DFB_Index_REFERENCE_NO] ON [dbo].[DFB] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[DFB]') AND name = N'DFB_Index_TID') ALTER INDEX [DFB_Index_TID] ON [dbo].[DFB] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="DFB"/> 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="DFB"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<DFB> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[DFB] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the DFB data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the DFB data set</returns> public override EduHubDataSetDataReader<DFB> GetDataSetDataReader() { return new DFBDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the DFB data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the DFB data set</returns> public override EduHubDataSetDataReader<DFB> GetDataSetDataReader(List<DFB> Entities) { return new DFBDataReader(new EduHubDataSetLoadedReader<DFB>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class DFBDataReader : EduHubDataSetDataReader<DFB> { public DFBDataReader(IEduHubDataSetReader<DFB> Reader) : base (Reader) { } public override int FieldCount { get { return 14; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // FAM_CODE return Current.FAM_CODE; case 2: // REFERENCE_NO return Current.REFERENCE_NO; case 3: // CUST_REFERENCE return Current.CUST_REFERENCE; case 4: // RECORD_TYPE return Current.RECORD_TYPE; case 5: // BILLER_CODE return Current.BILLER_CODE; case 6: // PAYMENT_TYPE return Current.PAYMENT_TYPE; case 7: // AMOUNT return Current.AMOUNT; case 8: // PAYMENT_DATE return Current.PAYMENT_DATE; case 9: // DELETE_FLAG return Current.DELETE_FLAG; case 10: // INVOICE_TID return Current.INVOICE_TID; 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 2: // REFERENCE_NO return Current.REFERENCE_NO == null; case 3: // CUST_REFERENCE return Current.CUST_REFERENCE == null; case 4: // RECORD_TYPE return Current.RECORD_TYPE == null; case 5: // BILLER_CODE return Current.BILLER_CODE == null; case 6: // PAYMENT_TYPE return Current.PAYMENT_TYPE == null; case 7: // AMOUNT return Current.AMOUNT == null; case 8: // PAYMENT_DATE return Current.PAYMENT_DATE == null; case 9: // DELETE_FLAG return Current.DELETE_FLAG == null; case 10: // INVOICE_TID return Current.INVOICE_TID == 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: // TID return "TID"; case 1: // FAM_CODE return "FAM_CODE"; case 2: // REFERENCE_NO return "REFERENCE_NO"; case 3: // CUST_REFERENCE return "CUST_REFERENCE"; case 4: // RECORD_TYPE return "RECORD_TYPE"; case 5: // BILLER_CODE return "BILLER_CODE"; case 6: // PAYMENT_TYPE return "PAYMENT_TYPE"; case 7: // AMOUNT return "AMOUNT"; case 8: // PAYMENT_DATE return "PAYMENT_DATE"; case 9: // DELETE_FLAG return "DELETE_FLAG"; case 10: // INVOICE_TID return "INVOICE_TID"; 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 "TID": return 0; case "FAM_CODE": return 1; case "REFERENCE_NO": return 2; case "CUST_REFERENCE": return 3; case "RECORD_TYPE": return 4; case "BILLER_CODE": return 5; case "PAYMENT_TYPE": return 6; case "AMOUNT": return 7; case "PAYMENT_DATE": return 8; case "DELETE_FLAG": return 9; case "INVOICE_TID": 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.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// Bank or credit union. /// </summary> public class BankOrCreditUnion_Core : TypeCore, IFinancialService { public BankOrCreditUnion_Core() { this._TypeId = 32; this._Id = "BankOrCreditUnion"; this._Schema_Org_Url = "http://schema.org/BankOrCreditUnion"; string label = ""; GetLabel(out label, "BankOrCreditUnion", typeof(BankOrCreditUnion_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,103}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{103}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// Copyright 2010 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using NodaTime.Calendars; using NodaTime.Text; using NUnit.Framework; namespace NodaTime.Test { public class PeriodTest { // June 19th 2010, 2:30:15am private static readonly LocalDateTime TestDateTime1 = new LocalDateTime(2010, 6, 19, 2, 30, 15); // June 19th 2010, 4:45:10am private static readonly LocalDateTime TestDateTime2 = new LocalDateTime(2010, 6, 19, 4, 45, 10); // June 19th 2010 private static readonly LocalDate TestDate1 = new LocalDate(2010, 6, 19); // March 1st 2011 private static readonly LocalDate TestDate2 = new LocalDate(2011, 3, 1); // March 1st 2012 private static readonly LocalDate TestDate3 = new LocalDate(2012, 3, 1); private const PeriodUnits HoursMinutesPeriodType = PeriodUnits.Hours | PeriodUnits.Minutes; private static readonly PeriodUnits[] AllPeriodUnits = (PeriodUnits[])Enum.GetValues(typeof(PeriodUnits)); [Test] public void BetweenLocalDateTimes_WithoutSpecifyingUnits_OmitsWeeks() { Period actual = Period.Between(new LocalDateTime(2012, 2, 21, 0, 0), new LocalDateTime(2012, 2, 28, 0, 0)); Period expected = Period.FromDays(7); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDateTimes_MovingForwardWithAllFields_GivesExactResult() { Period actual = Period.Between(TestDateTime1, TestDateTime2); Period expected = Period.FromHours(2) + Period.FromMinutes(14) + Period.FromSeconds(55); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDateTimes_MovingBackwardWithAllFields_GivesExactResult() { Period actual = Period.Between(TestDateTime2, TestDateTime1); Period expected = Period.FromHours(-2) + Period.FromMinutes(-14) + Period.FromSeconds(-55); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDateTimes_MovingForwardWithHoursAndMinutes_RoundsTowardsStart() { Period actual = Period.Between(TestDateTime1, TestDateTime2, HoursMinutesPeriodType); Period expected = Period.FromHours(2) + Period.FromMinutes(14); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDateTimes_MovingBackwardWithHoursAndMinutes_RoundsTowardsStart() { Period actual = Period.Between(TestDateTime2, TestDateTime1, HoursMinutesPeriodType); Period expected = Period.FromHours(-2) + Period.FromMinutes(-14); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDateTimes_AcrossDays() { Period expected = Period.FromHours(23) + Period.FromMinutes(59); Period actual = Period.Between(TestDateTime1, TestDateTime1.PlusDays(1).PlusMinutes(-1)); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDateTimes_AcrossDays_MinutesAndSeconds() { Period expected = Period.FromMinutes(24 * 60 - 1) + Period.FromSeconds(59); Period actual = Period.Between(TestDateTime1, TestDateTime1.PlusDays(1).PlusSeconds(-1), PeriodUnits.Minutes | PeriodUnits.Seconds); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDateTimes_NotInt64Representable() { LocalDateTime start = new LocalDateTime(-5000, 1, 1, 0, 1, 2, 123); LocalDateTime end = new LocalDateTime( 9000, 1, 1, 1, 2, 3, 456); Assert.False((end.ToLocalInstant().TimeSinceLocalEpoch - start.ToLocalInstant().TimeSinceLocalEpoch).IsInt64Representable); Period expected = new PeriodBuilder { // 365.2425 * 14000 = 5113395 Hours = 5113395L * 24 + 1, Minutes = 1, Seconds = 1, Milliseconds = 333 }.Build(); Period actual = Period.Between(start, end, PeriodUnits.AllTimeUnits); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDates_InvalidUnits() { Assert.Throws<ArgumentException>(() => Period.Between(TestDate1, TestDate2, 0)); Assert.Throws<ArgumentException>(() => Period.Between(TestDate1, TestDate2, (PeriodUnits) (-1))); Assert.Throws<ArgumentException>(() => Period.Between(TestDate1, TestDate2, PeriodUnits.AllTimeUnits)); Assert.Throws<ArgumentException>(() => Period.Between(TestDate1, TestDate2, PeriodUnits.Years | PeriodUnits.Hours)); } [Test] public void BetweenLocalDates_DifferentCalendarSystems_Throws() { LocalDate start = new LocalDate(2017, 11, 1, CalendarSystem.Coptic); LocalDate end = new LocalDate(2017, 11, 5, CalendarSystem.Gregorian); Assert.Throws<ArgumentException>(() => Period.Between(start, end)); } [Test] [TestCase("2016-05-16", "2019-03-13", PeriodUnits.Years, 2)] [TestCase("2016-05-16", "2017-07-13", PeriodUnits.Months, 13)] [TestCase("2016-05-16", "2016-07-13", PeriodUnits.Weeks, 8)] [TestCase("2016-05-16", "2016-07-13", PeriodUnits.Days, 58)] public void BetweenLocalDates_SingleUnit(string startText, string endText, PeriodUnits units, int expectedValue) { var start = LocalDatePattern.Iso.Parse(startText).Value; var end = LocalDatePattern.Iso.Parse(endText).Value; var actual = Period.Between(start, end, units); var expected = new PeriodBuilder { [units] = expectedValue }.Build(); Assert.AreEqual(expected, actual); } [Test] public void DaysBetweenLocalDates_DifferentCalendarsThrows() { var start = new LocalDate(2020, 6, 13, CalendarSystem.Iso); var end = new LocalDate(2020, 6, 15, CalendarSystem.Julian); Assert.Throws<ArgumentException>(() => Period.DaysBetween(start, end)); } [Test] public void DaysBetweenLocalDates_SameDatesReturnsZero() { var start = new LocalDate(2020, 6, 13, CalendarSystem.Iso); var end = start; var expected = 0; var actual = Period.DaysBetween(start, end); Assert.AreEqual(expected, actual); } [Test] [TestCase("2016-05-16", "2016-05-17", 1)] [TestCase("2020-06-15", "2020-06-18", 3)] [TestCase("2016-05-16", "2016-05-26", 10)] [TestCase("2020-06-15", "2021-06-19", 369)] [TestCase("2020-03-23", "2020-06-12", 81)] public void DaysBetweenLocalDates(string startText, string endText, int expected) { var start = LocalDatePattern.Iso.Parse(startText).Value; var end = LocalDatePattern.Iso.Parse(endText).Value; var actual = Period.DaysBetween(start, end); Assert.AreEqual(expected, actual); } [Test] [TestCase("2016-05-16", "2016-05-15", -1)] [TestCase("2020-06-15", "2020-06-12", -3)] [TestCase("2016-05-16", "2016-05-06", -10)] [TestCase("2021-06-19", "2020-06-15", -369)] [TestCase("2020-05-16", "2019-05-16", -366)] public void DaysBetweenLocalDates_StartDateGreaterThanEndDate(string startText, string endText, int expected) { var start = LocalDatePattern.Iso.Parse(startText).Value; var end = LocalDatePattern.Iso.Parse(endText).Value; var actual = Period.DaysBetween(start, end); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDates_MovingForwardNoLeapYears_WithExactResults() { Period actual = Period.Between(TestDate1, TestDate2); Period expected = Period.FromMonths(8) + Period.FromDays(10); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDates_MovingForwardInLeapYear_WithExactResults() { Period actual = Period.Between(TestDate1, TestDate3); Period expected = Period.FromYears(1) + Period.FromMonths(8) + Period.FromDays(11); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDates_MovingBackwardNoLeapYears_WithExactResults() { Period actual = Period.Between(TestDate2, TestDate1); Period expected = Period.FromMonths(-8) + Period.FromDays(-12); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDates_MovingBackwardInLeapYear_WithExactResults() { // This is asymmetric with moving forward, because we first take off a whole year, which // takes us to March 1st 2011, then 8 months to take us to July 1st 2010, then 12 days // to take us back to June 19th. In this case, the fact that our start date is in a leap // year had no effect. Period actual = Period.Between(TestDate3, TestDate1); Period expected = Period.FromYears(-1) + Period.FromMonths(-8) + Period.FromDays(-12); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDates_MovingForward_WithJustMonths() { Period actual = Period.Between(TestDate1, TestDate3, PeriodUnits.Months); Period expected = Period.FromMonths(20); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDates_MovingBackward_WithJustMonths() { Period actual = Period.Between(TestDate3, TestDate1, PeriodUnits.Months); Period expected = Period.FromMonths(-20); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalDates_AsymmetricForwardAndBackward() { // February 10th 2010 LocalDate d1 = new LocalDate(2010, 2, 10); // March 30th 2010 LocalDate d2 = new LocalDate(2010, 3, 30); // Going forward, we go to March 10th (1 month) then March 30th (20 days) Assert.AreEqual(Period.FromMonths(1) + Period.FromDays(20), Period.Between(d1, d2)); // Going backward, we go to February 28th (-1 month, day is rounded) then February 10th (-18 days) Assert.AreEqual(Period.FromMonths(-1) + Period.FromDays(-18), Period.Between(d2, d1)); } [Test] public void BetweenLocalDates_EndOfMonth() { LocalDate d1 = new LocalDate(2013, 3, 31); LocalDate d2 = new LocalDate(2013, 4, 30); Assert.AreEqual(Period.FromMonths(1), Period.Between(d1, d2)); Assert.AreEqual(Period.FromDays(-30), Period.Between(d2, d1)); } [Test] public void BetweenLocalDates_OnLeapYear() { LocalDate d1 = new LocalDate(2012, 2, 29); LocalDate d2 = new LocalDate(2013, 2, 28); Assert.AreEqual(Period.FromYears(1), Period.Between(d1, d2)); // Go back from February 28th 2013 to March 28th 2012, then back 28 days to February 29th 2012 Assert.AreEqual(Period.FromMonths(-11) + Period.FromDays(-28), Period.Between(d2, d1)); } [Test] public void BetweenLocalDates_AfterLeapYear() { LocalDate d1 = new LocalDate(2012, 3, 5); LocalDate d2 = new LocalDate(2013, 3, 5); Assert.AreEqual(Period.FromYears(1), Period.Between(d1, d2)); Assert.AreEqual(Period.FromYears(-1), Period.Between(d2, d1)); } [Test] public void BetweenLocalDateTimes_OnLeapYear() { LocalDateTime dt1 = new LocalDateTime(2012, 2, 29, 2, 0); LocalDateTime dt2 = new LocalDateTime(2012, 2, 29, 4, 0); LocalDateTime dt3 = new LocalDateTime(2013, 2, 28, 3, 0); Assert.AreEqual(Parse("P1YT1H"), Period.Between(dt1, dt3)); Assert.AreEqual(Parse("P11M29DT23H"), Period.Between(dt2, dt3)); Assert.AreEqual(Parse("P-11M-28DT-1H"), Period.Between(dt3, dt1)); Assert.AreEqual(Parse("P-11M-27DT-23H"), Period.Between(dt3, dt2)); } [Test] public void BetweenLocalDateTimes_OnLeapYearIslamic() { var calendar = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Civil); Assert.IsTrue(calendar.IsLeapYear(2)); Assert.IsFalse(calendar.IsLeapYear(3)); LocalDateTime dt1 = new LocalDateTime(2, 12, 30, 2, 0, calendar); LocalDateTime dt2 = new LocalDateTime(2, 12, 30, 4, 0, calendar); LocalDateTime dt3 = new LocalDateTime(3, 12, 29, 3, 0, calendar); // Adding a year truncates to 0003-12-28T02:00:00, then add an hour. Assert.AreEqual(Parse("P1YT1H"), Period.Between(dt1, dt3)); // Adding a year would overshoot. Adding 11 months takes us to month 03-11-30T04:00. // Adding another 28 days takes us to 03-12-28T04:00, then add another 23 hours to finish. Assert.AreEqual(Parse("P11M28DT23H"), Period.Between(dt2, dt3)); // Subtracting 11 months takes us to 03-01-29T03:00. Subtracting another 29 days // takes us to 02-12-30T03:00, and another hour to get to the target. Assert.AreEqual(Parse("P-11M-29DT-1H"), Period.Between(dt3, dt1)); Assert.AreEqual(Parse("P-11M-28DT-23H"), Period.Between(dt3, dt2)); } [Test] public void BetweenLocalDateTimes_InvalidUnits() { Assert.Throws<ArgumentException>(() => Period.Between(TestDate1, TestDate2, 0)); Assert.Throws<ArgumentException>(() => Period.Between(TestDate1, TestDate2, (PeriodUnits)(-1))); } [Test] public void BetweenLocalTimes_InvalidUnits() { LocalTime t1 = new LocalTime(10, 0); LocalTime t2 = LocalTime.FromHourMinuteSecondMillisecondTick(15, 30, 45, 20, 5); Assert.Throws<ArgumentException>(() => Period.Between(t1, t2, 0)); Assert.Throws<ArgumentException>(() => Period.Between(t1, t2, (PeriodUnits)(-1))); Assert.Throws<ArgumentException>(() => Period.Between(t1, t2, PeriodUnits.YearMonthDay)); Assert.Throws<ArgumentException>(() => Period.Between(t1, t2, PeriodUnits.Years | PeriodUnits.Hours)); } [Test] [TestCase("01:02:03", "05:00:00", PeriodUnits.Hours, 3)] [TestCase("01:02:03", "03:00:00", PeriodUnits.Minutes, 117)] [TestCase("01:02:03", "01:05:02", PeriodUnits.Seconds, 179)] [TestCase("01:02:03", "01:02:04.1234", PeriodUnits.Milliseconds, 1123)] [TestCase("01:02:03", "01:02:04.1234", PeriodUnits.Ticks, 11234000)] [TestCase("01:02:03", "01:02:04.1234", PeriodUnits.Nanoseconds, 1123400000)] public void BetweenLocalTimes_SingleUnit(string startText, string endText, PeriodUnits units, long expectedValue) { var start = LocalTimePattern.ExtendedIso.Parse(startText).Value; var end = LocalTimePattern.ExtendedIso.Parse(endText).Value; var actual = Period.Between(start, end, units); var expected = new PeriodBuilder { [units] = expectedValue }.Build(); Assert.AreEqual(expected, actual); } [Test] public void BetweenLocalTimes_MovingForwards() { LocalTime t1 = new LocalTime(10, 0); LocalTime t2 = LocalTime.FromHourMinuteSecondMillisecondTick(15, 30, 45, 20, 5); Assert.AreEqual(Period.FromHours(5) + Period.FromMinutes(30) + Period.FromSeconds(45) + Period.FromMilliseconds(20) + Period.FromTicks(5), Period.Between(t1, t2)); } [Test] public void BetweenLocalTimes_MovingBackwards() { LocalTime t1 = LocalTime.FromHourMinuteSecondMillisecondTick(15, 30, 45, 20, 5); LocalTime t2 = new LocalTime(10, 0); Assert.AreEqual(Period.FromHours(-5) + Period.FromMinutes(-30) + Period.FromSeconds(-45) + Period.FromMilliseconds(-20) + Period.FromTicks(-5), Period.Between(t1, t2)); } [Test] public void BetweenLocalTimes_MovingForwards_WithJustHours() { LocalTime t1 = new LocalTime(11, 30); LocalTime t2 = new LocalTime(17, 15); Assert.AreEqual(Period.FromHours(5), Period.Between(t1, t2, PeriodUnits.Hours)); } [Test] public void BetweenLocalTimes_MovingBackwards_WithJustHours() { LocalTime t1 = new LocalTime(17, 15); LocalTime t2 = new LocalTime(11, 30); Assert.AreEqual(Period.FromHours(-5), Period.Between(t1, t2, PeriodUnits.Hours)); } [Test] public void Addition_WithDifferent_PeriodTypes() { Period p1 = Period.FromHours(3); Period p2 = Period.FromMinutes(20); Period sum = p1 + p2; Assert.AreEqual(3, sum.Hours); Assert.AreEqual(20, sum.Minutes); } [Test] public void Addition_With_IdenticalPeriodTypes() { Period p1 = Period.FromHours(3); Period p2 = Period.FromHours(2); Period sum = p1 + p2; Assert.AreEqual(5, sum.Hours); Assert.AreEqual(sum, Period.Add(p1, p2)); } [Test] public void Addition_DayCrossingMonthBoundary() { LocalDateTime start = new LocalDateTime(2010, 2, 20, 10, 0); LocalDateTime result = start + Period.FromDays(10); Assert.AreEqual(new LocalDateTime(2010, 3, 2, 10, 0), result); } [Test] public void Addition_OneYearOnLeapDay() { LocalDateTime start = new LocalDateTime(2012, 2, 29, 10, 0); LocalDateTime result = start + Period.FromYears(1); // Feb 29th becomes Feb 28th Assert.AreEqual(new LocalDateTime(2013, 2, 28, 10, 0), result); } [Test] public void Addition_FourYearsOnLeapDay() { LocalDateTime start = new LocalDateTime(2012, 2, 29, 10, 0); LocalDateTime result = start + Period.FromYears(4); // Feb 29th is still valid in 2016 Assert.AreEqual(new LocalDateTime(2016, 2, 29, 10, 0), result); } [Test] public void Addition_YearMonthDay() { // One year, one month, two days Period period = Period.FromYears(1) + Period.FromMonths(1) + Period.FromDays(2); LocalDateTime start = new LocalDateTime(2007, 1, 30, 0, 0); // Periods are added in order, so this becomes... // Add one year: Jan 30th 2008 // Add one month: Feb 29th 2008 // Add two days: March 2nd 2008 // If we added the days first, we'd end up with March 1st instead. LocalDateTime result = start + period; Assert.AreEqual(new LocalDateTime(2008, 3, 2, 0, 0), result); } [Test] public void Subtraction_WithDifferent_PeriodTypes() { Period p1 = Period.FromHours(3); Period p2 = Period.FromMinutes(20); Period difference = p1 - p2; Assert.AreEqual(3, difference.Hours); Assert.AreEqual(-20, difference.Minutes); Assert.AreEqual(difference, Period.Subtract(p1, p2)); } [Test] public void Subtraction_With_IdenticalPeriodTypes() { Period p1 = Period.FromHours(3); Period p2 = Period.FromHours(2); Period difference = p1 - p2; Assert.AreEqual(1, difference.Hours); Assert.AreEqual(difference, Period.Subtract(p1, p2)); } [Test] public void Equality_WhenEqual() { Assert.AreEqual(Period.FromHours(10), Period.FromHours(10)); Assert.AreEqual(Period.FromMinutes(15), Period.FromMinutes(15)); Assert.AreEqual(Period.FromDays(5), Period.FromDays(5)); } [Test] public void Equality_WithDifferentPeriodTypes_OnlyConsidersValues() { Period allFields = Period.FromMinutes(1) + Period.FromHours(1) - Period.FromMinutes(1); Period justHours = Period.FromHours(1); Assert.AreEqual(allFields, justHours); } [Test] public void Equality_WhenUnequal() { Assert.IsFalse(Period.FromHours(10).Equals(Period.FromHours(20))); Assert.IsFalse(Period.FromMinutes(15).Equals(Period.FromSeconds(15))); Assert.IsFalse(Period.FromHours(1).Equals(Period.FromMinutes(60))); Assert.IsFalse(Period.FromHours(1).Equals(new object())); Assert.IsFalse(Period.FromHours(1).Equals(null)); Assert.IsFalse(Period.FromHours(1).Equals((object?) null)); } [Test] public void EqualityOperators() { Period val1 = Period.FromHours(1); Period val2 = Period.FromHours(1); Period val3 = Period.FromHours(2); Period? val4 = null; Assert.IsTrue(val1 == val2); Assert.IsFalse(val1 == val3); Assert.IsFalse(val1 == val4); Assert.IsFalse(val4 == val1); Assert.IsTrue(val4 == null); Assert.IsTrue(null == val4); Assert.IsFalse(val1 != val2); Assert.IsTrue(val1 != val3); Assert.IsTrue(val1 != val4); Assert.IsTrue(val4 != val1); Assert.IsFalse(val4 != null); Assert.IsFalse(null != val4); } [Test] [TestCase(PeriodUnits.Years, false)] [TestCase(PeriodUnits.Weeks, false)] [TestCase(PeriodUnits.Months, false)] [TestCase(PeriodUnits.Days, false)] [TestCase(PeriodUnits.Hours, true)] [TestCase(PeriodUnits.Minutes, true)] [TestCase(PeriodUnits.Seconds, true)] [TestCase(PeriodUnits.Milliseconds, true)] [TestCase(PeriodUnits.Ticks, true)] [TestCase(PeriodUnits.Nanoseconds, true)] public void HasTimeComponent_SingleValued(PeriodUnits unit, bool hasTimeComponent) { var period = new PeriodBuilder {[unit] = 1}.Build(); Assert.AreEqual(hasTimeComponent, period.HasTimeComponent); } [Test] [TestCase(PeriodUnits.Years, true)] [TestCase(PeriodUnits.Weeks, true)] [TestCase(PeriodUnits.Months, true)] [TestCase(PeriodUnits.Days, true)] [TestCase(PeriodUnits.Hours, false)] [TestCase(PeriodUnits.Minutes, false)] [TestCase(PeriodUnits.Seconds, false)] [TestCase(PeriodUnits.Milliseconds, false)] [TestCase(PeriodUnits.Ticks, false)] [TestCase(PeriodUnits.Nanoseconds, false)] public void HasDateComponent_SingleValued(PeriodUnits unit, bool hasDateComponent) { var period = new PeriodBuilder {[unit] = 1 }.Build(); Assert.AreEqual(hasDateComponent, period.HasDateComponent); } [Test] public void HasTimeComponent_Compound() { LocalDateTime dt1 = new LocalDateTime(2000, 1, 1, 10, 45, 00); LocalDateTime dt2 = new LocalDateTime(2000, 2, 4, 11, 50, 00); // Case 1: Entire period is date-based (no time units available) Assert.IsFalse(Period.Between(dt1.Date, dt2.Date).HasTimeComponent); // Case 2: Period contains date and time units, but time units are all zero Assert.IsFalse(Period.Between(dt1.Date + LocalTime.Midnight, dt2.Date + LocalTime.Midnight).HasTimeComponent); // Case 3: Entire period is time-based, but 0. (Same local time twice here.) Assert.IsFalse(Period.Between(dt1.TimeOfDay, dt1.TimeOfDay).HasTimeComponent); // Case 4: Period contains date and time units, and some time units are non-zero Assert.IsTrue(Period.Between(dt1, dt2).HasTimeComponent); // Case 5: Entire period is time-based, and some time units are non-zero Assert.IsTrue(Period.Between(dt1.TimeOfDay, dt2.TimeOfDay).HasTimeComponent); } [Test] public void HasDateComponent_Compound() { LocalDateTime dt1 = new LocalDateTime(2000, 1, 1, 10, 45, 00); LocalDateTime dt2 = new LocalDateTime(2000, 2, 4, 11, 50, 00); // Case 1: Entire period is time-based (no date units available) Assert.IsFalse(Period.Between(dt1.TimeOfDay, dt2.TimeOfDay).HasDateComponent); // Case 2: Period contains date and time units, but date units are all zero Assert.IsFalse(Period.Between(dt1, dt1.Date + dt2.TimeOfDay).HasDateComponent); // Case 3: Entire period is date-based, but 0. (Same local date twice here.) Assert.IsFalse(Period.Between(dt1.Date, dt1.Date).HasDateComponent); // Case 4: Period contains date and time units, and some date units are non-zero Assert.IsTrue(Period.Between(dt1, dt2).HasDateComponent); // Case 5: Entire period is date-based, and some time units are non-zero Assert.IsTrue(Period.Between(dt1.Date, dt2.Date).HasDateComponent); } [Test] public void ToString_Positive() { Period period = Period.FromDays(1) + Period.FromHours(2); Assert.AreEqual("P1DT2H", period.ToString()); } [Test] public void ToString_AllUnits() { Period period = new Period(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Assert.AreEqual("P1Y2M3W4DT5H6M7S8s9t10n", period.ToString()); } [Test] public void ToString_Negative() { Period period = Period.FromDays(-1) + Period.FromHours(-2); Assert.AreEqual("P-1DT-2H", period.ToString()); } [Test] public void ToString_Mixed() { Period period = Period.FromDays(-1) + Period.FromHours(2); Assert.AreEqual("P-1DT2H", period.ToString()); } [Test] public void ToString_Zero() { Assert.AreEqual("P0D", Period.Zero.ToString()); } [Test] public void ToBuilder_SingleUnit() { var builder = Period.FromHours(5).ToBuilder(); var expected = new PeriodBuilder { Hours = 5 }.Build(); Assert.AreEqual(expected, builder.Build()); } [Test] public void ToBuilder_MultipleUnits() { var builder = (Period.FromHours(5) + Period.FromWeeks(2)).ToBuilder(); var expected = new PeriodBuilder { Hours = 5, Weeks = 2 }.Build(); Assert.AreEqual(expected, builder.Build()); } [Test] public void Normalize_Weeks() { var original = new PeriodBuilder { Weeks = 2, Days = 5 }.Build(); var normalized = original.Normalize(); var expected = new PeriodBuilder { Days = 19 }.Build(); Assert.AreEqual(expected, normalized); } [Test] public void Normalize_Hours() { var original = new PeriodBuilder { Hours = 25, Days = 1 }.Build(); var normalized = original.Normalize(); var expected = new PeriodBuilder { Hours = 1, Days = 2 }.Build(); Assert.AreEqual(expected, normalized); } [Test] public void Normalize_Minutes() { var original = new PeriodBuilder { Hours = 1, Minutes = 150 }.Build(); var normalized = original.Normalize(); var expected = new PeriodBuilder { Hours = 3, Minutes = 30}.Build(); Assert.AreEqual(expected, normalized); } [Test] public void Normalize_Seconds() { var original = new PeriodBuilder { Minutes = 1, Seconds = 150 }.Build(); var normalized = original.Normalize(); var expected = new PeriodBuilder { Minutes = 3, Seconds = 30 }.Build(); Assert.AreEqual(expected, normalized); } [Test] public void Normalize_Milliseconds() { var original = new PeriodBuilder { Seconds = 1, Milliseconds = 1500 }.Build(); var normalized = original.Normalize(); var expected = new PeriodBuilder { Seconds = 2, Milliseconds= 500 }.Build(); Assert.AreEqual(expected, normalized); } [Test] public void Normalize_Ticks() { var original = new PeriodBuilder { Milliseconds = 1, Ticks = 15000 }.Build(); var normalized = original.Normalize(); var expected = new PeriodBuilder { Milliseconds = 2, Ticks = 0, Nanoseconds = 500000 }.Build(); Assert.AreEqual(expected, normalized); } [Test] public void Normalize_Nanoseconds() { var original = new PeriodBuilder { Ticks = 1, Nanoseconds = 150 }.Build(); var normalized = original.Normalize(); var expected = new PeriodBuilder { Nanoseconds = 250}.Build(); Assert.AreEqual(expected, normalized); } [Test] public void Normalize_MultipleFields() { var original = new PeriodBuilder { Hours = 1, Minutes = 119, Seconds = 150 }.Build(); var normalized = original.Normalize(); var expected = new PeriodBuilder { Hours = 3, Minutes = 1, Seconds = 30 }.Build(); Assert.AreEqual(expected, normalized); } [Test] public void Normalize_AllNegative() { var original = new PeriodBuilder { Hours = -1, Minutes = -119, Seconds = -150 }.Build(); var normalized = original.Normalize(); var expected = new PeriodBuilder { Hours = -3, Minutes = -1, Seconds = -30 }.Build(); Assert.AreEqual(expected, normalized); } [Test] public void Normalize_MixedSigns_PositiveResult() { var original = new PeriodBuilder { Hours = 3, Minutes = -1 }.Build(); var normalized = original.Normalize(); var expected = new PeriodBuilder { Hours = 2, Minutes = 59 }.Build(); Assert.AreEqual(expected, normalized); } [Test] public void Normalize_MixedSigns_NegativeResult() { var original = new PeriodBuilder { Hours = 1, Minutes = -121 }.Build(); var normalized = original.Normalize(); var expected = new PeriodBuilder { Hours = -1, Minutes = -1 }.Build(); Assert.AreEqual(expected, normalized); } [Test] public void Normalize_DoesntAffectMonthsAndYears() { var original = new PeriodBuilder { Years = 2, Months = 1, Days = 400 }.Build(); Assert.AreEqual(original, original.Normalize()); } [Test] public void Normalize_ZeroResult() { var original = new PeriodBuilder { Years = 0 }.Build(); Assert.AreEqual(Period.Zero, original.Normalize()); } [Test] public void Normalize_Overflow() { Period period = Period.FromHours(long.MaxValue); Assert.Throws<OverflowException>(() => period.Normalize()); } [Test] public void ToString_SingleUnit() { var period = Period.FromHours(5); Assert.AreEqual("PT5H", period.ToString()); } [Test] public void ToString_MultipleUnits() { var period = new PeriodBuilder { Hours = 5, Minutes = 30 }.Build(); Assert.AreEqual("PT5H30M", period.ToString()); } [Test] public void ToDuration_InvalidWithYears() { Period period = Period.FromYears(1); Assert.Throws<InvalidOperationException>(() => period.ToDuration()); } [Test] public void ToDuration_InvalidWithMonths() { Period period = Period.FromMonths(1); Assert.Throws<InvalidOperationException>(() => period.ToDuration()); } [Test] public void ToDuration_ValidAllAcceptableUnits() { Period period = new PeriodBuilder { Weeks = 1, Days = 2, Hours = 3, Minutes = 4, Seconds = 5, Milliseconds = 6, Ticks = 7 }.Build(); Assert.AreEqual( 1 * NodaConstants.TicksPerWeek + 2 * NodaConstants.TicksPerDay + 3 * NodaConstants.TicksPerHour + 4 * NodaConstants.TicksPerMinute + 5 * NodaConstants.TicksPerSecond + 6 * NodaConstants.TicksPerMillisecond + 7, period.ToDuration().BclCompatibleTicks); } [Test] public void ToDuration_ValidWithZeroValuesInMonthYearUnits() { Period period = Period.FromMonths(1) + Period.FromYears(1); period = period - period + Period.FromDays(1); Assert.IsFalse(period.HasTimeComponent); Assert.AreEqual(Duration.OneDay, period.ToDuration()); } [Test] [Category("Overflow")] public void ToDuration_Overflow() { Period period = Period.FromSeconds(long.MaxValue); Assert.Throws<OverflowException>(() => period.ToDuration()); } [Test] [Category("Overflow")] public void ToDuration_Overflow_WhenPossiblyValid() { // These two should pretty much cancel each other out - and would, if we had a 128-bit integer // representation to use. Period period = Period.FromSeconds(long.MaxValue) + Period.FromMinutes(long.MinValue / 60); Assert.Throws<OverflowException>(() => period.ToDuration()); } [Test] public void NormalizingEqualityComparer_NullToNonNull() { Period period = Period.FromYears(1); Assert.IsFalse(Period.NormalizingEqualityComparer.Equals(period, null)); Assert.IsFalse(Period.NormalizingEqualityComparer.Equals(null, period)); } [Test] public void NormalizingEqualityComparer_NullToNull() { Assert.IsTrue(Period.NormalizingEqualityComparer.Equals(null, null)); } [Test] public void NormalizingEqualityComparer_PeriodToItself() { Period period = Period.FromYears(1); Assert.IsTrue(Period.NormalizingEqualityComparer.Equals(period, period)); } [Test] public void NormalizingEqualityComparer_NonEqualAfterNormalization() { Period period1 = Period.FromHours(2); Period period2 = Period.FromMinutes(150); Assert.IsFalse(Period.NormalizingEqualityComparer.Equals(period1, period2)); } [Test] public void NormalizingEqualityComparer_EqualAfterNormalization() { Period period1 = Period.FromHours(2); Period period2 = Period.FromMinutes(120); Assert.IsTrue(Period.NormalizingEqualityComparer.Equals(period1, period2)); } [Test] public void NormalizingEqualityComparer_GetHashCodeAfterNormalization() { Period period1 = Period.FromHours(2); Period period2 = Period.FromMinutes(120); Assert.AreEqual(Period.NormalizingEqualityComparer.GetHashCode(period1), Period.NormalizingEqualityComparer.GetHashCode(period2)); } [Test] public void Comparer_NullWithNull() { var comparer = Period.CreateComparer(new LocalDateTime(2000, 1, 1, 0, 0)); Assert.AreEqual(0, comparer.Compare(null, null)); } [Test] public void Comparer_NullWithNonNull() { var comparer = Period.CreateComparer(new LocalDateTime(2000, 1, 1, 0, 0)); Assert.That(comparer.Compare(null, Period.Zero), Is.LessThan(0)); } [Test] public void Comparer_NonNullWithNull() { var comparer = Period.CreateComparer(new LocalDateTime(2000, 1, 1, 0, 0)); Assert.That(comparer.Compare(Period.Zero, null), Is.GreaterThan(0)); } [Test] public void Comparer_DurationablePeriods() { var bigger = Period.FromHours(25); var smaller = Period.FromDays(1); var comparer = Period.CreateComparer(new LocalDateTime(2000, 1, 1, 0, 0)); Assert.That(comparer.Compare(bigger, smaller), Is.GreaterThan(0)); Assert.That(comparer.Compare(smaller, bigger), Is.LessThan(0)); Assert.AreEqual(0, comparer.Compare(bigger, bigger)); } [Test] public void Comparer_NonDurationablePeriods() { var month = Period.FromMonths(1); var days = Period.FromDays(30); // At the start of January, a month is longer than 30 days var januaryComparer = Period.CreateComparer(new LocalDateTime(2000, 1, 1, 0, 0)); Assert.That(januaryComparer.Compare(month, days), Is.GreaterThan(0)); Assert.That(januaryComparer.Compare(days, month), Is.LessThan(0)); Assert.AreEqual(0, januaryComparer.Compare(month, month)); // At the start of February, a month is shorter than 30 days var februaryComparer = Period.CreateComparer(new LocalDateTime(2000, 2, 1, 0, 0)); Assert.That(februaryComparer.Compare(month, days), Is.LessThan(0)); Assert.That(februaryComparer.Compare(days, month), Is.GreaterThan(0)); Assert.AreEqual(0, februaryComparer.Compare(month, month)); } [Test] [TestCaseSource(nameof(AllPeriodUnits))] public void Between_ExtremeValues(PeriodUnits units) { // We can't use None, and Nanoseconds will *correctly* overflow. if (units == PeriodUnits.None || units == PeriodUnits.Nanoseconds) { return; } var minValue = LocalDate.MinIsoValue.At(LocalTime.MinValue); var maxValue = LocalDate.MaxIsoValue.At(LocalTime.MaxValue); Period.Between(minValue, maxValue, units); } [Test] public void Between_ExtremeValues_Overflow() { var minValue = LocalDate.MinIsoValue.At(LocalTime.MinValue); var maxValue = LocalDate.MaxIsoValue.At(LocalTime.MaxValue); Assert.Throws<OverflowException>(() => Period.Between(minValue, maxValue, PeriodUnits.Nanoseconds)); } [Test] [TestCase("2015-02-28T16:00:00", "2016-02-29T08:00:00", PeriodUnits.Years, 1, 0)] [TestCase("2015-02-28T16:00:00", "2016-02-29T08:00:00", PeriodUnits.Months, 12, -11)] [TestCase("2014-01-01T16:00:00", "2014-01-03T08:00:00", PeriodUnits.Days, 1, -1)] [TestCase("2014-01-01T16:00:00", "2014-01-03T08:00:00", PeriodUnits.Hours, 40, -40)] public void Between_LocalDateTime_AwkwardTimeOfDayWithSingleUnit(string startText, string endText, PeriodUnits units, int expectedForward, int expectedBackward) { LocalDateTime start = LocalDateTimePattern.ExtendedIso.Parse(startText).Value; LocalDateTime end = LocalDateTimePattern.ExtendedIso.Parse(endText).Value; Period forward = Period.Between(start, end, units); Assert.AreEqual(expectedForward, forward.ToBuilder()[units]); Period backward = Period.Between(end, start, units); Assert.AreEqual(expectedBackward, backward.ToBuilder()[units]); } [Test] public void Between_LocalDateTime_SameValue() { LocalDateTime start = new LocalDateTime(2014, 1, 1, 16, 0, 0); Assert.AreSame(Period.Zero, Period.Between(start, start)); } [Test] public void Between_LocalDateTime_AwkwardTimeOfDayWithMultipleUnits() { LocalDateTime start = new LocalDateTime(2014, 1, 1, 16, 0, 0); LocalDateTime end = new LocalDateTime(2015, 2, 3, 8, 0, 0); Period actual = Period.Between(start, end, PeriodUnits.YearMonthDay | PeriodUnits.AllTimeUnits); Period expected = new PeriodBuilder { Years = 1, Months = 1, Days = 1, Hours = 16 }.Build(); Assert.AreEqual(expected, actual); } [Test] public void BetweenYearMonth_InvalidUnits() { YearMonth yearMonth1 = new YearMonth(2010, 1); YearMonth yearMonth2 = new YearMonth(2011, 3); Assert.Throws<ArgumentException>(() => Period.Between(yearMonth1, yearMonth2, 0)); Assert.Throws<ArgumentException>(() => Period.Between(yearMonth1, yearMonth2, (PeriodUnits)(-1))); Assert.Throws<ArgumentException>(() => Period.Between(yearMonth1, yearMonth2, PeriodUnits.AllTimeUnits)); Assert.Throws<ArgumentException>(() => Period.Between(yearMonth1, yearMonth2, PeriodUnits.Days)); Assert.Throws<ArgumentException>(() => Period.Between(yearMonth1, yearMonth2, PeriodUnits.Years | PeriodUnits.Days)); Assert.Throws<ArgumentException>(() => Period.Between(yearMonth1, yearMonth2, PeriodUnits.Years | PeriodUnits.Weeks)); Assert.Throws<ArgumentException>(() => Period.Between(yearMonth1, yearMonth2, PeriodUnits.Years | PeriodUnits.Hours)); } [Test] public void BetweenYearMonth_DifferentCalendarSystems_Throws() { YearMonth start = new YearMonth(2017, 11, CalendarSystem.Coptic); YearMonth end = new YearMonth(2017, 11, CalendarSystem.Gregorian); Assert.Throws<ArgumentException>(() => Period.Between(start, end)); } [TestCase("2016-05", "2017-03", PeriodUnits.Years, 0)] [TestCase("2016-05", "2016-05", PeriodUnits.Years, 0)] [TestCase("2016-05", "2019-03", PeriodUnits.Years, 2)] [TestCase("2016-05", "2019-05", PeriodUnits.Years, 3)] [TestCase("2016-05", "2017-07", PeriodUnits.Months, 14)] [TestCase("2016-05", "2017-05", PeriodUnits.Months, 12)] [TestCase("2016-07", "2016-07", PeriodUnits.Months, 0)] public void BetweenYearMonth_SingleUnit(string startText, string endText, PeriodUnits units, int expectedValue) { var start = YearMonthPattern.Iso.Parse(startText).Value; var end = YearMonthPattern.Iso.Parse(endText).Value; var forward = Period.Between(start, end, units); var expectedForward = new PeriodBuilder { [units] = expectedValue }.Build(); Assert.AreEqual(expectedForward, forward); var backward = Period.Between(end, start, units); var expectedBackward = new PeriodBuilder { [units] = -expectedValue }.Build(); Assert.AreEqual(expectedBackward, backward); } [TestCase("2017-05", "2017-05", 0, 0)] [TestCase("2016-05", "2017-05", 1, 0)] [TestCase("2016-05", "2017-06", 1, 1)] [TestCase("2016-05", "2018-10", 2, 5)] [TestCase("2016-05", "2017-04", 0, 11)] [TestCase("2013-05", "2017-04", 3, 11)] public void BetweenYearMonth_BothUnits(string startText, string endText, int expectedYears, int expectedMonths) { var start = YearMonthPattern.Iso.Parse(startText).Value; var end = YearMonthPattern.Iso.Parse(endText).Value; var forward = Period.Between(start, end, PeriodUnits.Years | PeriodUnits.Months); var expectedForward = new PeriodBuilder { [PeriodUnits.Years] = expectedYears, [PeriodUnits.Months] = expectedMonths }.Build(); Assert.AreEqual(expectedForward, forward); var forwardNoUnits = Period.Between(start, end); Assert.AreEqual(expectedForward, forwardNoUnits); var backward = Period.Between(end, start, PeriodUnits.Years | PeriodUnits.Months); var expectedBackward = new PeriodBuilder { [PeriodUnits.Years] =- expectedYears, [PeriodUnits.Months] = -expectedMonths }.Build(); Assert.AreEqual(expectedBackward, backward); var backwardNoUnits = Period.Between(end, start); Assert.AreEqual(expectedBackward, backwardNoUnits); } [Test] public void FromNanoseconds() { var period = Period.FromNanoseconds(1234567890L); Assert.AreEqual(1234567890L, period.Nanoseconds); } [Test] public void AddPeriodToPeriod_NoOverflow() { Period p1 = Period.FromHours(long.MaxValue); Period p2 = Period.FromMinutes(60); Assert.AreEqual(new PeriodBuilder { Hours = long.MaxValue, Minutes = 60 }.Build(), p1 + p2); } [Test] public void AddPeriodToPeriod_Overflow() { Period p1 = Period.FromHours(long.MaxValue); Period p2 = Period.FromHours(1); Assert.Throws<OverflowException>(() => (p1 + p2).GetHashCode()); } /// <summary> /// Just a simple way of parsing a period string. It's a more compact period representation. /// </summary> private static Period Parse(string text) { return PeriodPattern.Roundtrip.Parse(text).Value; } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System.Runtime.CompilerServices; using Xunit; public class StackTraceRendererTests : NLogTestBase { [Fact] public void RenderStackTrace() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message} ${stacktrace}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; RenderMe(logFactory, "I am:"); logFactory.AssertDebugLastMessageContains(" => StackTraceRendererTests.RenderStackTrace => StackTraceRendererTests.RenderMe"); } [Fact] public void RenderStackTraceReversed() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:reverse=true}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; RenderMe(logFactory, "I am:"); logFactory.AssertDebugLastMessageContains("StackTraceRendererTests.RenderMe => StackTraceRendererTests.RenderStackTraceReversed => "); } [Fact] public void RenderStackTraceNoCaptureStackTrace() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:captureStackTrace=false}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; RenderMe(logFactory, "I am:"); logFactory.AssertDebugLastMessage("I am: "); } [Fact] public void RenderStackTraceNoCaptureStackTraceWithStackTrace() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:captureStackTrace=false}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; var logEvent = new LogEventInfo(LogLevel.Info, null, "I am:"); logEvent.SetStackTrace(new System.Diagnostics.StackTrace(true), 0); logFactory.GetCurrentClassLogger().Log(logEvent); logFactory.AssertDebugLastMessageContains($" => {nameof(StackTraceRendererTests)}.{nameof(RenderStackTraceNoCaptureStackTraceWithStackTrace)}"); } [Fact] public void RenderStackTrace_topframes() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:topframes=2}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; RenderMe(logFactory, "I am:"); logFactory.AssertDebugLastMessage("I am: StackTraceRendererTests.RenderStackTrace_topframes => StackTraceRendererTests.RenderMe"); } [Fact] public void RenderStackTrace_skipframes() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:skipframes=1}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; RenderMe(logFactory, "I am:"); logFactory.AssertDebugLastMessageContains(" => StackTraceRendererTests.RenderStackTrace_skipframes"); } [Fact] public void RenderStackTrace_raw() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:format=Raw}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; RenderMe(logFactory, "I am:"); logFactory.AssertDebugLastMessageContains("RenderStackTrace_raw at offset "); logFactory.AssertDebugLastMessageContains("RenderMe at offset "); #if !MONO logFactory.AssertDebugLastMessageContains("StackTraceRendererTests.cs"); #endif string debugLastMessage = GetDebugLastMessage("debug", logFactory); int index0 = debugLastMessage.IndexOf("RenderStackTraceReversed_raw at offset "); int index1 = debugLastMessage.IndexOf("RenderMe at offset "); Assert.True(index0 < index1); } [Fact] public void RenderStackTraceSeperator_raw() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:format=Raw:separator= \=&gt; }' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; RenderMe(logFactory, "I am:"); logFactory.AssertDebugLastMessageContains(" => RenderStackTraceSeperator_raw at offset "); logFactory.AssertDebugLastMessageContains(" => RenderMe at offset "); #if !MONO logFactory.AssertDebugLastMessageContains("StackTraceRendererTests.cs"); #endif string debugLastMessage = GetDebugLastMessage("debug", logFactory); int index0 = debugLastMessage.IndexOf(" => RenderStackTraceSeperator_raw at offset "); int index1 = debugLastMessage.IndexOf(" => RenderMe at offset "); Assert.True(index0 < index1); } [Fact] public void RenderStackTraceReversed_raw() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:format=Raw:reverse=true}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; RenderMe(logFactory, "I am:"); logFactory.AssertDebugLastMessageContains("RenderMe at offset "); logFactory.AssertDebugLastMessageContains("RenderStackTraceReversed_raw at offset "); #if !MONO logFactory.AssertDebugLastMessageContains("StackTraceRendererTests.cs"); #endif string debugLastMessage = GetDebugLastMessage("debug", logFactory); int index0 = debugLastMessage.IndexOf("RenderMe at offset "); int index1 = debugLastMessage.IndexOf("RenderStackTraceReversed_raw at offset "); Assert.True(index0 < index1); } [Fact] public void RenderStackTrace_DetailedFlat() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:format=DetailedFlat}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; RenderMe(logFactory, "I am:"); logFactory.AssertDebugLastMessageContains(" => [Void RenderStackTrace_DetailedFlat()] => [Void RenderMe(NLog.LogFactory, System.String)]"); } [Fact] public void RenderStackTraceReversed_DetailedFlat() { var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@" <nlog> <targets><target name='debug' type='Debug' layout='${message} ${stacktrace:format=DetailedFlat:reverse=true}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>").LogFactory; RenderMe(logFactory, "I am:"); logFactory.AssertDebugLastMessageContains("[Void RenderMe(NLog.LogFactory, System.String)] => [Void RenderStackTraceReversed_DetailedFlat()] => "); } [MethodImpl(MethodImplOptions.NoInlining)] private void RenderMe(LogFactory logFactory, string message) { var logger = logFactory.GetCurrentClassLogger(); logger.Info(message); } } }
// Copyright (c) 2017 Jan Pluskal // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Validation; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Castle.Windsor; using EntityFramework.BulkInsert.Extensions; using EntityFramework.InMemory; using Netfox.Core.Database; using Netfox.Core.Helpers; using Netfox.Core.Interfaces.ViewModels; namespace Netfox.Persistence { public sealed class NetfoxDbContextInMemory : NetfoxDbContext { public NetfoxDbContextInMemory(WindsorContainer windsorContainer, SqlConnectionStringBuilder sqlConnectionStringBuilder) : base(windsorContainer, sqlConnectionStringBuilder) { } public override bool IsInMemory { get; } = true; private TestDbSet<TEntity> CreateDbSet<TEntity>() where TEntity : class { return this.CreateDbSet(typeof(TEntity)) as TestDbSet<TEntity>; } private object CreateDbSet(Type type) { return this.CreateDbSet(type, null); } private object CreateDbSet(Type type, DbSet dbSet) { var mockDbSetType = typeof(TestDbSet<>).MakeGenericType(type); var mockOnAddCallback = this.GetType() .GetMethod(nameof(this.OnAddTestDbSetItem), BindingFlags.NonPublic|BindingFlags.GetField|BindingFlags.Instance) .MakeGenericMethod(type); var mockOnAddBulkCallback = this.GetType() .GetMethod(nameof(this.OnAddBulkTestDbSetItems), BindingFlags.NonPublic|BindingFlags.GetField|BindingFlags.Instance) .MakeGenericMethod(type); var mockOnRemoveCallback = this.GetType() .GetMethod(nameof(this.OnRemoveTestDbSetItem), BindingFlags.NonPublic|BindingFlags.GetField|BindingFlags.Instance) .MakeGenericMethod(type); var delegateType = typeof(Action<>).MakeGenericType(type); var onAdd = Delegate.CreateDelegate(delegateType, this, mockOnAddCallback); var onRemove = Delegate.CreateDelegate(delegateType, this, mockOnRemoveCallback); var ienumerableType = typeof(IEnumerable<>).MakeGenericType(type); var delegateTypeIenumerable = typeof(Action<>).MakeGenericType(ienumerableType); var onAddBulk = Delegate.CreateDelegate(delegateTypeIenumerable, this, mockOnAddBulkCallback); return Activator.CreateInstance(mockDbSetType, onAdd, onAddBulk, onRemove, dbSet); } private IEnumerable<PropertyInfo> GetAllDbSetProperties() { return this.GetType().GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>)); } private PropertyInfo GetAllGenericDbSetProperties(Type type) { return this.GetAllDbSetProperties().FirstOrDefault(p => p.PropertyType.GenericTypeArguments.Contains(type)); } private void SetDbSetProperty<TEntity>(DbSet<TEntity> dbSet, PropertyInfo dbSetPropertyInfo) where TEntity : class { dbSetPropertyInfo.SetValue(this, dbSet); } #region Overrides of BaseContex<NetfoxDbContext> public override void CheckCreateDatabase() { } public override void InsertToJunctionTable<T>(IEnumerable<T> joinTableValues) { } public override void ActivateDbSetChangeNotifier(Type dbSetType) { var autoRefreshArgs = this.AutoRefreshArgsDictionary.GetOrAdd(dbSetType, type => new AutoRefreshArgs(dbSetType)); var lastEntityCount = this.Set(dbSetType).Local.Count; var prt = PeriodicalRepetitiveTask.Create((now, ct) => Task.Run(() => { var currentEntityCount = this.Set(dbSetType).Local.Count; if(lastEntityCount == currentEntityCount) return; lastEntityCount = currentEntityCount; this.OnDbSetChanged(new DbSetChangedArgs(dbSetType)); }, ct), autoRefreshArgs.CancellationTokenSource.Token, TimeSpan.FromSeconds(5)); prt.Post(DateTimeOffset.Now); } #endregion #region BulkInsertBuffered public override async Task BulkInsertBuffered<TEntity>(IEnumerable<TEntity> entities, BulkInsertOptions options) { await Task.Run(() => { var entitiesArray = entities as TEntity[] ?? entities.ToArray(); this.InjectWindsorContainer(entitiesArray); var dbSet = this.Set<TEntity>() as TestDbSet<TEntity>; dbSet.AddRange(entitiesArray,false); }); } public override async Task BulkInsertBuffered<T>(IEnumerable<T> entities, int? batchSize = null) { await this.BulkInsertBuffered(entities, SqlBulkCopyOptions.Default, batchSize); } public override async Task BulkInsertBuffered<T>(IEnumerable<T> entities, SqlBulkCopyOptions sqlBulkCopyOptions, int? batchSize = null) { var options = new BulkInsertOptions { SqlBulkCopyOptions = sqlBulkCopyOptions }; if(batchSize.HasValue) options.BatchSize = batchSize.Value; await this.BulkInsertBuffered(entities, options); } public override async Task BulkInsertBuffered<T>( IEnumerable<T> entities, IDbTransaction transaction, SqlBulkCopyOptions sqlBulkCopyOptions = SqlBulkCopyOptions.Default, int? batchSize = null) { var options = new BulkInsertOptions { SqlBulkCopyOptions = sqlBulkCopyOptions }; if(batchSize.HasValue) options.BatchSize = batchSize.Value; await this.BulkInsertBuffered(entities, options); } #endregion #region BulkInsert public override void BulkInsert<TEntity>(IEnumerable<TEntity> entities, BulkInsertOptions options) { var entitiesArray = entities as TEntity[] ?? entities.ToArray(); this.InjectWindsorContainer(entitiesArray); var dbSet = this.Set<TEntity>() as TestDbSet<TEntity>; if(dbSet == null) { var method = this.GetType().GetMethods().First(m => m.IsGenericMethod && m.Name == nameof(BulkInsert)); var generic = method.MakeGenericMethod(typeof(TEntity).BaseType); var ret = generic.Invoke(this, new object[] { entities, options }); return; } dbSet.AddRange(entitiesArray,false); } private void InjectWindsorContainer<TEntity>(IEnumerable<TEntity> entities) { if(!typeof(IWindsorContainerChanger).IsAssignableFrom(typeof(TEntity))) return; foreach(var entity in entities) (entity as IWindsorContainerChanger).InvestigationWindsorContainer = this.WindsorContainer; } public override void BulkInsert<TEntity>(IEnumerable<TEntity> entities, int? batchSize = null) { this.BulkInsert(entities, SqlBulkCopyOptions.Default, batchSize); } public override void BulkInsert<TEntity>(IEnumerable<TEntity> entities, SqlBulkCopyOptions sqlBulkCopyOptions, int? batchSize = null) { var options = new BulkInsertOptions { SqlBulkCopyOptions = sqlBulkCopyOptions }; if(batchSize.HasValue) options.BatchSize = batchSize.Value; this.BulkInsert(entities, options); } public override void BulkInsert<TEntity>( IEnumerable<TEntity> entities, IDbTransaction transaction, SqlBulkCopyOptions sqlBulkCopyOptions = SqlBulkCopyOptions.Default, int? batchSize = null) { var options = new BulkInsertOptions { SqlBulkCopyOptions = sqlBulkCopyOptions }; if(batchSize.HasValue) options.BatchSize = batchSize.Value; this.BulkInsert(entities, options); } #endregion #region BulkInsertAsync public override Task BulkInsertAsync<TEntity>(IEnumerable<TEntity> entities, BulkInsertOptions options) { return Task.Run(() => { this.BulkInsert(entities, options); }); } public override Task BulkInsertAsync<T>(IEnumerable<T> entities, int? batchSize = null) { return this.BulkInsertAsync(entities, SqlBulkCopyOptions.Default, batchSize); } public override Task BulkInsertAsync<T>(IEnumerable<T> entities, SqlBulkCopyOptions sqlBulkCopyOptions, int? batchSize = null) { var options = new BulkInsertOptions { SqlBulkCopyOptions = sqlBulkCopyOptions }; if(batchSize.HasValue) options.BatchSize = batchSize.Value; return this.BulkInsertAsync(entities, options); } public override Task BulkInsertAsync<T>( IEnumerable<T> entities, IDbTransaction transaction, SqlBulkCopyOptions sqlBulkCopyOptions = SqlBulkCopyOptions.Default, int? batchSize = null) { var options = new BulkInsertOptions { SqlBulkCopyOptions = sqlBulkCopyOptions }; if(batchSize.HasValue) options.BatchSize = batchSize.Value; return this.BulkInsertAsync(entities, options); } #endregion #region Overrides of DbContext protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } public override int SaveChanges() { return base.SaveChanges(); } public override Task<int> SaveChangesAsync() { return base.SaveChangesAsync(); } public override Task<int> SaveChangesAsync(CancellationToken cancellationToken) { return base.SaveChangesAsync(cancellationToken); } protected override bool ShouldValidateEntity(DbEntityEntry entityEntry) { return base.ShouldValidateEntity(entityEntry); } protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items) { return base.ValidateEntity(entityEntry, items); } private ConcurrentDictionary<Type, object> DbSetsNotInDbContext { get; } = new ConcurrentDictionary<Type, object>(); public override DbSet<TEntity> Set<TEntity>() { var dbSetPropertyInfo = this.GetAllGenericDbSetProperties(typeof(TEntity)); if(dbSetPropertyInfo == null) { var type = typeof(TEntity); do { if(type == null) throw new InvalidOperationException("The entity type NetfoxDbContextInMemoryTests is not part of the model for the current context."); if(this.IsTypePersistent(type) && !this.IsTypePersistent(type?.BaseType)) { this.DbSetsNotInDbContext.GetOrAdd(type, this.CreateDbSet); break; } dbSetPropertyInfo = this.GetAllGenericDbSetProperties(type); if(dbSetPropertyInfo == null) type = type?.BaseType; } while(dbSetPropertyInfo == null); return this.DbSetsNotInDbContext.GetOrAdd(typeof(TEntity), t => this.CreateDbSet(t, this.Set(type))) as TestDbSet<TEntity>; } var dbSet = this.GetDbSetProperty<TEntity>(dbSetPropertyInfo); if(dbSet == null) { var type = typeof(TEntity); var baseType = type.BaseType; while(baseType != typeof(object)) { type = baseType; baseType = baseType?.BaseType; } if(type != typeof(TEntity)) dbSet = this.Set(type) as TestDbSet<TEntity>; else dbSet = this.CreateDbSet<TEntity>(); this.SetDbSetProperty(dbSet, dbSetPropertyInfo); } return dbSet; } private void OnAddTestDbSetItem<TEntity>(TEntity item) { var properties = this.GetPersistingProperties<TEntity>(); foreach(var property in properties) { var propType = property.PropertyType.IsGenericType? property.PropertyType.GetGenericArguments()[0] : property.PropertyType; var dbSet = this.GetTestDbSetForType(propType); dbSet.Add(property.GetValue(item)); } } private void OnAddBulkTestDbSetItems<TEntity>(IEnumerable<TEntity> items) { var itemsByType = items.GroupBy(item => item.GetType()); if(itemsByType.Count() != 1) { Debugger.Break(); throw new NotSupportedException($"Only items with the same type can be inserted by {nameof(this.OnAddBulkTestDbSetItems)}"); } var properties = this.GetPersistingProperties<TEntity>(); foreach(var property in properties) { var propertyOrAttributeType = property.PropertyType.IsGenericType? property.PropertyType.GetGenericArguments()[0] : property.PropertyType; dynamic dbSet = this.GetTestDbSetForType(propertyOrAttributeType); var persistingObjects = new List<object>(); foreach(var entity in items) { if (property.PropertyType.IsGenericType) //collection { var itemValues = property.GetValue(entity) as ICollection; if (itemValues == null) continue; dbSet.AddRange(itemValues); } else { //normal property var item = property.GetValue(entity); if (item == null) continue; persistingObjects.Add(item); } } dbSet.AddRange(persistingObjects); } } private void OnRemoveTestDbSetItem<TEntity>(TEntity item) { var properties = this.GetPersistingProperties<TEntity>(); foreach(var property in properties) { var propType = property.PropertyType.IsGenericType? property.PropertyType.GetGenericArguments()[0] : property.PropertyType; var dbSet = this.GetTestDbSetForType(propType); dbSet.Remove(property.GetValue(item)); } } private static readonly ConcurrentDictionary<Type, IEnumerable<PropertyInfo>> _typeCache = new ConcurrentDictionary<Type, IEnumerable<PropertyInfo>>(); private IEnumerable<PropertyInfo> GetPersistingProperties<TEntity>() { return _typeCache.GetOrAdd(typeof(TEntity), this.GetPersistingPropertiesReflection); } private IEnumerable<PropertyInfo> GetPersistingPropertiesReflection(Type type) { var propertyInfos = type.GetProperties(); var properties = propertyInfos .Where(p => this.IsTypePersistent(p.PropertyType) || this.IsTypeOfCollectionOPersistent(p.PropertyType) || this.IsDeclaredOnDbContext(p.PropertyType)) .Where(p => p.CustomAttributes.All(a => a.AttributeType != typeof(NotMappedAttribute))); return properties; } private bool IsDeclaredOnDbContext(Type type) { return this .GetType() .GetProperties() .Any(x => (this.IsTypePersistent(x.PropertyType) || x.PropertyType.IsGenericType && typeof(ICollection<>).IsAssignableFrom(type) && this.IsTypePersistent(x.PropertyType.GetGenericArguments()[0])) && x.PropertyType == type); } private bool IsTypeOfCollectionOPersistent(Type type) { var typeIsGenericType = type.IsGenericType; if(!typeIsGenericType) return false; var genericArgument = type.GetGenericArguments()[0]; var icollectionType = typeof(ICollection<>).MakeGenericType(genericArgument); var isAssignableFrom = icollectionType.IsAssignableFrom(type); var isTypePersistent = this.IsTypePersistent(genericArgument); return typeIsGenericType && isAssignableFrom && isTypePersistent; } private TestDbSet<TEntity> GetDbSetProperty<TEntity>(PropertyInfo dbSetPropertyInfo) where TEntity : class { return dbSetPropertyInfo.GetValue(this) as TestDbSet<TEntity>; } private IList GetTestDbSetForType(Type type) { var method = this.GetType().GetMethods().First(m => m.IsGenericMethod && m.Name == "Set"); var generic = method.MakeGenericMethod(type); var testDbSetForType = generic.Invoke(this, null) as IList; return testDbSetForType; } public override DbSet Set(Type entityType) { var testDbSetGeneric = this.GetTestDbSetForType(entityType); var ret = new TestDbSet(testDbSetGeneric, entityType); return ret; } protected override void Dispose(bool disposing) { // Check to see if Dispose has already been called. if(!this.Disposed) if(disposing) foreach(var autoRefreshArgs in this.AutoRefreshArgsDictionary) autoRefreshArgs.Value.CancellationTokenSource.Cancel(); base.Dispose(disposing); } #endregion } }
/******************************************************************************* * Copyright 2008-2013 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; namespace Amazon.EC2.Model { /// <summary> /// VPN Gateway /// </summary> [XmlRootAttribute(IsNullable = false)] public class VpnGateway { private string vpnGatewayIdField; private string vpnGatewayStateField; private string typeField; private string availabilityZoneField; private List<VpcAttachment> vpcAttachmentField; private List<Tag> tagField; /// <summary> /// The ID of the VPN gateway /// </summary> [XmlElementAttribute(ElementName = "VpnGatewayId")] public string VpnGatewayId { get { return this.vpnGatewayIdField; } set { this.vpnGatewayIdField = value; } } /// <summary> /// Sets the ID of the VPN gateway /// </summary> /// <param name="vpnGatewayId">The ID of the VPN gateway</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public VpnGateway WithVpnGatewayId(string vpnGatewayId) { this.vpnGatewayIdField = vpnGatewayId; return this; } /// <summary> /// Checks if VpnGatewayId property is set /// </summary> /// <returns>true if VpnGatewayId property is set</returns> public bool IsSetVpnGatewayId() { return this.vpnGatewayIdField != null; } /// <summary> /// The current state of the VPN gateway. /// Valid values: pending, available, deleting, deleted /// </summary> [XmlElementAttribute(ElementName = "VpnGatewayState")] public string VpnGatewayState { get { return this.vpnGatewayStateField; } set { this.vpnGatewayStateField = value; } } /// <summary> /// Sets the current state of the VPN gateway. /// </summary> /// <param name="vpnGatewayState">The current state of the VPN gateway (pending, /// available, deleting, deleted)</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public VpnGateway WithVpnGatewayState(string vpnGatewayState) { this.vpnGatewayStateField = vpnGatewayState; return this; } /// <summary> /// Checks if VpnGatewayState property is set /// </summary> /// <returns>true if VpnGatewayState property is set</returns> public bool IsSetVpnGatewayState() { return this.vpnGatewayStateField != null; } /// <summary> /// The type of VPN connection the VPN gateway supports (ipsec.1) /// </summary> [XmlElementAttribute(ElementName = "Type")] public string Type { get { return this.typeField; } set { this.typeField = value; } } /// <summary> /// Sets the type of VPN connection the VPN gateway supports /// </summary> /// <param name="type">The type of VPN connection the VPN gateway supports (ipsec.1)</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public VpnGateway WithType(string type) { this.typeField = type; return this; } /// <summary> /// Checks if Type property is set /// </summary> /// <returns>true if Type property is set</returns> public bool IsSetType() { return this.typeField != null; } /// <summary> /// The Availability Zone where the VPN gateway was created /// </summary> [XmlElementAttribute(ElementName = "AvailabilityZone")] public string AvailabilityZone { get { return this.availabilityZoneField; } set { this.availabilityZoneField = value; } } /// <summary> /// Sets the Availability Zone where the VPN gateway was created /// </summary> /// <param name="availabilityZone">The Availability Zone where the VPN gateway was created</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public VpnGateway WithAvailabilityZone(string availabilityZone) { this.availabilityZoneField = availabilityZone; return this; } /// <summary> /// Checks if AvailabilityZone property is set /// </summary> /// <returns>true if AvailabilityZone property is set</returns> public bool IsSetAvailabilityZone() { return this.availabilityZoneField != null; } /// <summary> /// List of VPC attachments. /// </summary> [XmlElementAttribute(ElementName = "VpcAttachment")] public List<VpcAttachment> VpcAttachment { get { if (this.vpcAttachmentField == null) { this.vpcAttachmentField = new List<VpcAttachment>(); } return this.vpcAttachmentField; } set { this.vpcAttachmentField = value; } } /// <summary> /// Sets the list of VPC attachments. /// </summary> /// <param name="list">list of VPC attachments</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public VpnGateway WithVpcAttachment(params VpcAttachment[] list) { foreach (VpcAttachment item in list) { VpcAttachment.Add(item); } return this; } /// <summary> /// Checks if VpcAttachment property is set /// </summary> /// <returns>true if VpcAttachment property is set</returns> public bool IsSetVpcAttachment() { return (VpcAttachment.Count > 0); } /// <summary> /// A list of tags for the VpnGateway. /// </summary> [XmlElementAttribute(ElementName = "Tag")] public List<Tag> Tag { get { if (this.tagField == null) { this.tagField = new List<Tag>(); } return this.tagField; } set { this.tagField = value; } } /// <summary> /// Sets a list of tags for the VpnGateway. /// </summary> /// <param name="list">A list of tags for the VpnGateway.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public VpnGateway WithTag(params Tag[] list) { foreach (Tag item in list) { Tag.Add(item); } return this; } /// <summary> /// Checks if Tag property is set /// </summary> /// <returns>true if Tag property is set</returns> public bool IsSetTag() { return (Tag.Count > 0); } } }
/* * Copyright 2014 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using BrockAllen.MembershipReboot; using IdentityServer3.Core; using IdentityServer3.Core.Extensions; using IdentityServer3.Core.Models; using IdentityServer3.Core.Services.Default; namespace FulcrumSeed.App_Packages.IdentityServer3.MembershipReboot { public class MembershipRebootUserService<TAccount> : UserServiceBase where TAccount : UserAccount { public string DisplayNameClaimType { get; set; } protected readonly UserAccountService<TAccount> appUserAccountService; public MembershipRebootUserService(UserAccountService<TAccount> appUserAccountService) { if (appUserAccountService == null) throw new ArgumentNullException("appUserAccountService"); this.appUserAccountService = appUserAccountService; } public override Task GetProfileDataAsync(ProfileDataRequestContext ctx) { var subject = ctx.Subject; var requestedClaimTypes = ctx.RequestedClaimTypes; var acct = appUserAccountService.GetByID(subject.GetSubjectId().ToGuid()); if (acct == null) { throw new ArgumentException("Invalid subject identifier"); } var claims = GetClaimsFromAccount(acct); if (requestedClaimTypes != null && requestedClaimTypes.Any()) { claims = claims.Where(x => requestedClaimTypes.Contains(x.Type)); } ctx.IssuedClaims = claims; return Task.FromResult(0); } protected virtual IEnumerable<Claim> GetClaimsFromAccount(TAccount account) { var claims = new List<Claim>{ new Claim(Constants.ClaimTypes.Subject, GetSubjectForAccount(account)), new Claim(Constants.ClaimTypes.UpdatedAt, IdentityModel.EpochTimeExtensions.ToEpochTime(account.LastUpdated).ToString(), ClaimValueTypes.Integer), new Claim("tenant", account.Tenant), new Claim(Constants.ClaimTypes.PreferredUserName, account.Username), }; if (!String.IsNullOrWhiteSpace(account.Email)) { claims.Add(new Claim(Constants.ClaimTypes.Email, account.Email)); claims.Add(new Claim(Constants.ClaimTypes.EmailVerified, account.IsAccountVerified ? "true" : "false")); } if (!String.IsNullOrWhiteSpace(account.MobilePhoneNumber)) { claims.Add(new Claim(Constants.ClaimTypes.PhoneNumber, account.MobilePhoneNumber)); claims.Add(new Claim(Constants.ClaimTypes.PhoneNumberVerified, !String.IsNullOrWhiteSpace(account.MobilePhoneNumber) ? "true" : "false")); } claims.AddRange(account.Claims.Select(x => new Claim(x.Type, x.Value))); claims.AddRange(appUserAccountService.MapClaims(account)); return claims; } protected virtual string GetSubjectForAccount(TAccount account) { return account.ID.ToString("D"); } protected virtual string GetDisplayNameForAccount(Guid accountID) { var acct = appUserAccountService.GetByID(accountID); var claims = GetClaimsFromAccount(acct); string name = null; if (DisplayNameClaimType != null) { name = acct.Claims.Where(x => x.Type == DisplayNameClaimType).Select(x => x.Value).FirstOrDefault(); } return name ?? acct.Claims.Where(x => x.Type == Constants.ClaimTypes.Name).Select(x => x.Value).FirstOrDefault() ?? acct.Claims.Where(x => x.Type == ClaimTypes.Name).Select(x => x.Value).FirstOrDefault() ?? acct.Username; } protected virtual Task<IEnumerable<Claim>> GetClaimsForAuthenticateResultAsync(TAccount account) { return Task.FromResult((IEnumerable<Claim>)null); } public override async Task AuthenticateLocalAsync(LocalAuthenticationContext ctx) { var username = ctx.UserName; var password = ctx.Password; var message = ctx.SignInMessage; AuthenticateResult result = null; try { TAccount account; if (ValidateLocalCredentials(username, password, message, out account)) { result = await PostAuthenticateLocalAsync(account, message); if (result == null) { var subject = GetSubjectForAccount(account); var name = GetDisplayNameForAccount(account.ID); var claims = await GetClaimsForAuthenticateResultAsync(account); result = new AuthenticateResult(subject, name, claims); } } else { if (account != null) { if (!account.IsLoginAllowed) { result = new AuthenticateResult("Account is not allowed to login"); } else if (account.IsAccountClosed) { result = new AuthenticateResult("Account is closed"); } } } } catch(ValidationException ex) { result = new AuthenticateResult(ex.Message); } ctx.AuthenticateResult = result; } protected virtual Task<AuthenticateResult> PostAuthenticateLocalAsync(TAccount account, SignInMessage message) { return Task.FromResult<AuthenticateResult>(null); } protected virtual bool ValidateLocalCredentials(string username, string password, SignInMessage message, out TAccount account) { var tenant = String.IsNullOrWhiteSpace(message.Tenant) ? appUserAccountService.Configuration.DefaultTenant : message.Tenant; return appUserAccountService.Authenticate(tenant, username, password, out account); } public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext ctx) { var externalUser = ctx.ExternalIdentity; var message = ctx.SignInMessage; if (externalUser == null) { throw new ArgumentNullException("externalUser"); } try { var tenant = String.IsNullOrWhiteSpace(message.Tenant) ? appUserAccountService.Configuration.DefaultTenant : message.Tenant; var acct = this.appUserAccountService.GetByLinkedAccount(tenant, externalUser.Provider, externalUser.ProviderId); if (acct == null) { ctx.AuthenticateResult = await ProcessNewExternalAccountAsync(tenant, externalUser.Provider, externalUser.ProviderId, externalUser.Claims); } else { ctx.AuthenticateResult = await ProcessExistingExternalAccountAsync(acct.ID, externalUser.Provider, externalUser.ProviderId, externalUser.Claims); } } catch (ValidationException ex) { ctx.AuthenticateResult = new AuthenticateResult(ex.Message); } } protected virtual async Task<AuthenticateResult> ProcessNewExternalAccountAsync(string tenant, string provider, string providerId, IEnumerable<Claim> claims) { var user = await TryGetExistingUserFromExternalProviderClaimsAsync(provider, claims); if (user == null) { user = await InstantiateNewAccountFromExternalProviderAsync(provider, providerId, claims); var email = claims.GetValue(Constants.ClaimTypes.Email); user = appUserAccountService.CreateAccount( tenant, Guid.NewGuid().ToString("N"), null, email, null, null, user); } appUserAccountService.AddOrUpdateLinkedAccount(user, provider, providerId); var result = await AccountCreatedFromExternalProviderAsync(user.ID, provider, providerId, claims); if (result != null) return result; return await SignInFromExternalProviderAsync(user.ID, provider); } protected virtual Task<TAccount> TryGetExistingUserFromExternalProviderClaimsAsync(string provider, IEnumerable<Claim> claims) { return Task.FromResult<TAccount>(null); } protected virtual Task<TAccount> InstantiateNewAccountFromExternalProviderAsync(string provider, string providerId, IEnumerable<Claim> claims) { // we'll let the default creation happen, but can override to initialize properties if needed return Task.FromResult<TAccount>(null); } protected virtual async Task<AuthenticateResult> AccountCreatedFromExternalProviderAsync(Guid accountID, string provider, string providerId, IEnumerable<Claim> claims) { SetAccountEmail(accountID, ref claims); SetAccountPhone(accountID, ref claims); return await UpdateAccountFromExternalClaimsAsync(accountID, provider, providerId, claims); } protected virtual async Task<AuthenticateResult> SignInFromExternalProviderAsync(Guid accountID, string provider) { var account = appUserAccountService.GetByID(accountID); var claims = await GetClaimsForAuthenticateResultAsync(account); return new AuthenticateResult( subject: accountID.ToString("D"), name: GetDisplayNameForAccount(accountID), claims:claims, identityProvider: provider, authenticationMethod: Constants.AuthenticationMethods.External); } protected virtual Task<AuthenticateResult> UpdateAccountFromExternalClaimsAsync(Guid accountID, string provider, string providerId, IEnumerable<Claim> claims) { appUserAccountService.AddClaims(accountID, new UserClaimCollection(claims)); return Task.FromResult<AuthenticateResult>(null); } protected virtual async Task<AuthenticateResult> ProcessExistingExternalAccountAsync(Guid accountID, string provider, string providerId, IEnumerable<Claim> claims) { return await SignInFromExternalProviderAsync(accountID, provider); } protected virtual void SetAccountEmail(Guid accountID, ref IEnumerable<Claim> claims) { var email = claims.GetValue(Constants.ClaimTypes.Email); if (email != null) { var acct = appUserAccountService.GetByID(accountID); if (acct.Email == null) { try { var email_verified = claims.GetValue(Constants.ClaimTypes.EmailVerified); if (email_verified != null && email_verified == "true") { appUserAccountService.SetConfirmedEmail(acct.ID, email); } else { appUserAccountService.ChangeEmailRequest(acct.ID, email); } var emailClaims = new string[] { Constants.ClaimTypes.Email, Constants.ClaimTypes.EmailVerified }; claims = claims.Where(x => !emailClaims.Contains(x.Type)); } catch (ValidationException) { // presumably the email is already associated with another account // so eat the validation exception and let the claim pass thru } } } } protected virtual void SetAccountPhone(Guid accountID, ref IEnumerable<Claim> claims) { var phone = claims.GetValue(Constants.ClaimTypes.PhoneNumber); if (phone != null) { var acct = appUserAccountService.GetByID(accountID); if (acct.MobilePhoneNumber == null) { try { var phone_verified = claims.GetValue(Constants.ClaimTypes.PhoneNumberVerified); if (phone_verified != null && phone_verified == "true") { appUserAccountService.SetConfirmedMobilePhone(acct.ID, phone); } else { appUserAccountService.ChangeMobilePhoneRequest(acct.ID, phone); } var phoneClaims = new string[] { Constants.ClaimTypes.PhoneNumber, Constants.ClaimTypes.PhoneNumberVerified }; claims = claims.Where(x => !phoneClaims.Contains(x.Type)); } catch (ValidationException) { // presumably the phone is already associated with another account // so eat the validation exception and let the claim pass thru } } } } public override Task IsActiveAsync(IsActiveContext ctx) { var subject = ctx.Subject; var acct = appUserAccountService.GetByID(subject.GetSubjectId().ToGuid()); ctx.IsActive = acct != null && !acct.IsAccountClosed && acct.IsLoginAllowed; return Task.FromResult(0); } } static class Extensions { public static Guid ToGuid(this string s) { Guid g; if (Guid.TryParse(s, out g)) { return g; } return Guid.Empty; } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Threading { public static class __Interlocked { public static IObservable<Tuple<System.Int32, System.Int32>> Increment(IObservable<System.Int32> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Interlocked.Increment(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.Int64, System.Int64>> Increment(IObservable<System.Int64> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Interlocked.Increment(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.Int32, System.Int32>> Decrement(IObservable<System.Int32> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Interlocked.Decrement(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.Int64, System.Int64>> Decrement(IObservable<System.Int64> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Interlocked.Decrement(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<Tuple<System.Int32, System.Int32>> Exchange(IObservable<System.Int32> location1, IObservable<System.Int32> value) { return Observable.Zip(location1, value, (location1Lambda, valueLambda) => { var result = System.Threading.Interlocked.Exchange(ref location1Lambda, valueLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Int64, System.Int64>> Exchange(IObservable<System.Int64> location1, IObservable<System.Int64> value) { return Observable.Zip(location1, value, (location1Lambda, valueLambda) => { var result = System.Threading.Interlocked.Exchange(ref location1Lambda, valueLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Single, System.Single>> Exchange(IObservable<System.Single> location1, IObservable<System.Single> value) { return Observable.Zip(location1, value, (location1Lambda, valueLambda) => { var result = System.Threading.Interlocked.Exchange(ref location1Lambda, valueLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Double, System.Double>> Exchange(IObservable<System.Double> location1, IObservable<System.Double> value) { return Observable.Zip(location1, value, (location1Lambda, valueLambda) => { var result = System.Threading.Interlocked.Exchange(ref location1Lambda, valueLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Object, System.Object>> Exchange(IObservable<System.Object> location1, IObservable<System.Object> value) { return Observable.Zip(location1, value, (location1Lambda, valueLambda) => { var result = System.Threading.Interlocked.Exchange(ref location1Lambda, valueLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.IntPtr, System.IntPtr>> Exchange(IObservable<System.IntPtr> location1, IObservable<System.IntPtr> value) { return Observable.Zip(location1, value, (location1Lambda, valueLambda) => { var result = System.Threading.Interlocked.Exchange(ref location1Lambda, valueLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<T, T>> Exchange<T>(IObservable<T> location1, IObservable<T> value) where T : class { return Observable.Zip(location1, value, (location1Lambda, valueLambda) => { var result = System.Threading.Interlocked.Exchange(ref location1Lambda, valueLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Int32, System.Int32>> CompareExchange( IObservable<System.Int32> location1, IObservable<System.Int32> value, IObservable<System.Int32> comparand) { return Observable.Zip(location1, value, comparand, (location1Lambda, valueLambda, comparandLambda) => { var result = System.Threading.Interlocked.CompareExchange(ref location1Lambda, valueLambda, comparandLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Int64, System.Int64>> CompareExchange( IObservable<System.Int64> location1, IObservable<System.Int64> value, IObservable<System.Int64> comparand) { return Observable.Zip(location1, value, comparand, (location1Lambda, valueLambda, comparandLambda) => { var result = System.Threading.Interlocked.CompareExchange(ref location1Lambda, valueLambda, comparandLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Single, System.Single>> CompareExchange( IObservable<System.Single> location1, IObservable<System.Single> value, IObservable<System.Single> comparand) { return Observable.Zip(location1, value, comparand, (location1Lambda, valueLambda, comparandLambda) => { var result = System.Threading.Interlocked.CompareExchange(ref location1Lambda, valueLambda, comparandLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Double, System.Double>> CompareExchange( IObservable<System.Double> location1, IObservable<System.Double> value, IObservable<System.Double> comparand) { return Observable.Zip(location1, value, comparand, (location1Lambda, valueLambda, comparandLambda) => { var result = System.Threading.Interlocked.CompareExchange(ref location1Lambda, valueLambda, comparandLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Object, System.Object>> CompareExchange( IObservable<System.Object> location1, IObservable<System.Object> value, IObservable<System.Object> comparand) { return Observable.Zip(location1, value, comparand, (location1Lambda, valueLambda, comparandLambda) => { var result = System.Threading.Interlocked.CompareExchange(ref location1Lambda, valueLambda, comparandLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.IntPtr, System.IntPtr>> CompareExchange( IObservable<System.IntPtr> location1, IObservable<System.IntPtr> value, IObservable<System.IntPtr> comparand) { return Observable.Zip(location1, value, comparand, (location1Lambda, valueLambda, comparandLambda) => { var result = System.Threading.Interlocked.CompareExchange(ref location1Lambda, valueLambda, comparandLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<T, T>> CompareExchange<T>(IObservable<T> location1, IObservable<T> value, IObservable<T> comparand) where T : class { return Observable.Zip(location1, value, comparand, (location1Lambda, valueLambda, comparandLambda) => { var result = System.Threading.Interlocked.CompareExchange(ref location1Lambda, valueLambda, comparandLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Int32, System.Int32>> Add(IObservable<System.Int32> location1, IObservable<System.Int32> value) { return Observable.Zip(location1, value, (location1Lambda, valueLambda) => { var result = System.Threading.Interlocked.Add(ref location1Lambda, valueLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Int64, System.Int64>> Add(IObservable<System.Int64> location1, IObservable<System.Int64> value) { return Observable.Zip(location1, value, (location1Lambda, valueLambda) => { var result = System.Threading.Interlocked.Add(ref location1Lambda, valueLambda); return Tuple.Create(result, location1Lambda); }); } public static IObservable<Tuple<System.Int64, System.Int64>> Read(IObservable<System.Int64> location) { return Observable.Select(location, (locationLambda) => { var result = System.Threading.Interlocked.Read(ref locationLambda); return Tuple.Create(result, locationLambda); }); } public static IObservable<System.Reactive.Unit> MemoryBarrier() { return ObservableExt.Factory(() => System.Threading.Interlocked.MemoryBarrier()); } } }
//----------------------------------------------------------------------- // <copyright file="ARScreen.cs" company="Google"> // // Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- using System.Collections; using UnityEngine; using Tango; /// <summary> /// ARScreen takes the YUV image from the API, resize the image plane and passes /// the YUV data and vertices data to the YUV2RGB shader to produce a properly /// sized RGBA image. /// /// Please note that all the YUV to RGB conversion is done through the YUV2RGB /// shader, no computation is in this class, this class only passes the data to /// shader. /// </summary> public class ARScreen : MonoBehaviour { public Camera m_renderCamera; public Material m_screenMaterial; // Values for debug display. [HideInInspector] public TangoEnums.TangoPoseStatusType m_status; [HideInInspector] public int m_frameCount; private TangoApplication m_tangoApplication; private YUVTexture m_textures; // Matrix for Tango coordinate frame to Unity coordinate frame conversion. // Start of service frame with respect to Unity world frame. private Matrix4x4 m_uwTss; // Unity camera frame with respect to color camera frame. private Matrix4x4 m_cTuc; // Device frame with respect to IMU frame. private Matrix4x4 m_imuTd; // Color camera frame with respect to IMU frame. private Matrix4x4 m_imuTc; // Unity camera frame with respect to IMU frame, this is composed by // Matrix4x4.Inverse(m_imuTd) * m_imuTc * m_cTuc; // We pre-compute this matrix to save some computation in update(). private Matrix4x4 m_dTuc; /// <summary> /// Initialize the AR Screen. /// </summary> private void Start() { // Constant matrix converting start of service frame to Unity world frame. m_uwTss = new Matrix4x4(); m_uwTss.SetColumn(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); m_uwTss.SetColumn(1, new Vector4(0.0f, 0.0f, 1.0f, 0.0f)); m_uwTss.SetColumn(2, new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); m_uwTss.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); // Constant matrix converting Unity world frame frame to device frame. m_cTuc.SetColumn(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); m_cTuc.SetColumn(1, new Vector4(0.0f, -1.0f, 0.0f, 0.0f)); m_cTuc.SetColumn(2, new Vector4(0.0f, 0.0f, 1.0f, 0.0f)); m_cTuc.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); m_tangoApplication = FindObjectOfType<TangoApplication>(); if (m_tangoApplication != null) { if (AndroidHelper.IsTangoCorePresent()) { // Request Tango permissions m_tangoApplication.RegisterPermissionsCallback(_OnTangoApplicationPermissionsEvent); m_tangoApplication.RequestNecessaryPermissionsAndConnect(); m_tangoApplication.Register(this); } else { // If no Tango Core is present let's tell the user to install it. Debug.Log("Tango Core is outdated."); } } else { Debug.Log("No Tango Manager found in scene."); } if (m_tangoApplication != null) { m_textures = m_tangoApplication.GetVideoOverlayTextureYUV(); // Pass YUV textures to shader for process. m_screenMaterial.SetTexture("_YTex", m_textures.m_videoOverlayTextureY); m_screenMaterial.SetTexture("_UTex", m_textures.m_videoOverlayTextureCb); m_screenMaterial.SetTexture("_VTex", m_textures.m_videoOverlayTextureCr); } m_tangoApplication.Register(this); } /// <summary> /// Unity update function, we update our texture from here. /// </summary> private void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { if (m_tangoApplication != null) { m_tangoApplication.Shutdown(); } // This is a temporary fix for a lifecycle issue where calling // Application.Quit() here, and restarting the application immediately, // results in a hard crash. AndroidHelper.AndroidQuit(); } double timestamp = VideoOverlayProvider.RenderLatestFrame(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR); _UpdateTransformation(timestamp); GL.InvalidateState(); } /// <summary> /// This callback function is called after user appoved or declined the permission to use Motion Tracking. /// </summary> /// <param name="permissionsGranted">If the permissions were granted.</param> private void _OnTangoApplicationPermissionsEvent(bool permissionsGranted) { if (permissionsGranted) { m_tangoApplication.InitApplication(); m_tangoApplication.InitProviders(string.Empty); m_tangoApplication.ConnectToService(); // Ask ARScreen to query the camera intrinsics from Tango Service. _SetCameraIntrinsics(); _SetCameraExtrinsics(); } else { AndroidHelper.ShowAndroidToastMessage("Motion Tracking Permissions Needed", true); } } /// <summary> /// Update the camera gameobject's transformation to the pose that on current timestamp. /// </summary> /// <param name="timestamp">Time to update the camera to.</param> private void _UpdateTransformation(double timestamp) { TangoPoseData pose = new TangoPoseData(); TangoCoordinateFramePair pair; pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE; pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; PoseProvider.GetPoseAtTime(pose, timestamp, pair); m_status = pose.status_code; if (pose.status_code == TangoEnums.TangoPoseStatusType.TANGO_POSE_VALID) { Vector3 m_tangoPosition = new Vector3((float)pose.translation[0], (float)pose.translation[1], (float)pose.translation[2]); Quaternion m_tangoRotation = new Quaternion((float)pose.orientation[0], (float)pose.orientation[1], (float)pose.orientation[2], (float)pose.orientation[3]); Matrix4x4 ssTd = Matrix4x4.TRS(m_tangoPosition, m_tangoRotation, Vector3.one); // Here we are getting the pose of Unity camera frame with respect to Unity world. // This is the transformation of our current pose within the Unity coordinate frame. Matrix4x4 uwTuc = m_uwTss * ssTd * m_dTuc; // Extract new local position m_renderCamera.transform.position = uwTuc.GetColumn(3); // Extract new local rotation m_renderCamera.transform.rotation = Quaternion.LookRotation(uwTuc.GetColumn(2), uwTuc.GetColumn(1)); m_frameCount++; } else { m_frameCount = 0; } } /// <summary> /// Set the screen (video overlay image plane) size and vertices. The image plane is not /// applying any project matrix or view matrix. So it's drawing space is the normalized /// screen space, that is [-1.0f, 1.0f] for both width and height. /// </summary> /// <param name="normalizedOffsetX">Horizontal padding to add to the left and right edges.</param> /// <param name="normalizedOffsetY">Vertical padding to add to top and bottom edges.</param> private void _SetScreenVertices(float normalizedOffsetX, float normalizedOffsetY) { MeshFilter meshFilter = GetComponent<MeshFilter>(); Mesh mesh = meshFilter.mesh; mesh.Clear(); // Set the vertices base on the offset, note that the offset is used to compensate // the ratio differences between the camera image and device screen. Vector3[] verts = new Vector3[4]; verts[0] = new Vector3(-1.0f - normalizedOffsetX, -1.0f - normalizedOffsetY, 1.0f); verts[1] = new Vector3(-1.0f - normalizedOffsetX, 1.0f + normalizedOffsetY, 1.0f); verts[2] = new Vector3(1.0f + normalizedOffsetX, 1.0f + normalizedOffsetY, 1.0f); verts[3] = new Vector3(1.0f + normalizedOffsetX, -1.0f - normalizedOffsetY, 1.0f); // Set indices. int[] indices = new int[6]; indices[0] = 0; indices[1] = 2; indices[2] = 3; indices[3] = 1; indices[4] = 2; indices[5] = 0; // Set UVs. Vector2[] uvs = new Vector2[4]; uvs[0] = new Vector2(0, 0); uvs[1] = new Vector2(0, 1f); uvs[2] = new Vector2(1f, 1f); uvs[3] = new Vector2(1f, 0); mesh.Clear(); mesh.vertices = verts; mesh.triangles = indices; mesh.uv = uvs; meshFilter.mesh = mesh; mesh.RecalculateNormals(); } /// <summary> /// The function is for querying the camera extrinsic, for example: the transformation between /// IMU and device frame. These extrinsics is used to transform the pose from the color camera frame /// to the device frame. Because the extrinsic is being queried using the GetPoseAtTime() /// with a desired frame pair, it can only be queried after the ConnectToService() is called. /// /// The device with respect to IMU frame is not directly queryable from API, so we use the IMU /// frame as a temporary value to get the device frame with respect to IMU frame. /// </summary> private void _SetCameraExtrinsics() { double timestamp = 0.0; TangoCoordinateFramePair pair; TangoPoseData poseData = new TangoPoseData(); // Getting the transformation of device frame with respect to IMU frame. pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_IMU; pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; PoseProvider.GetPoseAtTime(poseData, timestamp, pair); Vector3 position = new Vector3((float)poseData.translation[0], (float)poseData.translation[1], (float)poseData.translation[2]); Quaternion quat = new Quaternion((float)poseData.orientation[0], (float)poseData.orientation[1], (float)poseData.orientation[2], (float)poseData.orientation[3]); m_imuTd = Matrix4x4.TRS(position, quat, new Vector3(1.0f, 1.0f, 1.0f)); // Getting the transformation of IMU frame with respect to color camera frame. pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_IMU; pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_CAMERA_COLOR; PoseProvider.GetPoseAtTime(poseData, timestamp, pair); position = new Vector3((float)poseData.translation[0], (float)poseData.translation[1], (float)poseData.translation[2]); quat = new Quaternion((float)poseData.orientation[0], (float)poseData.orientation[1], (float)poseData.orientation[2], (float)poseData.orientation[3]); m_imuTc = Matrix4x4.TRS(position, quat, new Vector3(1.0f, 1.0f, 1.0f)); m_dTuc = Matrix4x4.Inverse(m_imuTd) * m_imuTc * m_cTuc; } /// <summary> /// Set up the size of ARScreen based on camera intrinsics. /// </summary> private void _SetCameraIntrinsics() { TangoCameraIntrinsics intrinsics = new TangoCameraIntrinsics(); VideoOverlayProvider.GetIntrinsics(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, intrinsics); float verticalFOV = 2.0f * Mathf.Rad2Deg * Mathf.Atan((intrinsics.height * 0.5f) / (float)intrinsics.fy); if (!float.IsNaN(verticalFOV)) { m_renderCamera.projectionMatrix = ProjectionMatrixForCameraIntrinsics((float)intrinsics.width, (float)intrinsics.height, (float)intrinsics.fx, (float)intrinsics.fy, (float)intrinsics.cx, (float)intrinsics.cy, 0.1f, 1000.0f); // Here we are scaling the image plane to make sure the image plane's ratio is set as the // color camera image ratio. // If we don't do this, because we are drawing the texture fullscreen, the image plane will // be set to the screen's ratio. float widthRatio = (float)Screen.width / (float)intrinsics.width; float heightRatio = (float)Screen.height / (float)intrinsics.height; if (widthRatio >= heightRatio) { float normalizedOffset = ((widthRatio / heightRatio) - 1.0f) / 2.0f; _SetScreenVertices(0, normalizedOffset); } else { float normalizedOffset = ((heightRatio / widthRatio) - 1.0f) / 2.0f; _SetScreenVertices(normalizedOffset, 0); } } } /// <summary> /// Create a projection matrix from window size, camera intrinsics, and clip settings. /// </summary> /// <param name="width">The width of the camera image.</param> /// <param name="height">The height of the camera image.</param> /// <param name="fx">The x-axis focal length of the camera.</param> /// <param name="fy">The y-axis focal length of the camera.</param> /// <param name="cx">The x-coordinate principal point in pixels.</param> /// <param name="cy">The y-coordinate principal point in pixels.</param> /// <param name="near">The desired near z-clipping plane.</param> /// <param name="far">The desired far z-clipping plane.</param> private Matrix4x4 ProjectionMatrixForCameraIntrinsics(float width, float height, float fx, float fy, float cx, float cy, float near, float far) { float xscale = near / fx; float yscale = near / fy; float xoffset = (cx - (width / 2.0f)) * xscale; // OpenGL coordinates has y pointing downwards so we negate this term. float yoffset = -(cy - (height / 2.0f)) * yscale; return Frustum(xscale * -width / 2.0f - xoffset, xscale * width / 2.0f - xoffset, yscale * -height / 2.0f - yoffset, yscale * height / 2.0f - yoffset, near, far); } /// <summary> /// This is function compute the projection matrix based on frustum size. /// This function's implementation is same as glFrustum. /// </summary> /// <param name="left">Specify the coordinates for the left vertical clipping planes.</param> /// <param name="right">Specify the coordinates for the right vertical clipping planes.</param> /// <param name="bottom">Specify the coordinates for the bottom horizontal clipping planes.</param> /// <param name="top">Specify the coordinates for the top horizontal clipping planes.</param> /// <param name="zNear">Specify the distances to the near depth clipping planes. Both distances must be positive.</param> /// <param name="zFar">Specify the distances to the far depth clipping planes. Both distances must be positive.</param> private Matrix4x4 Frustum(float left, float right, float bottom, float top, float zNear, float zFar) { Matrix4x4 m = new Matrix4x4(); m.SetRow(0, new Vector4(2.0f * zNear / (right - left), 0.0f, (right + left) / (right - left) , 0.0f)); m.SetRow(1, new Vector4(0.0f, 2.0f * zNear/ (top - bottom), (top + bottom) / (top - bottom) , 0.0f)); m.SetRow(2, new Vector4(0.0f, 0.0f, -(zFar + zNear) / (zFar - zNear), -(2 * zFar * zNear) / (zFar - zNear))); m.SetRow(3, new Vector4(0.0f, 0.0f, -1.0f, 0.0f)); return m; } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; using System.Web.UI.DataVisualization.Charting; using System.Drawing; namespace WebApplication1 { public partial class Graphs : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string query = "select distinct ID,StationName from StationMetaData"; DataTable dt = GetData(query); listboxAvailable.DataSource = dt; listboxAvailable.DataTextField = "StationName"; listboxAvailable.DataValueField = "ID"; listboxAvailable.DataBind(); } // Chart2.Visible = false; } private static DataTable GetData(string query) { DataTable dt = new DataTable(); string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand(query)) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.CommandType = CommandType.Text; cmd.Connection = con; sda.SelectCommand = cmd; sda.Fill(dt); } } return dt; } } protected void ShowGraph_Click(object sender, ImageClickEventArgs e) { //Do validations bool isvalidated = true; lblError.Visible = true; lblError.Items.Clear(); int max=0; if (listboxSelected.Items.Count == 0) { lblError.Items.Add(new ListItem("Please select atleast one Station", "Please select atleast one Station")); isvalidated = false; } if (String.IsNullOrEmpty(txtStartDate.Text)) { lblError.Items.Add(new ListItem("Enter Start date", "Enter Start date")); isvalidated = false; } if (String.IsNullOrEmpty(txtEndDate.Text)) { lblError.Items.Add(new ListItem("Enter End date", "Enter End date")); isvalidated = false; } if (CheckBoxList2.SelectedItem == null) { lblError.Items.Add(new ListItem("Select a Parameter", "Select a Parameter")); isvalidated = false; } if (isvalidated) { foreach (ListItem l in CheckBoxList2.Items) { if (!(l.Selected == true)) { continue; } Chart Chart2 = new Chart(); Chart2.ChartAreas.Add("ChartArea1"); Chart2.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineColor = Color.Gray; Chart2.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineColor = Color.Gray; String SelectedParameter = l.Value.ToString(); //Add the stationName foreach (ListItem item in listboxSelected.Items) { TableRow trow = new TableRow(); TableCell tcell_SelectedParameter = new TableCell(); tcell_SelectedParameter.Text = SelectedParameter; /*tcell_SelectedParameter.Font.Bold = true; ; tcell_SelectedParameter.Font.Underline = true; tcell_SelectedParameter.Font.Size = 14; tcell_SelectedParameter.Wrap = false; tcell_SelectedParameter.ColumnSpan = 8;*/ tcell_SelectedParameter.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center; trow.Cells.Add(tcell_SelectedParameter); tbl_Summary.Rows.Add(trow); string query = string.Format("SELECT SampleTime, {0} from WaterQualityData where StationID = '{1}' and SampleTime >= '{2}' and SampleTime <= '{3}' order by SampleTime asc", SelectedParameter, item.Value, txtStartDate.Text, txtEndDate.Text); DataTable dt = GetData(query); Chart2.ChartAreas[0].AxisX.Title = "Date"; Chart2.ChartAreas[0].AxisX.TitleAlignment = System.Drawing.StringAlignment.Center; Chart2.ChartAreas[0].AxisX.TitleFont = new System.Drawing.Font("Arial,Helvetica,sans-serif", 11, FontStyle.Bold); Chart2.ChartAreas[0].AxisY.Title = SelectedParameter; Chart2.ChartAreas[0].AxisY.TitleFont = new System.Drawing.Font("Arial,Helvetica,sans-serif", 11, FontStyle.Bold); Chart2.ChartAreas[0].AxisY.TitleAlignment = System.Drawing.StringAlignment.Center; Chart2.Series.Add(item.Text); Chart2.Series[item.Text].ChartType = SeriesChartType.Line; Chart2.Series[item.Text].IsVisibleInLegend = true; Chart2.Legends.Add(item.Text); String[] x = new String[dt.Rows.Count]; decimal[] y = new decimal[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) { x[i] = (Convert.ToDateTime(dt.Rows[i][0].ToString())).ToString("MM/dd/yy"); y[i] = Convert.ToDecimal(Math.Round(Convert.ToDouble(dt.Rows[i][1]), 2)); Chart2.Series[item.Text].Points.AddXY(x[i], y[i]); Chart2.Series[item.Text].Font = new System.Drawing.Font("Arial,Helvetica,sans-serif", 11); } if (max < x.Length) //to modify the width of the chart max = x.Length; //trow = new TableRow(); //Add the stationName TableCell tcell_stationID = new TableCell(); tcell_stationID.Text = item.Text; tcell_stationID.Wrap = false; tcell_stationID.HorizontalAlign = HorizontalAlign.Center; trow.Cells.Add(tcell_stationID); //Find the minimum value query = string.Format("Select {0},SampleTime from WaterQualityData where {0}=( SELECT Min({0}) from WaterQualityData where StationID = '{1}' and SampleTime >= '{2}' and SampleTime <= '{3}')", SelectedParameter, item.Value, txtStartDate.Text, txtEndDate.Text); //query = string.Format("SELECT * from WaterQualityData ");//where StationID = '{1}' and SampleTime >= '{2}' and SampleTime <= '{3}'", SelectedParameter, item.Value, txtStartDate.Text, txtEndDate.Text); dt = GetData(query); TableCell tcell_min = new TableCell(); TableCell tcell_minDate = new TableCell(); if (dt.Rows.Count > 0) { tcell_min.Text = dt.Rows[0][0].ToString(); // tcell_minDate.Text = (Convert.ToDateTime(dt.Rows[0][1].ToString()).ToShortTimeString()); tcell_minDate.Text = (Convert.ToDateTime(dt.Rows[0][1].ToString()).ToLongDateString()); tcell_minDate.Text += " " + (Convert.ToDateTime(dt.Rows[0][1].ToString()).ToLongTimeString()); } else { tcell_min.Text = " No Data "; tcell_minDate.Text = " No Data "; } tcell_min.HorizontalAlign = HorizontalAlign.Center; tcell_minDate.HorizontalAlign = HorizontalAlign.Center; trow.Cells.Add(tcell_min); trow.Cells.Add(tcell_minDate); //Find the maximum value query = string.Format("Select {0},SampleTime from WaterQualityData where {0}=(SELECT Max({0}) from WaterQualityData where StationID = '{1}' and SampleTime >= '{2}' and SampleTime <= '{3}')", SelectedParameter, item.Value, txtStartDate.Text, txtEndDate.Text); dt = GetData(query); TableCell tcell_max = new TableCell(); TableCell tcell_maxDate = new TableCell(); if (dt.Rows.Count > 0) { tcell_max.Text = dt.Rows[0][0].ToString(); // tcell_maxDate.Text = (Convert.ToDateTime(dt.Rows[0][1].ToString()).ToShorTimeString()); tcell_maxDate.Text = (Convert.ToDateTime(dt.Rows[0][1].ToString()).ToLongDateString()); tcell_maxDate.Text +=" " + (Convert.ToDateTime(dt.Rows[0][1].ToString()).ToLongTimeString()); } else { tcell_max.Text = " No Data "; tcell_maxDate.Text = " No Data "; } tcell_max.HorizontalAlign = HorizontalAlign.Center; tcell_maxDate.HorizontalAlign = HorizontalAlign.Center; trow.Cells.Add(tcell_max); trow.Cells.Add(tcell_maxDate); //Find the Avg Value query = string.Format("SELECT ROUND(avg(CAST({0} AS FLOAT)),4) from WaterQualityData where StationID = '{1}' and SampleTime >= '{2}' and SampleTime <= '{3}'", SelectedParameter, item.Value, txtStartDate.Text, txtEndDate.Text); dt = GetData(query); TableCell tcell_avg = new TableCell(); if (dt.Rows[0][0].ToString()!="") { tcell_avg.Text = dt.Rows[0][0].ToString(); } else { tcell_avg.Text = " No Data "; } trow.Cells.Add(tcell_avg); tbl_Summary.Rows.Add(trow); //Find the Median value query = string.Format(@"(select * from(select WaterQualityData.{0},row_number() over(order by WaterQualityData.{0} asc) as 'row' from WaterQualityData where WaterQualityData.StationID={1}) as temp, (select count(*) as cnt from WaterQualityData where WaterQualityData.StationID={1}) as temp1 where temp.row =temp1.cnt/2)", SelectedParameter, item.Value); dt = GetData(query); TableCell tcell_median = new TableCell(); if (dt.Rows.Count > 0) { tcell_median.Text = dt.Rows[0][0].ToString(); } else { tcell_median.Text = " No Data "; } tcell_median.Wrap = false; tcell_median.HorizontalAlign = HorizontalAlign.Center; trow.Cells.Add(tcell_median); tbl_Summary.Rows.Add(trow); //Find the Standard Deviation query = string.Format("SELECT ROUND(stdev(CAST({0} AS FLOAT)),3) from WaterQualityData where StationID = '{1}' and SampleTime >= '{2}' and SampleTime <= '{3}'", SelectedParameter, item.Value, txtStartDate.Text, txtEndDate.Text); dt = GetData(query); TableCell tcell_stdev = new TableCell(); if (dt.Rows[0][0].ToString() != "") { tcell_stdev.Text = dt.Rows[0][0].ToString(); } else { tcell_stdev.Text = " No Data "; } tcell_stdev.HorizontalAlign = HorizontalAlign.Center; trow.Cells.Add(tcell_stdev); tbl_Summary.Rows.Add(trow); //Find Q1 query = string.Format(@"(select round(avg(temp.{0}),3) from(select WaterQualityData.{0},row_number() over(order by WaterQualityData.{0} asc) as 'row' from WaterQualityData where WaterQualityData.StationID={1}) as temp, (select count(*) as cnt from WaterQualityData where WaterQualityData.StationID={1}) as temp1 where temp.row <= temp1.cnt/4)", SelectedParameter, item.Value); dt = GetData(query); TableCell tcell_Q1 = new TableCell(); if (dt.Rows[0][0].ToString() != "") { tcell_Q1.Text = dt.Rows[0][0].ToString(); } else { tcell_Q1.Text = " No Data "; } tcell_Q1.HorizontalAlign = HorizontalAlign.Center; tcell_Q1.Wrap = false; trow.Cells.Add(tcell_Q1); tbl_Summary.Rows.Add(trow); //Find Q2 query = string.Format(@"(select round(avg(temp.{0}),3) from(select WaterQualityData.{0},row_number() over(order by WaterQualityData.{0} asc) as 'row' from WaterQualityData where WaterQualityData.StationID={1}) as temp, (select count(*) as cnt from WaterQualityData where WaterQualityData.StationID={1}) as temp1 where temp.row > temp1.cnt/4 and temp.row <= temp1.cnt/2)", SelectedParameter, item.Value); dt = GetData(query); TableCell tcell_Q2 = new TableCell(); if (dt.Rows[0][0].ToString() != "") { tcell_Q2.Text = dt.Rows[0][0].ToString(); } else { tcell_Q2.Text = " No Data "; } tcell_Q2.Wrap = false; tcell_Q2.HorizontalAlign = HorizontalAlign.Center; trow.Cells.Add(tcell_Q2); tbl_Summary.Rows.Add(trow); //Find Q3 query = string.Format(@"(select round(avg(temp.{0}),3) from(select WaterQualityData.{0},row_number() over(order by WaterQualityData.{0} asc) as 'row' from WaterQualityData where WaterQualityData.StationID={1}) as temp, (select count(*) as cnt from WaterQualityData where WaterQualityData.StationID={1}) as temp1 where temp.row > temp1.cnt/2 and temp.row <= temp1.cnt*3/4)", SelectedParameter, item.Value); dt = GetData(query); TableCell tcell_Q3 = new TableCell(); if (dt.Rows[0][0].ToString() != "") { tcell_Q3.Text = dt.Rows[0][0].ToString(); } else { tcell_Q3.Text = " No Data "; } tcell_Q3.Wrap = false; tcell_Q3.HorizontalAlign = HorizontalAlign.Center; trow.Cells.Add(tcell_Q3); tbl_Summary.Rows.Add(trow); //Find Q4 query = string.Format(@"(select round(avg(temp.{0}),4) from(select WaterQualityData.{0},row_number() over(order by WaterQualityData.{0} asc) as 'row' from WaterQualityData where WaterQualityData.StationID={1}) as temp, (select count(*) as cnt from WaterQualityData where WaterQualityData.StationID={1}) as temp1 where temp.row > temp1.cnt*3/2 and temp.row <= temp1.cnt)", SelectedParameter, item.Value); dt = GetData(query); TableCell tcell_Q4 = new TableCell(); if (dt.Rows[0][0].ToString() != "") { tcell_Q4.Text = dt.Rows[0][0].ToString(); } else { tcell_Q4.Text = " No Data "; } tcell_Q4.Wrap = false; tcell_Q4.HorizontalAlign = HorizontalAlign.Center; trow.Cells.Add(tcell_Q4); tbl_Summary.Rows.Add(trow); ////Find the Mode value //query = string.Format("SELECT {0},count({0}) from WaterQualityData where StationID = '{1}' and SampleTime >= '{2}' and SampleTime <= '{3}' group by {0} having count({0})>1 order by count({0})", SelectedParameter, item.Value, txtStartDate.Text, txtEndDate.Text); //dt = GetData(query); //int rowcnt = dt.Rows.Count; //TableCell tcell_mode = new TableCell(); //int row = 0; //if (rowcnt == 0) // tcell_mode.Text = "NO MODE"; //while (rowcnt > 0) //{ //To do // if (rowcnt == 1) // tcell_mode.Text = dt.Rows[row][0].ToString(); // else // { // if (row == rowcnt - 1) // { // if (dt.Rows[row][1].ToString() == dt.Rows[row - 1][1].ToString()) // tcell_mode.Text += dt.Rows[row][0].ToString(); // break; // } // else // { // if (dt.Rows[row][1].ToString() == dt.Rows[row + 1][1].ToString()) // tcell_mode.Text += dt.Rows[row][0].ToString() + ","; // else // { // break; // } // } // } // row++; // rowcnt--; //} //tcell_mode.Wrap = false; //trow.Cells.Add(tcell_mode); //tbl_Summary.Rows.Add(trow); } if (max > 3) { Chart2.Width = 150 * max; } Panel1.Controls.Add(Chart2); } } tbl_Summary.BorderColor = System.Drawing.Color.Black; tbl_Summary.BorderStyle = BorderStyle.Solid; } protected void btn_Remove_Click(object sender, ImageClickEventArgs e) { if (listboxSelected.Items.Count == 0) { tbl_Summary.Rows.Clear(); } for (int i = listboxSelected.Items.Count - 1; i >= 0; i--) { if (listboxSelected.Items[i].Selected) { listboxAvailable.Items.Add(listboxSelected.Items[i]); listboxSelected.Items.Remove(listboxSelected.Items[i]); } } } protected void btn_Add_Click(object sender, ImageClickEventArgs e) { for (int i = listboxAvailable.Items.Count - 1; i >= 0; i--) { if (listboxAvailable.Items[i].Selected) { listboxSelected.Items.Add(listboxAvailable.Items[i]); listboxAvailable.Items.Remove(listboxAvailable.Items[i]); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Collections.Generic; using NativeCallManagedComVisible; using TestLibrary; // Don't set ComVisible. // [assembly: ComVisible(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("41DDB0BD-1E88-4B0C-BD23-FD3B7E4037A8")] /// <summary> /// Interface with ComImport. /// </summary> [ComImport] [Guid("52E5F852-BD3E-4DF2-8826-E1EC39557943")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceComImport { int Foo(); } /// <summary> /// Interface visible with ComVisible(true). /// </summary> [ComVisible(true)] [Guid("8FDE13DC-F917-44FF-AAC8-A638FD27D647")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceVisibleTrue { int Foo(); } /// <summary> /// Interface not visible with ComVisible(false). /// </summary> [ComVisible(false)] [Guid("0A2EF649-371D-4480-B0C7-07F455C836D3")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceVisibleFalse { int Foo(); } /// <summary> /// Interface not visible without ComVisible(). /// </summary> [Guid("FB504D72-39C4-457F-ACF4-3E5D8A31AAE4")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceWithoutVisible { int Foo(); } /// <summary> /// Interface not public. /// </summary> [ComVisible(true)] [Guid("11320010-13FA-4B40-8580-8CF92EE70774")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IInterfaceNotPublic { int Foo(); } /// <summary> /// Generic interface with ComVisible(true). /// </summary> [ComVisible(true)] [Guid("BA4B32D4-1D73-4605-AD0A-900A31E75BC3")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceGenericVisibleTrue<T> { T Foo(); } /// <summary> /// Generic class for guid generator. /// </summary> public class GenericClassW2Pars<T1, T2> { T1 Foo(T2 a) { return default(T1); } } /// <summary> /// Derived interface visible with ComVisible(true) and GUID. /// </summary> [ComVisible(true)] [Guid("FE62A5B9-34C4-4EAF-AF0A-1AD390B15BDB")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDerivedInterfaceVisibleTrueGuid { int Foo(); } /// <summary> /// Derived interface visible with ComVisible(true) wothout GUID. /// </summary> [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDerivedInterfaceVisibleTrueNoGuid { int Foo1(UInt16 int16Val, bool boolVal); int Foo5(Int32 int32Val); } /// <summary> /// Derived interface without visibility and without GUID. /// </summary> public interface IDerivedInterfaceWithoutVisibleNoGuid { int Foo7(Int32 int32Val); } /// <summary> /// Interface visible with ComVisible(true) and without Custom Attribute Guid. /// Note that in this test, change the method sequence in the interface will /// change the GUID and could reduce the test efficiency. /// </summary> [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceVisibleTrueNoGuid : IDerivedInterfaceVisibleTrueGuid, IDerivedInterfaceVisibleTrueNoGuid, IDerivedInterfaceWithoutVisibleNoGuid { new int Foo1(UInt16 int16Val, bool boolVal); new int Foo(); int Foo2(string str, out int outIntVal, IntPtr intPtrVal, int[] arrayVal, byte inByteVal = 0, int inIntVal = 0); int Foo3(ref short refShortVal, params byte[] paramsList); int Foo4(ref List<short> refShortVal, GenericClassW2Pars<int, short> genericClass, params object[] paramsList); } /// <summary> /// Interface not visible and without Custom Attribute Guid. /// </summary> [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceNotVisibleNoGuid { int Foo(); } /// <summary> /// Interface visible with ComVisible(true), without Custom Attribute Guid and a generic method. /// </summary> [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceVisibleTrueNoGuidGeneric { int Foo<T>(T genericVal); } /// <summary> /// Interface with ComImport derived from an interface with ComImport. /// </summary> [ComImport] [Guid("943759D7-3552-43AD-9C4D-CC2F787CF36E")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceComImport_ComImport : IInterfaceComImport { new int Foo(); } /// <summary> /// Interface with ComVisible(true) derived from an interface with ComImport. /// </summary> [ComVisible(true)] [Guid("75DE245B-0CE3-4B07-8761-328906C750B7")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceVisibleTrue_ComImport : IInterfaceComImport { new int Foo(); } /// <summary> /// Interface with ComVisible(false) derived from an interface with ComImport. /// </summary> [ComVisible(false)] [Guid("C73D96C3-B005-42D6-93F5-E30AEE08C66C")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceVisibleFalse_ComImport : IInterfaceComImport { new int Foo(); } /// <summary> /// Interface with ComVisible(true) derived from an interface with ComVisible(true). /// </summary> [ComVisible(true)] [Guid("60B3917B-9CC2-40F2-A975-CD6898DA697F")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceVisibleTrue_VisibleTrue : IInterfaceVisibleTrue { new int Foo(); } /// <summary> /// Interface with ComVisible(false) derived from an interface with ComVisible(true). /// </summary> [ComVisible(false)] [Guid("2FC59DDB-B1D0-4678-93AF-6A48E838B705")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceVisibleFalse_VisibleTrue : IInterfaceVisibleTrue { new int Foo(); } /// <summary> /// Interface with ComVisible(true) derived from an interface with ComVisible(false). /// </summary> [ComVisible(true)] [Guid("C82C25FC-FBAD-4EA9-BED1-343C887464B5")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInterfaceVisibleTrue_VisibleFalse : IInterfaceVisibleFalse { new int Foo(); } /// <summary> /// Interface with ComVisible(true) derived from an not public interface. /// </summary> [ComVisible(true)] [Guid("8A4C1691-5615-4762-8568-481DC671F9CE")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IInterfaceNotPublic_VisibleTrue : IInterfaceVisibleTrue { new int Foo(); } /// <summary> /// Class visible with ComVisible(true). /// </summary> [ComVisible(true)] [Guid("48FC2EFC-C7ED-4E02-8D02-F05B6A439FC9")] public sealed class ClassVisibleTrueServer : IInterfaceComImport, IInterfaceVisibleTrue, IInterfaceVisibleFalse, IInterfaceWithoutVisible, IInterfaceNotPublic, IInterfaceVisibleTrueNoGuid, IInterfaceNotVisibleNoGuid, IInterfaceComImport_ComImport, IInterfaceVisibleTrue_ComImport, IInterfaceVisibleFalse_ComImport, IInterfaceVisibleTrue_VisibleTrue, IInterfaceVisibleFalse_VisibleTrue, IInterfaceVisibleTrue_VisibleFalse, IInterfaceNotPublic_VisibleTrue { int IInterfaceComImport.Foo() { return 1; } int IInterfaceVisibleTrue.Foo() { return 2; } int IInterfaceVisibleFalse.Foo() { return 3; } int IInterfaceWithoutVisible.Foo() { return 4; } int IInterfaceNotPublic.Foo() { return 5; } int IInterfaceVisibleTrueNoGuid.Foo() { return 6; } int IInterfaceVisibleTrueNoGuid.Foo1(UInt16 int16Val, bool boolVal) { return 7; } int IInterfaceVisibleTrueNoGuid.Foo2(string str, out int outIntVal, IntPtr intPtrVal, int[] arrayVal, byte inByteVal, int inIntVal) { outIntVal = 10; return 8; } int IInterfaceVisibleTrueNoGuid.Foo3(ref short refShortVal, params byte[] paramsList) { return 9; } int IInterfaceVisibleTrueNoGuid.Foo4(ref List<short> refShortVal, GenericClassW2Pars<int, short> genericClass, params object[] paramsList) { return 10; } int IDerivedInterfaceVisibleTrueGuid.Foo() { return 12; } int IDerivedInterfaceVisibleTrueNoGuid.Foo1(UInt16 int16Val, bool boolVal) { return 13; } int IDerivedInterfaceVisibleTrueNoGuid.Foo5(Int32 int32Val) { return 14; } int IDerivedInterfaceWithoutVisibleNoGuid.Foo7(Int32 int32Val) { return 15; } int IInterfaceNotVisibleNoGuid.Foo() { return 16; } int IInterfaceComImport_ComImport.Foo() { return 101; } int IInterfaceVisibleTrue_ComImport.Foo() { return 102; } int IInterfaceVisibleFalse_ComImport.Foo() { return 103; } int IInterfaceVisibleTrue_VisibleTrue.Foo() { return 104; } int IInterfaceVisibleFalse_VisibleTrue.Foo() { return 105; } int IInterfaceVisibleTrue_VisibleFalse.Foo() { return 106; } int IInterfaceNotPublic_VisibleTrue.Foo() { return 107; } int Foo() { return 9; } } /// <summary> /// Class not visible with ComVisible(false). /// </summary> [ComVisible(false)] [Guid("6DF17EC1-A8F4-4693-B195-EDB27DF00170")] public sealed class ClassVisibleFalseServer : IInterfaceComImport, IInterfaceVisibleTrue, IInterfaceVisibleFalse, IInterfaceWithoutVisible, IInterfaceNotPublic { int IInterfaceComImport.Foo() { return 120; } int IInterfaceVisibleTrue.Foo() { return 121; } int IInterfaceVisibleFalse.Foo() { return 122; } int IInterfaceWithoutVisible.Foo() { return 123; } int IInterfaceNotPublic.Foo() { return 124; } int Foo() { return 129; } } /// <summary> /// Class not visible without ComVisible(). /// </summary> [Guid("A57430B8-E0C1-486E-AE57-A15D6A729F99")] public sealed class ClassWithoutVisibleServer : IInterfaceComImport, IInterfaceVisibleTrue, IInterfaceVisibleFalse, IInterfaceWithoutVisible, IInterfaceNotPublic { int IInterfaceComImport.Foo() { return 130; } int IInterfaceVisibleTrue.Foo() { return 131; } int IInterfaceVisibleFalse.Foo() { return 132; } int IInterfaceWithoutVisible.Foo() { return 133; } int IInterfaceNotPublic.Foo() { return 134; } int Foo() { return 139; } } /// <summary> /// Generic visible class with ComVisible(true). /// </summary> [ComVisible(true)] [Guid("3CD290FA-1CD0-4370-B8E6-5A573F78C9F7")] public sealed class ClassGenericServer<T> : IInterfaceVisibleTrue, IInterfaceGenericVisibleTrue<T>, IInterfaceComImport { int IInterfaceComImport.Foo() { return 140; } int IInterfaceVisibleTrue.Foo() { return 141; } T IInterfaceGenericVisibleTrue<T>.Foo() { return default(T); } T Foo() { return default(T); } } public class ComVisibleServer { /// <summary> /// Nested interface with ComImport. /// </summary> [ComImport] [Guid("1D927BC5-1530-4B8E-A183-995425CE4A0A")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceComImport { int Foo(); } /// <summary> /// Nested interface visible with ComVisible(true). /// </summary> [ComVisible(true)] [Guid("39209692-2568-4B1E-A6C8-A5C7F141D278")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceVisibleTrue { int Foo(); } /// <summary> /// Nested interface not visible with ComVisible(false). /// </summary> [ComVisible(false)] [Guid("1CE4B033-4927-447A-9F91-998357B32ADF")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceVisibleFalse { int Foo(); } /// <summary> /// Nested interface not visible without ComVisible(). /// </summary> [Guid("C770422A-C363-49F1-AAA1-3EC81A452816")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceWithoutVisible { int Foo(); } /// <summary> /// Nested interface not public. /// </summary> [ComVisible(true)] [Guid("F776FF8A-0673-49C2-957A-33C2576062ED")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface INestedInterfaceNotPublic { int Foo(); } /// <summary> /// Nested visible interface with ComVisible(true). /// </summary> public class NestedClass { [ComVisible(true)] [Guid("B31B4EC1-3B59-41C4-B3A0-CF89638CB837")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceNestedInClass { int Foo(); } } /// <summary> /// Generic interface with ComVisible(true). /// </summary> [ComVisible(true)] [Guid("D7A8A196-5D85-4C85-94E4-8344ED2C7277")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceGenericVisibleTrue<T> { T Foo(); } /// <summary> /// Nested interface with ComImport derived from an interface with ComImport. /// </summary> [ComImport] [Guid("C57D849A-A1A9-4CDC-A609-789D79F9332C")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceComImport_ComImport : INestedInterfaceComImport { new int Foo(); } /// <summary> /// Nested interface with ComVisible(true) derived from an interface with ComImport. /// </summary> [ComVisible(true)] [Guid("81F28686-F257-4B7E-A47F-57C9775BE2CE")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceVisibleTrue_ComImport : INestedInterfaceComImport { new int Foo(); } /// <summary> /// Nested interface with ComVisible(false) derived from an interface with ComImport. /// </summary> [ComVisible(false)] [Guid("FAAB7E6C-8548-429F-AD34-0CEC3EBDD7B7")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceVisibleFalse_ComImport : INestedInterfaceComImport { new int Foo(); } /// <summary> /// Nested interface with ComVisible(true) derived from an interface with ComVisible(true). /// </summary> [ComVisible(true)] [Guid("BEFD79A9-D8E6-42E4-8228-1892298460D7")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceVisibleTrue_VisibleTrue : INestedInterfaceVisibleTrue { new int Foo(); } /// <summary> /// Nested interface with ComVisible(false) derived from an interface with ComVisible(true). /// </summary> [ComVisible(false)] [Guid("5C497454-EA83-4F79-B990-4EB28505E801")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceVisibleFalse_VisibleTrue : INestedInterfaceVisibleTrue { new int Foo(); } /// <summary> /// Nested interface with ComVisible(true) derived from an interface with ComVisible(false). /// </summary> [ComVisible(true)] [Guid("A17CF08F-EEC4-4EA5-B12C-5A603101415D")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface INestedInterfaceVisibleTrue_VisibleFalse : INestedInterfaceVisibleFalse { new int Foo(); } /// <summary> /// Nested interface with ComVisible(true) derived from an not public interface. /// </summary> [ComVisible(true)] [Guid("40B723E9-E1BE-4F55-99CD-D2590D191A53")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface INestedInterfaceNotPublic_VisibleTrue : INestedInterfaceVisibleTrue { new int Foo(); } /// <summary> /// Nested class visible with ComVisible(true). /// </summary> [ComVisible(true)] [Guid("CF681980-CE6D-421E-8B21-AEAE3F1B7DAC")] public sealed class NestedClassVisibleTrueServer : INestedInterfaceComImport, INestedInterfaceVisibleTrue, INestedInterfaceVisibleFalse, INestedInterfaceWithoutVisible, INestedInterfaceNotPublic, NestedClass.INestedInterfaceNestedInClass, INestedInterfaceComImport_ComImport, INestedInterfaceVisibleTrue_ComImport, INestedInterfaceVisibleFalse_ComImport, INestedInterfaceVisibleTrue_VisibleTrue, INestedInterfaceVisibleFalse_VisibleTrue, INestedInterfaceVisibleTrue_VisibleFalse, INestedInterfaceNotPublic_VisibleTrue { int INestedInterfaceComImport.Foo() { return 10; } int INestedInterfaceVisibleTrue.Foo() { return 11; } int INestedInterfaceVisibleFalse.Foo() { return 12; } int INestedInterfaceWithoutVisible.Foo() { return 13; } int INestedInterfaceNotPublic.Foo() { return 14; } int NestedClass.INestedInterfaceNestedInClass.Foo() { return 110; } int INestedInterfaceComImport_ComImport.Foo() { return 111; } int INestedInterfaceVisibleTrue_ComImport.Foo() { return 112; } int INestedInterfaceVisibleFalse_ComImport.Foo() { return 113; } int INestedInterfaceVisibleTrue_VisibleTrue.Foo() { return 114; } int INestedInterfaceVisibleFalse_VisibleTrue.Foo() { return 115; } int INestedInterfaceVisibleTrue_VisibleFalse.Foo() { return 116; } int INestedInterfaceNotPublic_VisibleTrue.Foo() { return 117; } int Foo() { return 19; } } /// <summary> /// Nested class not visible with ComVisible(false). /// </summary> [ComVisible(false)] [Guid("6DF17EC1-A8F4-4693-B195-EDB27DF00170")] public sealed class NestedClassVisibleFalseServer : INestedInterfaceComImport, INestedInterfaceVisibleTrue, INestedInterfaceVisibleFalse, INestedInterfaceWithoutVisible, INestedInterfaceNotPublic { int INestedInterfaceComImport.Foo() { return 20; } int INestedInterfaceVisibleTrue.Foo() { return 21; } int INestedInterfaceVisibleFalse.Foo() { return 22; } int INestedInterfaceWithoutVisible.Foo() { return 23; } int INestedInterfaceNotPublic.Foo() { return 24; } int Foo() { return 29; } } /// <summary> /// Nested class not visible without ComVisible(). /// </summary> [Guid("A57430B8-E0C1-486E-AE57-A15D6A729F99")] public sealed class NestedClassWithoutVisibleServer : INestedInterfaceComImport, INestedInterfaceVisibleTrue, INestedInterfaceVisibleFalse, INestedInterfaceWithoutVisible, INestedInterfaceNotPublic { int INestedInterfaceComImport.Foo() { return 30; } int INestedInterfaceVisibleTrue.Foo() { return 31; } int INestedInterfaceVisibleFalse.Foo() { return 32; } int INestedInterfaceWithoutVisible.Foo() { return 33; } int INestedInterfaceNotPublic.Foo() { return 34; } int Foo() { return 39; } } /// <summary> /// Generic visible nested class with ComVisible(true). /// </summary> [ComVisible(true)] [Guid("CAFBD2FF-710A-4E83-9229-42FA16963424")] public sealed class NestedClassGenericServer<T> : INestedInterfaceVisibleTrue, INestedInterfaceGenericVisibleTrue<T>, INestedInterfaceComImport { int INestedInterfaceComImport.Foo() { return 40; } int INestedInterfaceVisibleTrue.Foo() { return 41; } T INestedInterfaceGenericVisibleTrue<T>.Foo() { return default(T); } T Foo() { return default(T); } } [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceComImport([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceVisibleTrue([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceVisibleFalse([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceWithoutVisible([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceNotPublic([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceVisibleTrueNoGuid([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceNotVisibleNoGuid([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceGenericVisibleTrue([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceComImport_ComImport([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceVisibleTrue_ComImport([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceVisibleFalse_ComImport([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceVisibleTrue_VisibleTrue([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceVisibleFalse_VisibleTrue([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceVisibleTrue_VisibleFalse([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_InterfaceNotPublic_VisibleTrue([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceComImport([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceVisibleTrue([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceVisibleFalse([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceWithoutVisible([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceNotPublic([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceNestedInClass([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceGenericVisibleTrue([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceComImport_ComImport([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceVisibleTrue_ComImport([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceVisibleFalse_ComImport([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceVisibleTrue_VisibleTrue([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceVisibleFalse_VisibleTrue([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceVisibleTrue_VisibleFalse([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); [DllImport("ComVisibleNative")] public static extern int CCWTest_NestedInterfaceNotPublic_VisibleTrue([MarshalAs(UnmanagedType.IUnknown)] object unk, out int fooSuccessVal); /// <summary> /// Test case set for ComVisible. The assembly is set as [assembly: ComVisible(false)] /// </summary> /// <returns></returns> private static void RunComVisibleTests() { int fooSuccessVal = 0; // // Tests for class with ComVisible(true) // Console.WriteLine("Class with ComVisible(true)"); ClassVisibleTrueServer visibleBaseClass = new ClassVisibleTrueServer(); Console.WriteLine("CCWTest_InterfaceComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceComImport((object)visibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(1, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceVisibleTrue"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceVisibleTrue((object)visibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(2, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceVisibleFalse"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_InterfaceVisibleFalse((object)visibleBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); Console.WriteLine("CCWTest_InterfaceWithoutVisible"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceWithoutVisible((object)visibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(4, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceNotPublic"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_InterfaceNotPublic((object)visibleBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); Console.WriteLine("CCWTest_InterfaceVisibleTrueNoGuid"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceVisibleTrueNoGuid((object)visibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(6, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceNotVisibleNoGuid"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceNotVisibleNoGuid((object)visibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(16, fooSuccessVal, "COM method didn't return the expected value."); // // Tests for nested Interface in a class with ComVisible(true) // Console.WriteLine("Nested Interface in a class with ComVisible(true)"); Console.WriteLine("CCWTest_InterfaceComImport_ComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceComImport_ComImport((object)visibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(101, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceVisibleTrue_ComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceVisibleTrue_ComImport((object)visibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(102, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceVisibleFalse_ComImport"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_InterfaceVisibleFalse_ComImport((object)visibleBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); Console.WriteLine("CCWTest_InterfaceVisibleTrue_VisibleTrue"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceVisibleTrue_VisibleTrue((object)visibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(104, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceVisibleFalse_VisibleTrue"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_InterfaceVisibleFalse_VisibleTrue((object)visibleBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); Console.WriteLine("CCWTest_InterfaceVisibleTrue_VisibleFalse"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceVisibleTrue_VisibleFalse((object)visibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(106, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceNotPublic_VisibleTrue"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_InterfaceNotPublic_VisibleTrue((object)visibleBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); // // Tests for class with ComVisible(false) // Console.WriteLine("Class with ComVisible(false)"); ClassVisibleFalseServer visibleFalseBaseClass = new ClassVisibleFalseServer(); Console.WriteLine("CCWTest_InterfaceComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceComImport((object)visibleFalseBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(120, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceVisibleTrue"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceVisibleTrue((object)visibleFalseBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(121, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceVisibleFalse"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_InterfaceVisibleFalse((object)visibleFalseBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); Console.WriteLine("CCWTest_InterfaceWithoutVisible"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceWithoutVisible((object)visibleFalseBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(123, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceNotPublic"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_InterfaceNotPublic((object)visibleFalseBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); // // Tests for class without ComVisible() // Console.WriteLine("Class without ComVisible()"); ClassWithoutVisibleServer withoutVisibleBaseClass = new ClassWithoutVisibleServer(); Console.WriteLine("CCWTest_InterfaceComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceComImport((object)withoutVisibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(130, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceVisibleTrue"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceVisibleTrue((object)withoutVisibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(131, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceVisibleFalse"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_InterfaceVisibleFalse((object)withoutVisibleBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); Console.WriteLine("CCWTest_InterfaceWithoutVisible"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceWithoutVisible((object)withoutVisibleBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(133, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceNotPublic"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_InterfaceNotPublic((object)withoutVisibleBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); // // Tests for generic class with ComVisible(true) // Console.WriteLine("Generic class with ComVisible(true)"); ClassGenericServer<int> genericServer = new ClassGenericServer<int>(); Console.WriteLine("CCWTest_InterfaceComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceComImport((object)genericServer, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(140, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceVisibleTrue"); Assert.AreEqual(Helpers.S_OK, CCWTest_InterfaceVisibleTrue((object)genericServer, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(141, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_InterfaceGenericVisibleTrue"); Assert.AreEqual(Helpers.COR_E_INVALIDOPERATION, CCWTest_InterfaceGenericVisibleTrue((object)genericServer, out fooSuccessVal), "Returned diferent exception than the expected COR_E_INVALIDOPERATION."); // // Tests for nested class with ComVisible(true) // Console.WriteLine("Nested class with ComVisible(true)"); NestedClassVisibleTrueServer visibleNestedBaseClass = new NestedClassVisibleTrueServer(); Console.WriteLine("CCWTest_NestedInterfaceComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceComImport((object)visibleNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(10, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceVisibleTrue"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceVisibleTrue((object)visibleNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(11, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceVisibleFalse"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_NestedInterfaceVisibleFalse((object)visibleNestedBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); Console.WriteLine("CCWTest_NestedInterfaceWithoutVisible"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceWithoutVisible((object)visibleNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(13, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceNotPublic"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_NestedInterfaceNotPublic((object)visibleNestedBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); // // Tests for nested Interface in a nested class with ComVisible(true) // Console.WriteLine("Nested Interface in a nested class with ComVisible(true)"); Console.WriteLine("CCWTest_NestedInterfaceNestedInClass"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceNestedInClass((object)visibleNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(110, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceComImport_ComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceComImport_ComImport((object)visibleNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(111, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceVisibleTrue_ComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceVisibleTrue_ComImport((object)visibleNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(112, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceVisibleFalse_ComImport"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_NestedInterfaceVisibleFalse_ComImport((object)visibleNestedBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); Console.WriteLine("CCWTest_NestedInterfaceVisibleTrue_VisibleTrue"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceVisibleTrue_VisibleTrue((object)visibleNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(114, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceVisibleFalse_VisibleTrue"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_NestedInterfaceVisibleFalse_VisibleTrue((object)visibleNestedBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); Console.WriteLine("CCWTest_NestedInterfaceVisibleTrue_VisibleFalse"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceVisibleTrue_VisibleFalse((object)visibleNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(116, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceNotPublic_VisibleTrue"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_NestedInterfaceNotPublic_VisibleTrue((object)visibleNestedBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); // // Tests for nested class with ComVisible(false) // Console.WriteLine("Nested class with ComVisible(false)"); NestedClassVisibleFalseServer visibleFalseNestedBaseClass = new NestedClassVisibleFalseServer(); Console.WriteLine("CCWTest_NestedInterfaceComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceComImport((object)visibleFalseNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(20, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceVisibleTrue"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceVisibleTrue((object)visibleFalseNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(21, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceVisibleFalse"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_NestedInterfaceVisibleFalse((object)visibleFalseNestedBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); Console.WriteLine("CCWTest_NestedInterfaceWithoutVisible"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceWithoutVisible((object)visibleFalseNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(23, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceNotPublic"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_NestedInterfaceNotPublic((object)visibleFalseNestedBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); // // Tests for nested class without ComVisible() // Console.WriteLine("Nested class without ComVisible()"); NestedClassWithoutVisibleServer withoutVisibleNestedBaseClass = new NestedClassWithoutVisibleServer(); Console.WriteLine("CCWTest_NestedInterfaceComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceComImport((object)withoutVisibleNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(30, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceVisibleTrue"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceVisibleTrue((object)withoutVisibleNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(31, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceVisibleFalse"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_NestedInterfaceVisibleFalse((object)withoutVisibleNestedBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); Console.WriteLine("CCWTest_NestedInterfaceWithoutVisible"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceWithoutVisible((object)withoutVisibleNestedBaseClass, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(33, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceNotPublic"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_NestedInterfaceNotPublic((object)withoutVisibleNestedBaseClass, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); // // Tests for generic nested class with ComVisible(true) // Console.WriteLine("Nested generic class with ComVisible(true)"); NestedClassGenericServer<int> nestedGenericServer = new NestedClassGenericServer<int>(); Console.WriteLine("CCWTest_NestedInterfaceComImport"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceComImport((object)nestedGenericServer, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(40, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceVisibleTrue"); Assert.AreEqual(Helpers.S_OK, CCWTest_NestedInterfaceVisibleTrue((object)nestedGenericServer, out fooSuccessVal), "COM method thrown an unexpected exception."); Assert.AreEqual(41, fooSuccessVal, "COM method didn't return the expected value."); Console.WriteLine("CCWTest_NestedInterfaceGenericVisibleTrue"); Assert.AreEqual(Helpers.E_NOINTERFACE, CCWTest_NestedInterfaceGenericVisibleTrue((object)nestedGenericServer, out fooSuccessVal), "Returned diferent exception than the expected E_NOINTERFACE."); } public static int Main() { try { RunComVisibleTests(); return 100; } catch (Exception e) { Console.WriteLine($"Test Failure: {e}"); return 101; } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Input; namespace System.Windows.Controls { /// <summary> /// A column that displays a check box. /// </summary> public class DataGridCheckBoxColumn : DataGridBoundColumn { static DataGridCheckBoxColumn() { ElementStyleProperty.OverrideMetadata(typeof(DataGridCheckBoxColumn), new FrameworkPropertyMetadata(DefaultElementStyle)); EditingElementStyleProperty.OverrideMetadata(typeof(DataGridCheckBoxColumn), new FrameworkPropertyMetadata(DefaultEditingElementStyle)); } #region Styles /// <summary> /// The default value of the ElementStyle property. /// This value can be used as the BasedOn for new styles. /// </summary> public static Style DefaultElementStyle { get { if (_defaultElementStyle == null) { Style style = new Style(typeof(CheckBox)); // When not in edit mode, the end-user should not be able to toggle the state style.Setters.Add(new Setter(UIElement.IsHitTestVisibleProperty, false)); style.Setters.Add(new Setter(UIElement.FocusableProperty, false)); style.Setters.Add(new Setter(CheckBox.HorizontalAlignmentProperty, HorizontalAlignment.Center)); style.Setters.Add(new Setter(CheckBox.VerticalAlignmentProperty, VerticalAlignment.Top)); style.Seal(); _defaultElementStyle = style; } return _defaultElementStyle; } } /// <summary> /// The default value of the EditingElementStyle property. /// This value can be used as the BasedOn for new styles. /// </summary> public static Style DefaultEditingElementStyle { get { if (_defaultEditingElementStyle == null) { Style style = new Style(typeof(CheckBox)); style.Setters.Add(new Setter(CheckBox.HorizontalAlignmentProperty, HorizontalAlignment.Center)); style.Setters.Add(new Setter(CheckBox.VerticalAlignmentProperty, VerticalAlignment.Top)); style.Seal(); _defaultEditingElementStyle = style; } return _defaultEditingElementStyle; } } #endregion #region Element Generation /// <summary> /// Creates the visual tree for boolean based cells. /// </summary> protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { return GenerateCheckBox(/* isEditing = */ false, cell); } /// <summary> /// Creates the visual tree for boolean based cells. /// </summary> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { return GenerateCheckBox(/* isEditing = */ true, cell); } private CheckBox GenerateCheckBox(bool isEditing, DataGridCell cell) { CheckBox checkBox = (cell != null) ? (cell.Content as CheckBox) : null; if (checkBox == null) { checkBox = new CheckBox(); } checkBox.IsThreeState = IsThreeState; ApplyStyle(isEditing, /* defaultToElementStyle = */ true, checkBox); ApplyBinding(checkBox, CheckBox.IsCheckedProperty); return checkBox; } protected internal override void RefreshCellContent(FrameworkElement element, string propertyName) { DataGridCell cell = element as DataGridCell; if (cell != null && string.Compare(propertyName, "IsThreeState", StringComparison.Ordinal) == 0) { var checkBox = cell.Content as CheckBox; if (checkBox != null) { checkBox.IsThreeState = IsThreeState; } } else { base.RefreshCellContent(element, propertyName); } } #endregion #region Editing /// <summary> /// The DependencyProperty for the IsThreeState property. /// Flags: None /// Default Value: false /// </summary> public static readonly DependencyProperty IsThreeStateProperty = CheckBox.IsThreeStateProperty.AddOwner( typeof(DataGridCheckBoxColumn), new FrameworkPropertyMetadata(false, DataGridColumn.NotifyPropertyChangeForRefreshContent)); /// <summary> /// The IsThreeState property determines whether the control supports two or three states. /// IsChecked property can be set to null as a third state when IsThreeState is true /// </summary> public bool IsThreeState { get { return (bool)GetValue(IsThreeStateProperty); } set { SetValue(IsThreeStateProperty, value); } } /// <summary> /// Called when a cell has just switched to edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <param name="editingEventArgs">The event args of the input event that caused the cell to go into edit mode. May be null.</param> /// <returns>The unedited value of the cell.</returns> protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs) { CheckBox checkBox = editingElement as CheckBox; if (checkBox != null) { checkBox.Focus(); bool? uneditedValue = checkBox.IsChecked; // If a click or a space key invoked the begin edit, then do an immediate toggle if ((IsMouseLeftButtonDown(editingEventArgs) && IsMouseOver(checkBox, editingEventArgs)) || IsSpaceKeyDown(editingEventArgs)) { checkBox.IsChecked = (uneditedValue != true); } return uneditedValue; } return (bool?) false; } internal override void OnInput(InputEventArgs e) { // Space key down will begin edit mode if (IsSpaceKeyDown(e)) { BeginEdit(e, true); } } private static bool IsMouseLeftButtonDown(RoutedEventArgs e) { MouseButtonEventArgs mouseArgs = e as MouseButtonEventArgs; return (mouseArgs != null) && (mouseArgs.ChangedButton == MouseButton.Left) && (mouseArgs.ButtonState == MouseButtonState.Pressed); } private static bool IsMouseOver(CheckBox checkBox, RoutedEventArgs e) { // This element is new, so the IsMouseOver property will not have been updated // yet, but there is enough information to do a hit-test. return checkBox.InputHitTest(((MouseButtonEventArgs)e).GetPosition(checkBox)) != null; } private static bool IsSpaceKeyDown(RoutedEventArgs e) { KeyEventArgs keyArgs = e as KeyEventArgs; return (keyArgs != null) && keyArgs.RoutedEvent == Keyboard.KeyDownEvent && ((keyArgs.KeyStates & KeyStates.Down) == KeyStates.Down) && (keyArgs.Key == Key.Space); } #endregion #region Data private static Style _defaultElementStyle; private static Style _defaultEditingElementStyle; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { // TODO (#7852): // // - Connect(EndPoint): // - disconnected socket // - Accept(EndPoint): // - disconnected socket // // End*: // - Invalid asyncresult type // - asyncresult from different object // - asyncresult with end already called public class ArgumentValidation { // This type is used to test Socket.Select's argument validation. private sealed class LargeList : IList { private const int MaxSelect = 65536; public int Count { get { return MaxSelect + 1; } } public bool IsFixedSize { get { return true; } } public bool IsReadOnly { get { return true; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return null; } } public object this[int index] { get { return null; } set { } } public int Add(object value) { return -1; } public void Clear() { } public bool Contains(object value) { return false; } public void CopyTo(Array array, int index) { } public IEnumerator GetEnumerator() { return null; } public int IndexOf(object value) { return -1; } public void Insert(int index, object value) { } public void Remove(object value) { } public void RemoveAt(int index) { } } private readonly static byte[] s_buffer = new byte[1]; private readonly static IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) }; private readonly static SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs(); private readonly static Socket s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private readonly static Socket s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); private static void TheAsyncCallback(IAsyncResult ar) { } private static Socket GetSocket(AddressFamily addressFamily = AddressFamily.InterNetwork) { Debug.Assert(addressFamily == AddressFamily.InterNetwork || addressFamily == AddressFamily.InterNetworkV6); return addressFamily == AddressFamily.InterNetwork ? s_ipv4Socket : s_ipv6Socket; } [Fact] public void SetExclusiveAddressUse_BoundSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => { socket.ExclusiveAddressUse = true; }); } } [Fact] public void SetReceiveBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveBufferSize = -1; }); } [Fact] public void SetSendBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendBufferSize = -1; }); } [Fact] public void SetReceiveTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveTimeout = int.MinValue; }); } [Fact] public void SetSendTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendTimeout = int.MinValue; }); } [Fact] public void SetTtl_OutOfRange_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = -1; }); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = 256; }); } [Fact] public void DontFragment_IPv6_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).DontFragment); } [Fact] public void SetDontFragment_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetworkV6).DontFragment = true; }); } [Fact] public void Bind_Throws_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Bind(null)); } [Fact] public void Connect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect(null)); } [Fact] public void Connect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.Connect(new IPEndPoint(IPAddress.Loopback, 1))); } } [Fact] public void Connect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress)null, 1)); } [Fact] public void Connect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, 65536)); } [Fact] public void Connect_IPAddress_InvalidAddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).Connect(IPAddress.IPv6Loopback, 1)); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).Connect(IPAddress.Loopback, 1)); } [Fact] public void Connect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((string)null, 1)); } [Fact] public void Connect_Host_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", 65536)); } [Fact] public void Connect_IPAddresses_NullArray_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress[])null, 1)); } [Fact] public void Connect_IPAddresses_EmptyArray_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().Connect(new IPAddress[0], 1)); } [Fact] public void Connect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, 65536)); } [Fact] public void Accept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().Accept()); } [Fact] public void Accept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.Accept()); } } [Fact] public void Send_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; Assert.Throws<ArgumentException>(() => GetSocket().Send(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void SendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(s_buffer, 0, 0, SocketFlags.None, null)); } [Fact] public void SendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint)); } [Fact] public void SendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, -1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint)); } [Fact] public void Receive_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; Assert.Throws<ArgumentException>(() => GetSocket().Receive(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void ReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(null, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, -1, s_buffer.Length, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, -1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length, 1, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NotBound_Throws_InvalidOperation() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void SetSocketOption_Object_ObjectNull_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, (object)null)); } [Fact] public void SetSocketOption_Linger_NotLingerOption_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new object())); } [Fact] public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1))); Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1))); } [Fact] public void SetSocketOption_IPMulticast_NotIPMulticastOption_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new object())); Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_IPv6Multicast_NotIPMulticastOption_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new object())); Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_Object_InvalidOptionName_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, new object())); } [Fact] public void Select_NullOrEmptyLists_Throws_ArgumentNull() { var emptyList = new List<Socket>(); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, emptyList, -1)); } [Fact] public void Select_LargeList_Throws_ArgumentOutOfRange() { var largeList = new LargeList(); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(largeList, null, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, largeList, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, null, largeList, -1)); } [Fact] public void AcceptAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().AcceptAsync(null)); } [Fact] public void AcceptAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; Assert.Throws<ArgumentException>(() => GetSocket().AcceptAsync(eventArgs)); } [Fact] public void AcceptAsync_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().AcceptAsync(s_eventArgs)); } [Fact] public void AcceptAsync_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.AcceptAsync(s_eventArgs)); } } [Fact] public void ConnectAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(null)); } [Fact] public void ConnectAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; Assert.Throws<ArgumentException>(() => GetSocket().ConnectAsync(eventArgs)); } [Fact] public void ConnectAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(s_eventArgs)); } [Fact] public void ConnectAsync_ListeningSocket_Throws_InvalidOperation() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 1) }; using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.ConnectAsync(eventArgs)); } } [Fact] public void ConnectAsync_AddressFamily_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6) }; Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); } [Fact] public void ConnectAsync_Static_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, null)); } [Fact] public void ConnectAsync_Static_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; Assert.Throws<ArgumentException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs)); } [Fact] public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs)); } [Fact] public void ReceiveAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveAsync(null)); } [Fact] public void ReceiveFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(null)); } [Fact] public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(s_eventArgs)); } [Fact] public void ReceiveFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs)); } [Fact] public void ReceiveMessageFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(null)); } [Fact] public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs)); } [Fact] public void ReceiveMessageFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs)); } [Fact] public void SendAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendAsync(null)); } [Fact] public void SendPacketsAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(null)); } [Fact] public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(s_eventArgs)); } [Fact] public void SendPacketsAsync_NotConnected_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] }; Assert.Throws<NotSupportedException>(() => GetSocket().SendPacketsAsync(eventArgs)); } [Fact] public void SendToAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(null)); } [Fact] public void SendToAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(s_eventArgs)); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void Socket_Connect_DnsEndPoint_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new DnsEndPoint("localhost", 12345))); } } [Fact] public async Task Socket_Connect_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } await accept; } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void Socket_Connect_StringHost_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<PlatformNotSupportedException>(() => s.Connect("localhost", 12345)); } } [Fact] public async Task Socket_Connect_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Fact] public async Task Socket_Connect_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void Socket_Connect_MultipleAddresses_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new[] { IPAddress.Loopback }, 12345)); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void Socket_ConnectAsync_DnsEndPoint_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync(new DnsEndPoint("localhost", 12345)); }); } } [Fact] public async Task Socket_ConnectAsync_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port))); } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void Socket_ConnectAsync_StringHost_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync("localhost", 12345); }); } } [Fact] public async Task Socket_ConnectAsync_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Fact] public async Task Socket_ConnectAsync_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void Socket_ConnectAsync_MultipleAddresses_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync(new[] { IPAddress.Loopback }, 12345); }); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void Connect_ConnectTwice_NotSupported() { using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { // // Connect once, to an invalid address, expecting failure // EndPoint ep = new IPEndPoint(IPAddress.Broadcast, 1234); Assert.ThrowsAny<SocketException>(() => client.Connect(ep)); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.Connect(ep)); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void ConnectAsync_ConnectTwice_NotSupported() { AutoResetEvent completed = new AutoResetEvent(false); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { // // Connect once, to an invalid address, expecting failure // SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 1234); args.Completed += delegate { completed.Set(); }; if (client.ConnectAsync(args)) { Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); } Assert.NotEqual(SocketError.Success, args.SocketError); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.ConnectAsync(args)); } } [Fact] public void BeginAccept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().BeginAccept(TheAsyncCallback, null)); } [Fact] public void BeginAccept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.BeginAccept(TheAsyncCallback, null)); } } [Fact] public void EndAccept_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndAccept(null)); } [Fact] public void BeginConnect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((EndPoint)null, TheAsyncCallback, null)); } [Fact] public void BeginConnect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); } } [Fact] [PlatformSpecific(PlatformID.Windows)] public void BeginConnect_EndPoint_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6), TheAsyncCallback, null)); } [Fact] public void BeginConnect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((string)null, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_Host_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", -1, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", 65536, TheAsyncCallback, null)); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void BeginConnect_Host_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect("localhost", 1, TheAsyncCallback, null)); } } [Fact] public void BeginConnect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress)null, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, -1, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, 65536, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddress_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(IPAddress.IPv6Loopback, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddresses_NullIPAddresses_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress[])null, 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddresses_EmptyIPAddresses_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginConnect(new IPAddress[0], 1, TheAsyncCallback, null)); } [Fact] public void BeginConnect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, -1, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, 65536, TheAsyncCallback, null)); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void BeginConnect_IPAddresses_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null)); } } [Fact] public void EndConnect_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndConnect(null)); } [Fact] public void BeginSend_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginSend_Buffers_EmptyBuffers_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginSend(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void EndSend_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSend(null)); } [Fact] public void BeginSendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); } [Fact] public void BeginSendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(s_buffer, 0, 0, SocketFlags.None, null, TheAsyncCallback, null)); } [Fact] public void BeginSendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); } [Fact] public void BeginSendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, -1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); } [Fact] public void EndSendTo_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSendTo(null)); } [Fact] public void BeginReceive_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void BeginReceive_Buffers_EmptyBuffers_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginReceive(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); } [Fact] public void EndReceive_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceive(null)); } [Fact] public void BeginReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void BeginReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void BeginReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void BeginReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void BeginReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void BeginReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); } [Fact] public void EndReceiveFrom_NullAsyncResult_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveFrom(null, ref endpoint)); } [Fact] public void BeginReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(null, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void BeginReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint remote = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void BeginReceiveMessageFrom_AddressFamily_Throws_Argument() { EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void BeginReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void BeginReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, -1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void BeginReceiveMessageFrom_NotBound_Throws_InvalidOperation() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); } [Fact] public void EndReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; // Behavior difference from Desktop: used to throw ArgumentException. Assert.Throws<ArgumentNullException>(() => GetSocket(AddressFamily.InterNetwork).EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_NullAsyncResult_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void TcpClient_ConnectAsync_StringHost_NotSupportedAfterClientAccess() { using (TcpClient client = new TcpClient()) { var tmp = client.Client; Assert.Throws<PlatformNotSupportedException>(() => { client.ConnectAsync("localhost", 12345); }); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void TcpClient_ConnectAsync_ArrayOfAddresses_NotSupportedAfterClientAccess() { using (TcpClient client = new TcpClient()) { var tmp = client.Client; Assert.Throws<PlatformNotSupportedException>(() => { client.ConnectAsync(new[] { IPAddress.Loopback }, 12345); }); } } } }
// 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 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// SubscriptionsOperations operations. /// </summary> internal partial class SubscriptionsOperations : IServiceOperations<ServiceBusManagementClient>, ISubscriptionsOperations { /// <summary> /// Initializes a new instance of the SubscriptionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SubscriptionsOperations(ServiceBusManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ServiceBusManagementClient /// </summary> public ServiceBusManagementClient Client { get; private set; } /// <summary> /// List all the subscriptions under a specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SBSubscription>>> ListByTopicWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (topicName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "topicName"); } if (topicName != null) { if (topicName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "topicName", 50); } if (topicName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "topicName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("topicName", topicName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByTopic", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{topicName}", System.Uri.EscapeDataString(topicName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SBSubscription>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SBSubscription>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates a topic subscription. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639385.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='subscriptionName'> /// The subscription name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a subscription resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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<SBSubscription>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string subscriptionName, SBSubscription parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (topicName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "topicName"); } if (topicName != null) { if (topicName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "topicName", 50); } if (topicName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "topicName", 1); } } if (subscriptionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionName"); } if (subscriptionName != null) { if (subscriptionName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "subscriptionName", 50); } if (subscriptionName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "subscriptionName", 1); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("topicName", topicName); tracingParameters.Add("subscriptionName", subscriptionName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{topicName}", System.Uri.EscapeDataString(topicName)); _url = _url.Replace("{subscriptionName}", System.Uri.EscapeDataString(subscriptionName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SBSubscription>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SBSubscription>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes a subscription from the specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639381.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='subscriptionName'> /// The subscription name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string subscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (topicName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "topicName"); } if (topicName != null) { if (topicName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "topicName", 50); } if (topicName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "topicName", 1); } } if (subscriptionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionName"); } if (subscriptionName != null) { if (subscriptionName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "subscriptionName", 50); } if (subscriptionName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "subscriptionName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("topicName", topicName); tracingParameters.Add("subscriptionName", subscriptionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{topicName}", System.Uri.EscapeDataString(topicName)); _url = _url.Replace("{subscriptionName}", System.Uri.EscapeDataString(subscriptionName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Returns a subscription description for the specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639402.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='subscriptionName'> /// The subscription name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// 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<SBSubscription>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string subscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (topicName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "topicName"); } if (topicName != null) { if (topicName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "topicName", 50); } if (topicName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "topicName", 1); } } if (subscriptionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionName"); } if (subscriptionName != null) { if (subscriptionName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "subscriptionName", 50); } if (subscriptionName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "subscriptionName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("topicName", topicName); tracingParameters.Add("subscriptionName", subscriptionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{topicName}", System.Uri.EscapeDataString(topicName)); _url = _url.Replace("{subscriptionName}", System.Uri.EscapeDataString(subscriptionName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SBSubscription>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SBSubscription>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List all the subscriptions under a specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SBSubscription>>> ListByTopicNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByTopicNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SBSubscription>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SBSubscription>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class RecordingPositionRequestEncoder { public const ushort BLOCK_LENGTH = 24; public const ushort TEMPLATE_ID = 12; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private RecordingPositionRequestEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public RecordingPositionRequestEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public RecordingPositionRequestEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public RecordingPositionRequestEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public RecordingPositionRequestEncoder ControlSessionId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public RecordingPositionRequestEncoder CorrelationId(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int RecordingIdEncodingOffset() { return 16; } public static int RecordingIdEncodingLength() { return 8; } public static long RecordingIdNullValue() { return -9223372036854775808L; } public static long RecordingIdMinValue() { return -9223372036854775807L; } public static long RecordingIdMaxValue() { return 9223372036854775807L; } public RecordingPositionRequestEncoder RecordingId(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { RecordingPositionRequestDecoder writer = new RecordingPositionRequestDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyInteger { using Microsoft.Rest; using Models; /// <summary> /// IntModel operations. /// </summary> public partial class IntModel : Microsoft.Rest.IServiceOperations<AutoRestIntegerTestService>, IIntModel { /// <summary> /// Initializes a new instance of the IntModel class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public IntModel(AutoRestIntegerTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestIntegerTestService /// </summary> public AutoRestIntegerTestService Client { get; private set; } /// <summary> /// Get null Int value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<int?>> GetNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/null").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<int?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<int?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get invalid Int value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<int?>> GetInvalidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/invalid").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<int?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<int?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<int?>> GetOverflowInt32WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetOverflowInt32", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/overflowint32").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<int?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<int?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<int?>> GetUnderflowInt32WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetUnderflowInt32", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/underflowint32").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<int?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<int?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<long?>> GetOverflowInt64WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetOverflowInt64", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/overflowint64").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<long?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<long?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<long?>> GetUnderflowInt64WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetUnderflowInt64", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/underflowint64").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<long?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<long?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put max int32 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutMax32WithHttpMessagesAsync(int intBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutMax32", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/max/32").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers 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; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put max int64 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutMax64WithHttpMessagesAsync(long intBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutMax64", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/max/64").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers 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; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put min int32 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutMin32WithHttpMessagesAsync(int intBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutMin32", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/min/32").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers 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; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put min int64 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutMin64WithHttpMessagesAsync(long intBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutMin64", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/min/64").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers 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; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get datetime encoded as Unix time value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.DateTime?>> GetUnixTimeWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetUnixTime", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new Microsoft.Rest.Serialization.UnixTimeJsonConverter()); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put datetime encoded as Unix time /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutUnixTimeDateWithHttpMessagesAsync(System.DateTime intBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutUnixTimeDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers 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; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(intBody, new Microsoft.Rest.Serialization.UnixTimeJsonConverter()); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get invalid Unix time value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.DateTime?>> GetInvalidUnixTimeWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetInvalidUnixTime", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/invalidunixtime").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new Microsoft.Rest.Serialization.UnixTimeJsonConverter()); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get null Unix time value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.DateTime?>> GetNullUnixTimeWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNullUnixTime", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/nullunixtime").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new Microsoft.Rest.Serialization.UnixTimeJsonConverter()); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ConvertScalarToVector128Int64Int64() { var test = new ScalarSimdUnaryOpTest__ConvertScalarToVector128Int64Int64(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works test.RunLclVarScenario_UnsafeRead(); // 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 ScalarSimdUnaryOpTest__ConvertScalarToVector128Int64Int64 { private struct TestStruct { public Int64 _fld; public static TestStruct Create() { var testStruct = new TestStruct(); testStruct._fld = TestLibrary.Generator.GetInt64(); return testStruct; } public void RunStructFldScenario(ScalarSimdUnaryOpTest__ConvertScalarToVector128Int64Int64 testClass) { var result = Sse2.X64.ConvertScalarToVector128Int64(_fld); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64 _data; private static Int64 _clsVar; private Int64 _fld; private ScalarSimdUnaryOpTest__DataTable<Int64> _dataTable; static ScalarSimdUnaryOpTest__ConvertScalarToVector128Int64Int64() { _clsVar = TestLibrary.Generator.GetInt64(); } public ScalarSimdUnaryOpTest__ConvertScalarToVector128Int64Int64() { Succeeded = true; _fld = TestLibrary.Generator.GetInt64(); _data = TestLibrary.Generator.GetInt64(); _dataTable = new ScalarSimdUnaryOpTest__DataTable<Int64>(new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.X64.ConvertScalarToVector128Int64( Unsafe.ReadUnaligned<Int64>(ref Unsafe.As<Int64, byte>(ref _data)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_data, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2.X64).GetMethod(nameof(Sse2.X64.ConvertScalarToVector128Int64), new Type[] { typeof(Int64) }) .Invoke(null, new object[] { Unsafe.ReadUnaligned<Int64>(ref Unsafe.As<Int64, byte>(ref _data)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_data, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.X64.ConvertScalarToVector128Int64( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var data = Unsafe.ReadUnaligned<Int64>(ref Unsafe.As<Int64, byte>(ref _data)); var result = Sse2.X64.ConvertScalarToVector128Int64(data); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(data, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ScalarSimdUnaryOpTest__ConvertScalarToVector128Int64Int64(); var result = Sse2.X64.ConvertScalarToVector128Int64(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.X64.ConvertScalarToVector128Int64(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.X64.ConvertScalarToVector128Int64(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Int64 firstOp, void* result, [CallerMemberName] string method = "") { Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(firstOp, outArray, method); } private void ValidateResult(Int64 firstOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (false) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2.X64)}.{nameof(Sse2.X64.ConvertScalarToVector128Int64)}<Int64>(Int64): {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) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // // Extends PermissionSet to allow an associated name and description // namespace System.Security { using System; using System.Security.Util; using System.Security.Permissions; using System.Runtime.Serialization; using System.Diagnostics.Contracts; #if !FEATURE_CAS_POLICY using Microsoft.Win32; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Versioning; using System.Text; #else // FEATURE_CAS_POLICY using System.Threading; #endif // FEATURE_CAS_POLICY [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public sealed class NamedPermissionSet : PermissionSet { #if FEATURE_CAS_POLICY // The name of this PermissionSet private String m_name; // The description of this PermissionSet private String m_description; [OptionalField(VersionAdded = 2)] internal String m_descrResource; internal NamedPermissionSet() : base() { } public NamedPermissionSet( String name ) : base() { CheckName( name ); m_name = name; } public NamedPermissionSet( String name, PermissionState state) : base( state ) { CheckName( name ); m_name = name; } public NamedPermissionSet( String name, PermissionSet permSet ) : base( permSet ) { CheckName( name ); m_name = name; } public NamedPermissionSet( NamedPermissionSet permSet ) : base( permSet ) { m_name = permSet.m_name; m_description = permSet.Description; } internal NamedPermissionSet(SecurityElement permissionSetXml) : base(PermissionState.None) { Contract.Assert(permissionSetXml != null); FromXml(permissionSetXml); } public String Name { get { return m_name; } set { CheckName( value ); m_name = value; } } private static void CheckName( String name ) { if (name == null || name.Equals( "" )) throw new ArgumentException( Environment.GetResourceString( "Argument_NPMSInvalidName" )); Contract.EndContractBlock(); } public String Description { get { if(m_descrResource != null) { m_description = Environment.GetResourceString(m_descrResource); m_descrResource = null; } return m_description; } set { m_description = value; m_descrResource = null; } } public override PermissionSet Copy() { return new NamedPermissionSet( this ); } public NamedPermissionSet Copy( String name ) { NamedPermissionSet set = new NamedPermissionSet( this ); set.Name = name; return set; } public override SecurityElement ToXml() { SecurityElement elem = base.ToXml("System.Security.NamedPermissionSet"); // If you hit this assert then most likely you are trying to change the name of this class. // This is ok as long as you change the hard coded string above and change the assert below. Contract.Assert( this.GetType().FullName.Equals( "System.Security.NamedPermissionSet" ), "Class name changed!" ); if (m_name != null && !m_name.Equals( "" )) { elem.AddAttribute( "Name", SecurityElement.Escape( m_name ) ); } if (Description != null && !Description.Equals( "" )) { elem.AddAttribute( "Description", SecurityElement.Escape( Description ) ); } return elem; } public override void FromXml( SecurityElement et ) { FromXml( et, false, false ); } internal override void FromXml( SecurityElement et, bool allowInternalOnly, bool ignoreTypeLoadFailures ) { if (et == null) throw new ArgumentNullException( "et" ); Contract.EndContractBlock(); String elem; elem = et.Attribute( "Name" ); m_name = elem == null ? null : elem; elem = et.Attribute( "Description" ); m_description = (elem == null ? "" : elem); m_descrResource = null; base.FromXml( et, allowInternalOnly, ignoreTypeLoadFailures ); } internal void FromXmlNameOnly( SecurityElement et ) { // This function gets only the name for the permission set, ignoring all other info. String elem; elem = et.Attribute( "Name" ); m_name = (elem == null ? null : elem); } // NamedPermissionSet Equals should have the exact semantic as PermissionSet. // We explicitly override them here to make sure that no one accidently // changes this. [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals( Object obj ) { return base.Equals( obj ); } [System.Runtime.InteropServices.ComVisible(false)] public override int GetHashCode() { return base.GetHashCode(); } private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } #else // FEATURE_CAS_POLICY internal static PermissionSet GetBuiltInSet(string name) { // Used by PermissionSetAttribute to create one of the built-in, // immutable permission sets. if (name == null) return null; else if (name.Equals("FullTrust")) return CreateFullTrustSet(); else if (name.Equals("Nothing")) return CreateNothingSet(); else if (name.Equals("Execution")) return CreateExecutionSet(); else if (name.Equals("SkipVerification")) return CreateSkipVerificationSet(); else if (name.Equals("Internet")) return CreateInternetSet(); else return null; } private static PermissionSet CreateFullTrustSet() { return new PermissionSet(PermissionState.Unrestricted); } private static PermissionSet CreateNothingSet() { return new PermissionSet(PermissionState.None); } private static PermissionSet CreateExecutionSet() { PermissionSet permSet = new PermissionSet(PermissionState.None); #pragma warning disable 618 permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); #pragma warning restore 618 return permSet; } private static PermissionSet CreateSkipVerificationSet() { PermissionSet permSet = new PermissionSet(PermissionState.None); #pragma warning disable 618 permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.SkipVerification)); #pragma warning restore 618 return permSet; } private static PermissionSet CreateInternetSet() { PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Open)); #pragma warning disable 618 permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); #pragma warning restore 618 permSet.AddPermission(new UIPermission(UIPermissionWindow.SafeTopLevelWindows, UIPermissionClipboard.OwnClipboard)); return permSet; } #endif // !FEATURE_CAS_POLICY } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics.Contracts; namespace System.Net.Http.Headers { public class MediaTypeHeaderValue : ICloneable { private const string charSet = "charset"; private ICollection<NameValueHeaderValue> _parameters; private string _mediaType; public string CharSet { get { NameValueHeaderValue charSetParameter = NameValueHeaderValue.Find(_parameters, charSet); if (charSetParameter != null) { return charSetParameter.Value; } return null; } set { // We don't prevent a user from setting whitespace-only charsets. Like we can't prevent a user from // setting a non-existing charset. NameValueHeaderValue charSetParameter = NameValueHeaderValue.Find(_parameters, charSet); if (string.IsNullOrEmpty(value)) { // Remove charset parameter if (charSetParameter != null) { _parameters.Remove(charSetParameter); } } else { if (charSetParameter != null) { charSetParameter.Value = value; } else { Parameters.Add(new NameValueHeaderValue(charSet, value)); } } } } public ICollection<NameValueHeaderValue> Parameters { get { if (_parameters == null) { _parameters = new ObjectCollection<NameValueHeaderValue>(); } return _parameters; } } public string MediaType { get { return _mediaType; } set { CheckMediaTypeFormat(value, "value"); _mediaType = value; } } internal MediaTypeHeaderValue() { // Used by the parser to create a new instance of this type. } protected MediaTypeHeaderValue(MediaTypeHeaderValue source) { Contract.Requires(source != null); _mediaType = source._mediaType; if (source._parameters != null) { foreach (var parameter in source._parameters) { this.Parameters.Add((NameValueHeaderValue)((ICloneable)parameter).Clone()); } } } public MediaTypeHeaderValue(string mediaType) { CheckMediaTypeFormat(mediaType, "mediaType"); _mediaType = mediaType; } public override string ToString() { return _mediaType + NameValueHeaderValue.ToString(_parameters, ';', true); } public override bool Equals(object obj) { MediaTypeHeaderValue other = obj as MediaTypeHeaderValue; if (other == null) { return false; } return (string.Compare(_mediaType, other._mediaType, StringComparison.OrdinalIgnoreCase) == 0) && HeaderUtilities.AreEqualCollections(_parameters, other._parameters); } public override int GetHashCode() { // The media-type string is case-insensitive. return _mediaType.ToLowerInvariant().GetHashCode() ^ NameValueHeaderValue.GetHashCode(_parameters); } public static MediaTypeHeaderValue Parse(string input) { int index = 0; return (MediaTypeHeaderValue)MediaTypeHeaderParser.SingleValueParser.ParseValue(input, null, ref index); } public static bool TryParse(string input, out MediaTypeHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (MediaTypeHeaderParser.SingleValueParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (MediaTypeHeaderValue)output; return true; } return false; } internal static int GetMediaTypeLength(string input, int startIndex, Func<MediaTypeHeaderValue> mediaTypeCreator, out MediaTypeHeaderValue parsedValue) { Contract.Requires(mediaTypeCreator != null); Contract.Requires(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Caller must remove leading whitespaces. If not, we'll return 0. string mediaType = null; int mediaTypeLength = MediaTypeHeaderValue.GetMediaTypeExpressionLength(input, startIndex, out mediaType); if (mediaTypeLength == 0) { return 0; } int current = startIndex + mediaTypeLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); MediaTypeHeaderValue mediaTypeHeader = null; // If we're not done and we have a parameter delimiter, then we have a list of parameters. if ((current < input.Length) && (input[current] == ';')) { mediaTypeHeader = mediaTypeCreator(); mediaTypeHeader._mediaType = mediaType; current++; // skip delimiter. int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';', mediaTypeHeader.Parameters); if (parameterLength == 0) { return 0; } parsedValue = mediaTypeHeader; return current + parameterLength - startIndex; } // We have a media type without parameters. mediaTypeHeader = mediaTypeCreator(); mediaTypeHeader._mediaType = mediaType; parsedValue = mediaTypeHeader; return current - startIndex; } private static int GetMediaTypeExpressionLength(string input, int startIndex, out string mediaType) { Contract.Requires((input != null) && (input.Length > 0) && (startIndex < input.Length)); // This method just parses the "type/subtype" string, it does not parse parameters. mediaType = null; // Parse the type, i.e. <type> in media type string "<type>/<subtype>; param1=value1; param2=value2" int typeLength = HttpRuleParser.GetTokenLength(input, startIndex); if (typeLength == 0) { return 0; } int current = startIndex + typeLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Parse the separator between type and subtype if ((current >= input.Length) || (input[current] != '/')) { return 0; } current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Parse the subtype, i.e. <subtype> in media type string "<type>/<subtype>; param1=value1; param2=value2" int subtypeLength = HttpRuleParser.GetTokenLength(input, current); if (subtypeLength == 0) { return 0; } // If there are no whitespaces between <type> and <subtype> in <type>/<subtype> get the media type using // one Substring call. Otherwise get substrings for <type> and <subtype> and combine them. int mediatTypeLength = current + subtypeLength - startIndex; if (typeLength + subtypeLength + 1 == mediatTypeLength) { mediaType = input.Substring(startIndex, mediatTypeLength); } else { mediaType = input.Substring(startIndex, typeLength) + "/" + input.Substring(current, subtypeLength); } return mediatTypeLength; } private static void CheckMediaTypeFormat(string mediaType, string parameterName) { if (string.IsNullOrEmpty(mediaType)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } // When adding values using strongly typed objects, no leading/trailing LWS (whitespaces) are allowed. // Also no LWS between type and subtype are allowed. string tempMediaType; int mediaTypeLength = GetMediaTypeExpressionLength(mediaType, 0, out tempMediaType); if ((mediaTypeLength == 0) || (tempMediaType.Length != mediaType.Length)) { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, mediaType)); } } // Implement ICloneable explicitly to allow derived types to "override" the implementation. object ICloneable.Clone() { return new MediaTypeHeaderValue(this); } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Diagnostics; using System.Dynamic; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using System.Threading; using System.Collections.Generic; namespace IronPython.Runtime.Binding { using Ast = Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; partial class MetaUserObject : MetaPythonObject, IPythonGetable { #region IPythonGetable Members public DynamicMetaObject GetMember(PythonGetMemberBinder/*!*/ member, DynamicMetaObject/*!*/ codeContext) { return GetMemberWorker(member, codeContext); } #endregion #region MetaObject Overrides public override DynamicMetaObject/*!*/ BindGetMember(GetMemberBinder/*!*/ action) { return GetMemberWorker(action, PythonContext.GetCodeContextMO(action)); } public override DynamicMetaObject/*!*/ BindSetMember(SetMemberBinder/*!*/ action, DynamicMetaObject/*!*/ value) { return new MetaSetBinderHelper(this, value, action).Bind(action.Name); } public override DynamicMetaObject/*!*/ BindDeleteMember(DeleteMemberBinder/*!*/ action) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "DeleteMember"); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "DeleteMember"); return MakeDeleteMemberRule( new DeleteBindingInfo( action, new DynamicMetaObject[] { this }, new ConditionalBuilder(action), BindingHelpers.GetValidationInfo(this, PythonType) ) ); } #endregion #region Get Member Helpers /// <summary> /// Provides the lookup logic for resolving a Python object. Subclasses /// provide the actual logic for producing the binding result. Currently /// there are two forms of the binding result: one is the DynamicMetaObject /// form used for non-optimized bindings. The other is the Func of CallSite, /// object, CodeContext, object form which is used for fast binding and /// pre-compiled rules. /// </summary> internal abstract class GetOrInvokeBinderHelper<TResult> { protected readonly IPythonObject _value; protected bool _extensionMethodRestriction; public GetOrInvokeBinderHelper(IPythonObject value) { _value = value; } public TResult Bind(CodeContext context, string name) { IPythonObject sdo = Value; PythonTypeSlot foundSlot; if (TryGetGetAttribute(context, sdo.PythonType, out foundSlot)) { return BindGetAttribute(foundSlot); } // otherwise look the object according to Python rules: // 1. 1st search the MRO of the type, and if it's there, and it's a get/set descriptor, // return that value. // 2. Look in the instance dictionary. If it's there return that value, otherwise return // a value found during the MRO search. If no value was found during the MRO search then // raise an exception. // 3. fall back to __getattr__ if defined. // // Ultimately we cache the result of the MRO search based upon the type version. If we have // a get/set descriptor we'll only ever use that directly. Otherwise if we have a get descriptor // we'll first check the dictionary and then invoke the get descriptor. If we have no descriptor // at all we'll just check the dictionary. If both lookups fail we'll raise an exception. bool isOldStyle, systemTypeResolution, extensionMethodResolution; foundSlot = FindSlot(context, name, sdo, out isOldStyle, out systemTypeResolution, out extensionMethodResolution); _extensionMethodRestriction = extensionMethodResolution; if (!isOldStyle || foundSlot is ReflectedSlotProperty) { if (sdo.PythonType.HasDictionary && (foundSlot == null || !foundSlot.IsSetDescriptor(context, sdo.PythonType))) { MakeDictionaryAccess(); } if (foundSlot != null) { MakeSlotAccess(foundSlot, systemTypeResolution); } } else { MakeOldStyleAccess(); } if (!IsFinal) { // fall back to __getattr__ if it's defined. // TODO: For InvokeMember we should probably do a fallback w/ an error suggestion PythonTypeSlot getattr; if (Value.PythonType.TryResolveSlot(context, "__getattr__", out getattr)) { MakeGetAttrAccess(getattr); } MakeTypeError(); } return FinishRule(); } protected abstract void MakeTypeError(); protected abstract void MakeGetAttrAccess(PythonTypeSlot getattr); protected abstract bool IsFinal { get; } protected abstract void MakeSlotAccess(PythonTypeSlot foundSlot, bool systemTypeResolution); protected abstract TResult BindGetAttribute(PythonTypeSlot foundSlot); protected abstract TResult FinishRule(); protected abstract void MakeDictionaryAccess(); protected abstract void MakeOldStyleAccess(); public IPythonObject Value { get { return _value; } } } /// <summary> /// GetBinder which produces a DynamicMetaObject. This binder always /// successfully produces a DynamicMetaObject which can perform the requested get. /// </summary> abstract class MetaGetBinderHelper : GetOrInvokeBinderHelper<DynamicMetaObject> { private readonly DynamicMetaObject _self; private readonly GetBindingInfo _bindingInfo; protected readonly MetaUserObject _target; private readonly DynamicMetaObjectBinder _binder; protected readonly DynamicMetaObject _codeContext; private string _resolution = "GetMember "; public MetaGetBinderHelper(MetaUserObject target, DynamicMetaObjectBinder binder, DynamicMetaObject codeContext) : base(target.Value) { _target = target; _self = _target.Restrict(Value.GetType()); _binder = binder; _codeContext = codeContext; _bindingInfo = new GetBindingInfo( _binder, new DynamicMetaObject[] { _target }, Ast.Variable(Expression.Type, "self"), Ast.Variable(typeof(object), "lookupRes"), new ConditionalBuilder(_binder), BindingHelpers.GetValidationInfo(_self, Value.PythonType) ); } /// <summary> /// Makes a rule which calls a user-defined __getattribute__ function and falls back to __getattr__ if that /// raises an AttributeError. /// /// slot is the __getattribute__ method to be called. /// </summary> private DynamicMetaObject/*!*/ MakeGetAttributeRule(GetBindingInfo/*!*/ info, IPythonObject/*!*/ obj, PythonTypeSlot/*!*/ slot, DynamicMetaObject codeContext) { // if the type implements IDynamicMetaObjectProvider and we picked up it's __getattribute__ then we want to just // dispatch to the base meta object (or to the default binder). an example of this is: // // class mc(type): // def __getattr__(self, name): // return 42 // // class nc_ga(object): // __metaclass__ = mc // // a = nc_ga.x # here we want to dispatch to the type's rule, not call __getattribute__ directly. CodeContext context = PythonContext.GetPythonContext(info.Action).SharedContext; Type finalType = obj.PythonType.FinalSystemType; if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(finalType)) { PythonTypeSlot baseSlot; if (TryGetGetAttribute(context, DynamicHelpers.GetPythonTypeFromType(finalType), out baseSlot) && baseSlot == slot) { return FallbackError(); } } // otherwise generate code into a helper function. This will do the slot lookup and exception // handling for both __getattribute__ as well as __getattr__ if it exists. PythonTypeSlot getattr; obj.PythonType.TryResolveSlot(context, "__getattr__", out getattr); DynamicMetaObject self = _target.Restrict(Value.GetType()); string methodName = BindingHelpers.IsNoThrow(info.Action) ? "GetAttributeNoThrow" : "GetAttribute"; return BindingHelpers.AddDynamicTestAndDefer( info.Action, new DynamicMetaObject( Ast.Call( typeof(UserTypeOps).GetMethod(methodName), Ast.Constant(PythonContext.GetPythonContext(info.Action).SharedContext), info.Args[0].Expression, Ast.Constant(GetGetMemberName(info.Action)), Ast.Constant(slot, typeof(PythonTypeSlot)), Ast.Constant(getattr, typeof(PythonTypeSlot)), Ast.Constant(new SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, string, object>>>()) ), self.Restrictions ), info.Args, info.Validation ); } protected abstract DynamicMetaObject FallbackError(); protected abstract DynamicMetaObject Fallback(); protected virtual Expression Invoke(Expression res) { return Invoke(new DynamicMetaObject(res, BindingRestrictions.Empty)).Expression; } protected virtual DynamicMetaObject Invoke(DynamicMetaObject res) { return res; } protected override DynamicMetaObject BindGetAttribute(PythonTypeSlot foundSlot) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "User GetAttribute"); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "User GetAttribute"); return Invoke(MakeGetAttributeRule(_bindingInfo, Value, foundSlot, _codeContext)); } protected override void MakeGetAttrAccess(PythonTypeSlot getattr) { _resolution += "GetAttr "; MakeGetAttrRule(_bindingInfo, GetWeakSlot(getattr), _codeContext); } protected override void MakeTypeError() { _bindingInfo.Body.FinishCondition(FallbackError().Expression); } protected override bool IsFinal { get { return _bindingInfo.Body.IsFinal; } } protected override DynamicMetaObject FinishRule() { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, _resolution); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "UserGet"); DynamicMetaObject res = _bindingInfo.Body.GetMetaObject(_target); res = new DynamicMetaObject( Ast.Block( new ParameterExpression[] { _bindingInfo.Self, _bindingInfo.Result }, Ast.Assign(_bindingInfo.Self, _self.Expression), res.Expression ), _self.Restrictions.Merge(res.Restrictions) ); if (_extensionMethodRestriction) { res = new DynamicMetaObject( res.Expression, res.Restrictions.Merge(((CodeContext)_codeContext.Value).ModuleContext.ExtensionMethods.GetRestriction(_codeContext.Expression)) ); } return BindingHelpers.AddDynamicTestAndDefer( _binder, res, new DynamicMetaObject[] { _target }, _bindingInfo.Validation ); } private void MakeGetAttrRule(GetBindingInfo/*!*/ info, Expression/*!*/ getattr, DynamicMetaObject codeContext) { info.Body.AddCondition( MakeGetAttrTestAndGet(info, getattr), Invoke(MakeGetAttrCall(info, codeContext)) ); } private Expression/*!*/ MakeGetAttrCall(GetBindingInfo/*!*/ info, DynamicMetaObject codeContext) { Expression call = Ast.Dynamic( PythonContext.GetPythonContext(info.Action).InvokeOne, typeof(object), PythonContext.GetCodeContext(info.Action), info.Result, Ast.Constant(GetGetMemberName(info.Action)) ); call = MaybeMakeNoThrow(info, call); return call; } private Expression/*!*/ MaybeMakeNoThrow(GetBindingInfo/*!*/ info, Expression/*!*/ expr) { if (BindingHelpers.IsNoThrow(info.Action)) { DynamicMetaObject fallback = FallbackError(); ParameterExpression tmp = Ast.Variable(typeof(object), "getAttrRes"); expr = Ast.Block( new ParameterExpression[] { tmp }, Ast.Block( AstUtils.Try( Ast.Assign(tmp, AstUtils.Convert(expr, typeof(object))) ).Catch( typeof(MissingMemberException), Ast.Assign(tmp, AstUtils.Convert(fallback.Expression, typeof(object))) ), tmp ) ); } return expr; } protected override void MakeSlotAccess(PythonTypeSlot foundSlot, bool systemTypeResolution) { _resolution += CompilerHelpers.GetType(foundSlot) + " "; if (systemTypeResolution) { _bindingInfo.Body.FinishCondition(Fallback().Expression); } else { MakeSlotAccess(foundSlot); } } private void MakeSlotAccess(PythonTypeSlot dts) { ReflectedSlotProperty rsp = dts as ReflectedSlotProperty; if (rsp != null) { // we need to fall back to __getattr__ if the value is not defined, so call it and check the result. _bindingInfo.Body.AddCondition( Ast.NotEqual( Ast.Assign( _bindingInfo.Result, Ast.ArrayAccess( GetSlots(_target), Ast.Constant(rsp.Index) ) ), Ast.Field(null, typeof(Uninitialized).GetField("Instance")) ), Invoke(_bindingInfo.Result) ); return; } PythonTypeUserDescriptorSlot slot = dts as PythonTypeUserDescriptorSlot; if (slot != null) { _bindingInfo.Body.FinishCondition( Ast.Call( typeof(PythonOps).GetMethod("GetUserSlotValue"), Ast.Constant(PythonContext.GetPythonContext(_bindingInfo.Action).SharedContext), Ast.Convert(AstUtils.WeakConstant(slot), typeof(PythonTypeUserDescriptorSlot)), _target.Expression, Ast.Property( Ast.Convert( _bindingInfo.Self, typeof(IPythonObject)), PythonTypeInfo._IPythonObject.PythonType ) ) ); } // users can subclass PythonProperty so check the type explicitly // and only in-line the ones we fully understand. if (dts.GetType() == typeof(PythonProperty)) { // properties are mutable so we generate code to get the value rather // than burning it into the rule. Expression getter = Ast.Property( Ast.Convert(AstUtils.WeakConstant(dts), typeof(PythonProperty)), "fget" ); ParameterExpression tmpGetter = Ast.Variable(typeof(object), "tmpGet"); _bindingInfo.Body.AddVariable(tmpGetter); _bindingInfo.Body.FinishCondition( Ast.Block( Ast.Assign(tmpGetter, getter), Ast.Condition( Ast.NotEqual( tmpGetter, Ast.Constant(null) ), Invoke( Ast.Dynamic( PythonContext.GetPythonContext(_bindingInfo.Action).InvokeOne, typeof(object), Ast.Constant(PythonContext.GetPythonContext(_bindingInfo.Action).SharedContext), tmpGetter, _bindingInfo.Self ) ), _binder.Throw(Ast.Call(typeof(PythonOps).GetMethod("UnreadableProperty")), typeof(object)) ) ) ); return; } Expression tryGet = Ast.Call( PythonTypeInfo._PythonOps.SlotTryGetBoundValue, Ast.Constant(PythonContext.GetPythonContext(_bindingInfo.Action).SharedContext), Ast.Convert(AstUtils.WeakConstant(dts), typeof(PythonTypeSlot)), AstUtils.Convert(_bindingInfo.Self, typeof(object)), Ast.Property( Ast.Convert( _bindingInfo.Self, typeof(IPythonObject)), PythonTypeInfo._IPythonObject.PythonType ), _bindingInfo.Result ); Expression value = Invoke(_bindingInfo.Result); if (dts.GetAlwaysSucceeds) { _bindingInfo.Body.FinishCondition( Ast.Block(tryGet, value) ); } else { _bindingInfo.Body.AddCondition( tryGet, value ); } } protected override void MakeDictionaryAccess() { _resolution += "Dictionary "; FieldInfo fi = _target.LimitType.GetField(NewTypeMaker.DictFieldName); Expression dict; if (fi != null) { dict = Ast.Field( Ast.Convert(_bindingInfo.Self, _target.LimitType), fi ); } else { dict = Ast.Property( Ast.Convert(_bindingInfo.Self, typeof(IPythonObject)), PythonTypeInfo._IPythonObject.Dict ); } var instanceNames = Value.PythonType.GetOptimizedInstanceNames(); int instanceIndex; if (instanceNames != null && (instanceIndex = instanceNames.IndexOf(GetGetMemberName(_bindingInfo.Action))) != -1) { // optimized instance value access _bindingInfo.Body.AddCondition( Ast.Call( typeof(UserTypeOps).GetMethod("TryGetDictionaryValue"), dict, AstUtils.Constant(GetGetMemberName(_bindingInfo.Action)), Ast.Constant(Value.PythonType.GetOptimizedInstanceVersion()), Ast.Constant(instanceIndex), _bindingInfo.Result ), Invoke(new DynamicMetaObject(_bindingInfo.Result, BindingRestrictions.Empty)).Expression ); } else { _bindingInfo.Body.AddCondition( Ast.AndAlso( Ast.NotEqual( dict, Ast.Constant(null) ), Ast.Call( dict, PythonTypeInfo._PythonDictionary.TryGetvalue, AstUtils.Constant(GetGetMemberName(_bindingInfo.Action)), _bindingInfo.Result ) ), Invoke(new DynamicMetaObject(_bindingInfo.Result, BindingRestrictions.Empty)).Expression ); } } /// <summary> /// Checks a range of the MRO to perform old-style class lookups if any old-style classes /// are present. We will call this twice to produce a search before a slot and after /// a slot. /// </summary> protected override void MakeOldStyleAccess() { _resolution += "MixedOldStyle "; _bindingInfo.Body.AddCondition( Ast.Call( typeof(UserTypeOps).GetMethod("TryGetMixedNewStyleOldStyleSlot"), Ast.Constant(PythonContext.GetPythonContext(_bindingInfo.Action).SharedContext), AstUtils.Convert(_bindingInfo.Self, typeof(object)), AstUtils.Constant(GetGetMemberName(_bindingInfo.Action)), _bindingInfo.Result ), Invoke(_bindingInfo.Result) ); } public Expression Expression { get { return _target.Expression; } } } internal class FastGetBinderHelper : GetOrInvokeBinderHelper<FastGetBase> { private readonly int _version; private readonly PythonGetMemberBinder/*!*/ _binder; private readonly CallSite<Func<CallSite, object, CodeContext, object>> _site; private readonly CodeContext _context; private bool _dictAccess, _noOptimizedForm; private PythonTypeSlot _slot; private PythonTypeSlot _getattrSlot; public FastGetBinderHelper(CodeContext/*!*/ context, CallSite<Func<CallSite, object, CodeContext, object>>/*!*/ site, IPythonObject/*!*/ value, PythonGetMemberBinder/*!*/ binder) : base(value) { Assert.NotNull(value, binder, context, site); _version = value.PythonType.Version; _binder = binder; _site = site; _context = context; } protected override void MakeTypeError() { } protected override bool IsFinal { get { return _slot != null && _slot.GetAlwaysSucceeds; } } protected override void MakeSlotAccess(PythonTypeSlot foundSlot, bool systemTypeResolution) { if (systemTypeResolution) { if (!_binder.Context.Binder.TryResolveSlot(_context, this.Value.PythonType, this.Value.PythonType, _binder.Name, out foundSlot)) { Debug.Assert(false); } } _slot = foundSlot; } public FastBindResult<Func<CallSite, object, CodeContext, object>> GetBinding(CodeContext context, string name) { var cachedGets = GetCachedGets(); var key = CachedGetKey.Make(name, context.ModuleContext.ExtensionMethods); FastGetBase dlg; lock (cachedGets) { if (!cachedGets.TryGetValue(key, out dlg) || !dlg.IsValid(Value.PythonType)) { var binding = Bind(context, name); if (binding != null) { dlg = binding; if (dlg.ShouldCache) { cachedGets[key] = dlg; } } } } if (dlg != null && dlg.ShouldUseNonOptimizedSite) { return new FastBindResult<Func<CallSite, object, CodeContext, object>>(dlg._func, dlg.ShouldCache); } return new FastBindResult<Func<CallSite, object, CodeContext, object>>(); } private Dictionary<CachedGetKey, FastGetBase> GetCachedGets() { if (_binder.IsNoThrow) { var cachedGets = Value.PythonType._cachedTryGets; if (cachedGets == null) { Interlocked.CompareExchange( ref Value.PythonType._cachedTryGets, new Dictionary<CachedGetKey, FastGetBase>(), null); cachedGets = Value.PythonType._cachedTryGets; } return cachedGets; } else { var cachedGets = Value.PythonType._cachedGets; if (cachedGets == null) { Interlocked.CompareExchange( ref Value.PythonType._cachedGets, new Dictionary<CachedGetKey, FastGetBase>(), null); cachedGets = Value.PythonType._cachedGets; } return cachedGets; } } protected override FastGetBase FinishRule() { if (_noOptimizedForm) { return null; } GetMemberDelegates func; ReflectedSlotProperty rsp = _slot as ReflectedSlotProperty; if (rsp != null) { Debug.Assert(!_dictAccess); // properties for __slots__ are get/set descriptors so we should never access the dictionary. func = new GetMemberDelegates(OptimizedGetKind.PropertySlot, Value.PythonType, _binder, _binder.Name, _version, _slot, _getattrSlot, rsp.Getter, FallbackError(), _context.ModuleContext.ExtensionMethods); } else if (_dictAccess) { if (_slot is PythonTypeUserDescriptorSlot) { func = new GetMemberDelegates(OptimizedGetKind.UserSlotDict, Value.PythonType, _binder, _binder.Name, _version, _slot, _getattrSlot, null, FallbackError(), _context.ModuleContext.ExtensionMethods); } else { func = new GetMemberDelegates(OptimizedGetKind.SlotDict, Value.PythonType, _binder, _binder.Name, _version, _slot, _getattrSlot, null, FallbackError(), _context.ModuleContext.ExtensionMethods); } } else { if (_slot is PythonTypeUserDescriptorSlot) { func = new GetMemberDelegates(OptimizedGetKind.UserSlotOnly, Value.PythonType, _binder, _binder.Name, _version, _slot, _getattrSlot, null, FallbackError(), _context.ModuleContext.ExtensionMethods); } else { func = new GetMemberDelegates(OptimizedGetKind.SlotOnly, Value.PythonType, _binder, _binder.Name, _version, _slot, _getattrSlot, null, FallbackError(), _context.ModuleContext.ExtensionMethods); } } return func; } private Func<CallSite, object, CodeContext, object> FallbackError() { Type finalType = Value.PythonType.FinalSystemType; if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(finalType)) { return ((IFastGettable)Value).MakeGetBinding(_site, _binder, _context, _binder.Name); } if (_binder.IsNoThrow) { return (site, self, context) => OperationFailed.Value; } string name = _binder.Name; return (site, self, context) => { throw PythonOps.AttributeErrorForMissingAttribute(((IPythonObject)self).PythonType.Name, name); }; } protected override void MakeDictionaryAccess() { _dictAccess = true; } protected override FastGetBase BindGetAttribute(PythonTypeSlot foundSlot) { Type finalType = Value.PythonType.FinalSystemType; if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(finalType)) { Debug.Assert(Value is IFastGettable); PythonTypeSlot baseSlot; if (TryGetGetAttribute(_context, DynamicHelpers.GetPythonTypeFromType(finalType), out baseSlot) && baseSlot == foundSlot) { return new ChainedUserGet(_binder, _version, FallbackError()); } } PythonTypeSlot getattr; Value.PythonType.TryResolveSlot(_context, "__getattr__", out getattr); return new GetAttributeDelegates(_binder, _binder.Name, _version, foundSlot, getattr); } protected override void MakeGetAttrAccess(PythonTypeSlot getattr) { _getattrSlot = getattr; } protected override void MakeOldStyleAccess() { _noOptimizedForm = true; } } class GetBinderHelper : MetaGetBinderHelper { private readonly DynamicMetaObjectBinder _binder; public GetBinderHelper(MetaUserObject target, DynamicMetaObjectBinder binder, DynamicMetaObject codeContext) : base(target, binder, codeContext) { _binder = binder; } protected override DynamicMetaObject Fallback() { return GetMemberFallback(_target, _binder, _codeContext); } protected override DynamicMetaObject FallbackError() { return _target.FallbackGetError(_binder, _codeContext); } } class InvokeBinderHelper : MetaGetBinderHelper { private readonly InvokeMemberBinder _binder; private readonly DynamicMetaObject[] _args; public InvokeBinderHelper(MetaUserObject target, InvokeMemberBinder binder, DynamicMetaObject[] args, DynamicMetaObject codeContext) : base(target, binder, codeContext) { _binder = binder; _args = args; } protected override DynamicMetaObject Fallback() { return _binder.FallbackInvokeMember(_target, _args); } protected override DynamicMetaObject FallbackError() { if (_target._baseMetaObject != null) { return _target._baseMetaObject.BindInvokeMember(_binder, _args); } return Fallback(); } protected override DynamicMetaObject Invoke(DynamicMetaObject res) { return _binder.FallbackInvoke(res, _args, null); } } private DynamicMetaObject GetMemberWorker(DynamicMetaObjectBinder/*!*/ member, DynamicMetaObject codeContext) { return new GetBinderHelper(this, member, codeContext).Bind((CodeContext)codeContext.Value, GetGetMemberName(member)); } /// <summary> /// Checks to see if this type has __getattribute__ that overrides all other attribute lookup. /// /// This is more complex then it needs to be. The problem is that when we have a /// mixed new-style/old-style class we have a weird __getattribute__ defined. When /// we always dispatch through rules instead of PythonTypes it should be easy to remove /// this. /// </summary> private static bool TryGetGetAttribute(CodeContext/*!*/ context, PythonType/*!*/ type, out PythonTypeSlot dts) { if (type.TryResolveSlot(context, "__getattribute__", out dts)) { BuiltinMethodDescriptor bmd = dts as BuiltinMethodDescriptor; if (bmd == null || bmd.DeclaringType != typeof(object) || bmd.Template.Targets.Count != 1 || bmd.Template.Targets[0].DeclaringType != typeof(ObjectOps) || bmd.Template.Targets[0].Name != "__getattribute__") { return dts != null; } } return false; } private static MethodCallExpression/*!*/ MakeGetAttrTestAndGet(GetBindingInfo/*!*/ info, Expression/*!*/ getattr) { return Ast.Call( PythonTypeInfo._PythonOps.SlotTryGetBoundValue, AstUtils.Constant(PythonContext.GetPythonContext(info.Action).SharedContext), AstUtils.Convert(getattr, typeof(PythonTypeSlot)), AstUtils.Convert(info.Self, typeof(object)), Ast.Convert( Ast.Property( Ast.Convert( info.Self, typeof(IPythonObject)), PythonTypeInfo._IPythonObject.PythonType ), typeof(PythonType) ), info.Result ); } private static Expression/*!*/ GetWeakSlot(PythonTypeSlot slot) { return AstUtils.Convert(AstUtils.WeakConstant(slot), typeof(PythonTypeSlot)); } private static Expression/*!*/ MakeTypeError(DynamicMetaObjectBinder binder, string/*!*/ name, PythonType/*!*/ type) { return binder.Throw( Ast.Call( typeof(PythonOps).GetMethod("AttributeErrorForMissingAttribute", new Type[] { typeof(string), typeof(string) }), AstUtils.Constant(type.Name), AstUtils.Constant(name) ), typeof(object) ); } #endregion #region Set Member Helpers internal abstract class SetBinderHelper<TResult> { private readonly IPythonObject/*!*/ _instance; private readonly object _value; protected readonly CodeContext/*!*/ _context; public SetBinderHelper(CodeContext/*!*/ context, IPythonObject/*!*/ instance, object value) { Assert.NotNull(context, instance); _instance = instance; _value = value; _context = context; } public TResult Bind(string name) { bool bound = false; // call __setattr__ if it exists PythonTypeSlot dts; if (_instance.PythonType.TryResolveSlot(_context, "__setattr__", out dts) && !IsStandardObjectMethod(dts)) { // skip the fake __setattr__ on mixed new-style/old-style types if (dts != null) { MakeSetAttrTarget(dts); bound = true; } } if (!bound) { // then see if we have a set descriptor bool isOldStyle,systemTypeResolution, extensionMethodResolution; dts = FindSlot(_context, name, _instance, out isOldStyle, out systemTypeResolution, out extensionMethodResolution); ReflectedSlotProperty rsp = dts as ReflectedSlotProperty; if (rsp != null) { MakeSlotsSetTarget(rsp); bound = true; } else if (dts != null && dts.IsSetDescriptor(_context, _instance.PythonType)) { MakeSlotSetOrFallback(dts, systemTypeResolution); bound = systemTypeResolution || dts.GetType() == typeof(PythonProperty); // the only slot we currently optimize in MakeSlotSet } } if (!bound) { // finally if we have a dictionary set the value there. if (_instance.PythonType.HasDictionary) { MakeDictionarySetTarget(); } else { MakeFallback(); } } return Finish(); } public IPythonObject Instance { get { return _instance; } } public object Value { get { return _value; } } protected abstract TResult Finish(); protected abstract void MakeSetAttrTarget(PythonTypeSlot dts); protected abstract void MakeSlotsSetTarget(ReflectedSlotProperty prop); protected abstract void MakeSlotSetOrFallback(PythonTypeSlot dts, bool systemTypeResolution); protected abstract void MakeDictionarySetTarget(); protected abstract void MakeFallback(); } internal class FastSetBinderHelper<TValue> : SetBinderHelper<SetMemberDelegates<TValue>> { private readonly PythonSetMemberBinder _binder; private readonly int _version; private PythonTypeSlot _setattrSlot; private ReflectedSlotProperty _slotProp; private bool _unsupported, _dictSet; public FastSetBinderHelper(CodeContext context, IPythonObject self, object value, PythonSetMemberBinder binder) : base(context, self, value) { _binder = binder; _version = self.PythonType.Version; } protected override SetMemberDelegates<TValue> Finish() { if (_unsupported) { return new SetMemberDelegates<TValue>(_context, Instance.PythonType, OptimizedSetKind.None, _binder.Name, _version, _setattrSlot, null); } else if (_setattrSlot != null) { return new SetMemberDelegates<TValue>(_context, Instance.PythonType, OptimizedSetKind.SetAttr, _binder.Name, _version, _setattrSlot, null); } else if (_slotProp != null) { return new SetMemberDelegates<TValue>(_context, Instance.PythonType, OptimizedSetKind.UserSlot, _binder.Name, _version, null, _slotProp.Setter); } else if(_dictSet) { return new SetMemberDelegates<TValue>(_context, Instance.PythonType, OptimizedSetKind.SetDict, _binder.Name, _version, null, null); } else { return new SetMemberDelegates<TValue>(_context, Instance.PythonType, OptimizedSetKind.Error, _binder.Name, _version, null, null); } } public FastBindResult<Func<CallSite, object, TValue, object>> MakeSet() { var cachedSets = GetCachedSets(); FastSetBase dlg; lock (cachedSets) { var kvp = new SetMemberKey(typeof(TValue), _binder.Name); if (!cachedSets.TryGetValue(kvp, out dlg) || dlg._version != Instance.PythonType.Version) { dlg = Bind(_binder.Name); if (dlg != null) { cachedSets[kvp] = dlg; } } } if (dlg.ShouldUseNonOptimizedSite) { return new FastBindResult<Func<CallSite, object, TValue, object>>((Func<CallSite, object, TValue, object>)(object)dlg._func, false); } return new FastBindResult<Func<CallSite, object, TValue, object>>(); } private Dictionary<SetMemberKey, FastSetBase> GetCachedSets() { var cachedSets = Instance.PythonType._cachedSets; if (cachedSets == null) { Interlocked.CompareExchange( ref Instance.PythonType._cachedSets, new Dictionary<SetMemberKey, FastSetBase>(), null); cachedSets = Instance.PythonType._cachedSets; } return cachedSets; } protected override void MakeSlotSetOrFallback(PythonTypeSlot dts, bool systemTypeResolution) { _unsupported = true; } protected override void MakeSlotsSetTarget(ReflectedSlotProperty prop) { _slotProp = prop; } protected override void MakeFallback() { } protected override void MakeSetAttrTarget(PythonTypeSlot dts) { _setattrSlot = dts; } protected override void MakeDictionarySetTarget() { _dictSet = true; } } internal class MetaSetBinderHelper : SetBinderHelper<DynamicMetaObject> { private readonly MetaUserObject/*!*/ _target; private readonly DynamicMetaObject/*!*/ _value; private readonly SetBindingInfo _info; private DynamicMetaObject _result; private string _resolution = "SetMember "; public MetaSetBinderHelper(MetaUserObject/*!*/ target, DynamicMetaObject/*!*/ value, SetMemberBinder/*!*/ binder) : base(PythonContext.GetPythonContext(binder).SharedContext, target.Value, value.Value) { Assert.NotNull(target, value, binder); _target = target; _value = value; _info = new SetBindingInfo( binder, new DynamicMetaObject[] { target, value }, new ConditionalBuilder(binder), BindingHelpers.GetValidationInfo(target, Instance.PythonType) ); } protected override void MakeSetAttrTarget(PythonTypeSlot dts) { ParameterExpression tmp = Ast.Variable(typeof(object), "boundVal"); _info.Body.AddVariable(tmp); _info.Body.AddCondition( Ast.Call( typeof(PythonOps).GetMethod("SlotTryGetValue"), AstUtils.Constant(PythonContext.GetPythonContext(_info.Action).SharedContext), AstUtils.Convert(AstUtils.WeakConstant(dts), typeof(PythonTypeSlot)), AstUtils.Convert(_info.Args[0].Expression, typeof(object)), AstUtils.Convert(AstUtils.WeakConstant(Instance.PythonType), typeof(PythonType)), tmp ), Ast.Dynamic( PythonContext.GetPythonContext(_info.Action).Invoke( new CallSignature(2) ), typeof(object), PythonContext.GetCodeContext(_info.Action), tmp, AstUtils.Constant(_info.Action.Name), _info.Args[1].Expression ) ); _info.Body.FinishCondition( FallbackSetError(_info.Action, _info.Args[1]).Expression ); _result = _info.Body.GetMetaObject(_target, _value); _resolution += "SetAttr "; } protected override DynamicMetaObject Finish() { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, _resolution); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "UserSet"); Debug.Assert(_result != null); _result = new DynamicMetaObject( _result.Expression, _target.Restrict(Instance.GetType()).Restrictions.Merge(_result.Restrictions) ); Debug.Assert(!_result.Expression.Type.IsValueType()); return BindingHelpers.AddDynamicTestAndDefer( _info.Action, _result, new DynamicMetaObject[] { _target, _value }, _info.Validation ); } protected override void MakeFallback() { _info.Body.FinishCondition( FallbackSetError(_info.Action, _value).Expression ); _result = _info.Body.GetMetaObject(_target, _value); } protected override void MakeDictionarySetTarget() { _resolution += "Dictionary "; FieldInfo fi = _info.Args[0].LimitType.GetField(NewTypeMaker.DictFieldName); if (fi != null) { FieldInfo classField = _info.Args[0].LimitType.GetField(NewTypeMaker.ClassFieldName); var optInstanceNames = Instance.PythonType.GetOptimizedInstanceNames(); int keysIndex; if (classField != null && optInstanceNames != null && (keysIndex = optInstanceNames.IndexOf(_info.Action.Name)) != -1) { // optimized access which can read directly into an object array avoiding a dictionary lookup. // return UserTypeOps.FastSetDictionaryValue(this._class, ref this._dict, name, value, keysVersion, keysIndex); _info.Body.FinishCondition( Ast.Call( typeof(UserTypeOps).GetMethod("FastSetDictionaryValueOptimized"), Ast.Field( Ast.Convert(_info.Args[0].Expression, _info.Args[0].LimitType), classField ), Ast.Field( Ast.Convert(_info.Args[0].Expression, _info.Args[0].LimitType), fi ), AstUtils.Constant(_info.Action.Name), AstUtils.Convert(_info.Args[1].Expression, typeof(object)), Ast.Constant(Instance.PythonType.GetOptimizedInstanceVersion()), Ast.Constant(keysIndex) ) ); } else { // return UserTypeOps.FastSetDictionaryValue(ref this._dict, name, value); _info.Body.FinishCondition( Ast.Call( typeof(UserTypeOps).GetMethod("FastSetDictionaryValue"), Ast.Field( Ast.Convert(_info.Args[0].Expression, _info.Args[0].LimitType), fi ), AstUtils.Constant(_info.Action.Name), AstUtils.Convert(_info.Args[1].Expression, typeof(object)) ) ); } } else { // return UserTypeOps.SetDictionaryValue(rule.Parameters[0], name, value); _info.Body.FinishCondition( Ast.Call( typeof(UserTypeOps).GetMethod("SetDictionaryValue"), Ast.Convert(_info.Args[0].Expression, typeof(IPythonObject)), AstUtils.Constant(_info.Action.Name), AstUtils.Convert(_info.Args[1].Expression, typeof(object)) ) ); } _result = _info.Body.GetMetaObject(_target, _value); } protected override void MakeSlotSetOrFallback(PythonTypeSlot dts, bool systemTypeResolution) { if (systemTypeResolution) { _result = _target.Fallback(_info.Action, _value); } else { _result = MakeSlotSet(_info, dts); } } protected override void MakeSlotsSetTarget(ReflectedSlotProperty prop) { _resolution += "Slot "; MakeSlotsSetTargetHelper(_info, prop, _value.Expression); _result = _info.Body.GetMetaObject(_target, _value); } /// <summary> /// Helper for falling back - if we have a base object fallback to it first (which can /// then fallback to the calling site), otherwise fallback to the calling site. /// </summary> private DynamicMetaObject/*!*/ FallbackSetError(SetMemberBinder/*!*/ action, DynamicMetaObject/*!*/ value) { if (_target._baseMetaObject != null) { return _target._baseMetaObject.BindSetMember(action, value); } else if (action is PythonSetMemberBinder) { return new DynamicMetaObject( MakeTypeError(action, action.Name, Instance.PythonType), BindingRestrictions.Empty ); } return _info.Action.FallbackSetMember(_target.Restrict(_target.GetLimitType()), value); } } private static bool IsStandardObjectMethod(PythonTypeSlot dts) { BuiltinMethodDescriptor bmd = dts as BuiltinMethodDescriptor; if (bmd == null) return false; return bmd.Template.Targets[0].DeclaringType == typeof(ObjectOps); } private static void MakeSlotsDeleteTarget(MemberBindingInfo/*!*/ info, ReflectedSlotProperty/*!*/ rsp) { MakeSlotsSetTargetHelper(info, rsp, Ast.Field(null, typeof(Uninitialized).GetField("Instance"))); } private static void MakeSlotsSetTargetHelper(MemberBindingInfo/*!*/ info, ReflectedSlotProperty/*!*/ rsp, Expression/*!*/ value) { // type has __slots__ defined for this member, call the setter directly ParameterExpression tmp = Ast.Variable(typeof(object), "res"); info.Body.AddVariable(tmp); info.Body.FinishCondition( Ast.Block( Ast.Assign( tmp, Ast.Convert( Ast.Assign( Ast.ArrayAccess( GetSlots(info.Args[0]), AstUtils.Constant(rsp.Index) ), AstUtils.Convert(value, typeof(object)) ), tmp.Type ) ), tmp ) ); } private static DynamicMetaObject MakeSlotSet(SetBindingInfo/*!*/ info, PythonTypeSlot/*!*/ dts) { ParameterExpression tmp = Ast.Variable(info.Args[1].Expression.Type, "res"); info.Body.AddVariable(tmp); // users can subclass PythonProperty so check the type explicitly // and only in-line the ones we fully understand. if (dts.GetType() == typeof(PythonProperty)) { // properties are mutable so we generate code to get the value rather // than burning it into the rule. Expression setter = Ast.Property( Ast.Convert(AstUtils.WeakConstant(dts), typeof(PythonProperty)), "fset" ); ParameterExpression tmpSetter = Ast.Variable(typeof(object), "tmpSet"); info.Body.AddVariable(tmpSetter); info.Body.FinishCondition( Ast.Block( Ast.Assign(tmpSetter, setter), Ast.Condition( Ast.NotEqual( tmpSetter, AstUtils.Constant(null) ), Ast.Block( Ast.Assign(tmp, info.Args[1].Expression), Ast.Dynamic( PythonContext.GetPythonContext(info.Action).InvokeOne, typeof(object), AstUtils.Constant(PythonContext.GetPythonContext(info.Action).SharedContext), tmpSetter, info.Args[0].Expression, AstUtils.Convert(tmp, typeof(object)) ), Ast.Convert( tmp, typeof(object) ) ), info.Action.Throw(Ast.Call(typeof(PythonOps).GetMethod("UnsetableProperty")), typeof(object)) ) ) ); return info.Body.GetMetaObject(); } CodeContext context = PythonContext.GetPythonContext(info.Action).SharedContext; Debug.Assert(context != null); info.Body.AddCondition( Ast.Block( Ast.Assign(tmp, info.Args[1].Expression), Ast.Call( typeof(PythonOps).GetMethod("SlotTrySetValue"), AstUtils.Constant(context), AstUtils.Convert(AstUtils.WeakConstant(dts), typeof(PythonTypeSlot)), AstUtils.Convert(info.Args[0].Expression, typeof(object)), Ast.Convert( Ast.Property( Ast.Convert( info.Args[0].Expression, typeof(IPythonObject)), PythonTypeInfo._IPythonObject.PythonType ), typeof(PythonType) ), AstUtils.Convert(tmp, typeof(object)) ) ), AstUtils.Convert(tmp, typeof(object)) ); return null; } #endregion #region Delete Member Helpers private DynamicMetaObject/*!*/ MakeDeleteMemberRule(DeleteBindingInfo/*!*/ info) { CodeContext context = PythonContext.GetPythonContext(info.Action).SharedContext; DynamicMetaObject self = info.Args[0].Restrict(info.Args[0].GetRuntimeType()); IPythonObject sdo = info.Args[0].Value as IPythonObject; if (info.Action.Name == "__class__") { return new DynamicMetaObject( info.Action.Throw( Ast.New( typeof(TypeErrorException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant("can't delete __class__ attribute") ), typeof(object) ), self.Restrictions ); } // call __delattr__ if it exists PythonTypeSlot dts; if (sdo.PythonType.TryResolveSlot(context, "__delattr__", out dts) && !IsStandardObjectMethod(dts)) { MakeDeleteAttrTarget(info, sdo, dts); } // then see if we have a delete descriptor sdo.PythonType.TryResolveSlot(context, info.Action.Name, out dts); ReflectedSlotProperty rsp = dts as ReflectedSlotProperty; if (rsp != null) { MakeSlotsDeleteTarget(info, rsp); } if (!info.Body.IsFinal && dts != null) { MakeSlotDelete(info, dts); } if (!info.Body.IsFinal && sdo.PythonType.HasDictionary) { // finally if we have a dictionary set the value there. MakeDictionaryDeleteTarget(info); } if (!info.Body.IsFinal) { // otherwise fallback info.Body.FinishCondition( FallbackDeleteError(info.Action, info.Args).Expression ); } DynamicMetaObject res = info.Body.GetMetaObject(info.Args); res = new DynamicMetaObject( res.Expression, self.Restrictions.Merge(res.Restrictions) ); return BindingHelpers.AddDynamicTestAndDefer( info.Action, res, info.Args, info.Validation ); } private static DynamicMetaObject MakeSlotDelete(DeleteBindingInfo/*!*/ info, PythonTypeSlot/*!*/ dts) { // users can subclass PythonProperty so check the type explicitly // and only in-line the ones we fully understand. if (dts.GetType() == typeof(PythonProperty)) { // properties are mutable so we generate code to get the value rather // than burning it into the rule. Expression deleter = Ast.Property( Ast.Convert(AstUtils.WeakConstant(dts), typeof(PythonProperty)), "fdel" ); ParameterExpression tmpDeleter = Ast.Variable(typeof(object), "tmpDel"); info.Body.AddVariable(tmpDeleter); info.Body.FinishCondition( Ast.Block( Ast.Assign(tmpDeleter, deleter), Ast.Condition( Ast.NotEqual( tmpDeleter, AstUtils.Constant(null) ), Ast.Dynamic( PythonContext.GetPythonContext(info.Action).InvokeOne, typeof(object), AstUtils.Constant(PythonContext.GetPythonContext(info.Action).SharedContext), tmpDeleter, info.Args[0].Expression ), info.Action.Throw(Ast.Call(typeof(PythonOps).GetMethod("UndeletableProperty")), typeof(object)) ) ) ); return info.Body.GetMetaObject(); } info.Body.AddCondition( Ast.Call( typeof(PythonOps).GetMethod("SlotTryDeleteValue"), AstUtils.Constant(PythonContext.GetPythonContext(info.Action).SharedContext), AstUtils.Convert(AstUtils.WeakConstant(dts), typeof(PythonTypeSlot)), AstUtils.Convert(info.Args[0].Expression, typeof(object)), Ast.Convert( Ast.Property( Ast.Convert( info.Args[0].Expression, typeof(IPythonObject)), PythonTypeInfo._IPythonObject.PythonType ), typeof(PythonType) ) ), AstUtils.Constant(null) ); return null; } private static void MakeDeleteAttrTarget(DeleteBindingInfo/*!*/ info, IPythonObject self, PythonTypeSlot dts) { ParameterExpression tmp = Ast.Variable(typeof(object), "boundVal"); info.Body.AddVariable(tmp); // call __delattr__ info.Body.AddCondition( Ast.Call( PythonTypeInfo._PythonOps.SlotTryGetBoundValue, AstUtils.Constant(PythonContext.GetPythonContext(info.Action).SharedContext), AstUtils.Convert(AstUtils.WeakConstant(dts), typeof(PythonTypeSlot)), AstUtils.Convert(info.Args[0].Expression, typeof(object)), AstUtils.Convert(AstUtils.WeakConstant(self.PythonType), typeof(PythonType)), tmp ), DynamicExpression.Dynamic( PythonContext.GetPythonContext(info.Action).InvokeOne, typeof(object), PythonContext.GetCodeContext(info.Action), tmp, AstUtils.Constant(info.Action.Name) ) ); } private static void MakeDictionaryDeleteTarget(DeleteBindingInfo/*!*/ info) { info.Body.FinishCondition( Ast.Call( typeof(UserTypeOps).GetMethod("RemoveDictionaryValue"), Ast.Convert(info.Args[0].Expression, typeof(IPythonObject)), AstUtils.Constant(info.Action.Name) ) ); } #endregion #region Common Helpers /// <summary> /// Looks up the associated PythonTypeSlot from the object. Indicates if the result /// came from a standard .NET type in which case we will fallback to the sites binder. /// </summary> private static PythonTypeSlot FindSlot(CodeContext/*!*/ context, string/*!*/ name, IPythonObject/*!*/ sdo, out bool isOldStyle, out bool systemTypeResolution, out bool extensionMethodResolution) { PythonTypeSlot foundSlot = null; isOldStyle = false; // if we're mixed new-style/old-style we have to do a slower check systemTypeResolution = false; // if we pick up the property from a System type we fallback foreach (PythonType pt in sdo.PythonType.ResolutionOrder) { if (pt.IsOldClass) { isOldStyle = true; } if (pt.TryLookupSlot(context, name, out foundSlot)) { // use our built-in binding for ClassMethodDescriptors rather than falling back if (!(foundSlot is ClassMethodDescriptor)) { systemTypeResolution = pt.IsSystemType; } break; } } extensionMethodResolution = false; if (foundSlot == null) { extensionMethodResolution = true; var extMethods = context.ModuleContext.ExtensionMethods.GetBinder(context.LanguageContext).GetMember(MemberRequestKind.Get, sdo.PythonType.UnderlyingSystemType, name); if (extMethods.Count > 0) { foundSlot = PythonTypeOps.GetSlot(extMethods, name, false); } } return foundSlot; } #endregion #region BindingInfo classes class MemberBindingInfo { public readonly ConditionalBuilder/*!*/ Body; public readonly DynamicMetaObject/*!*/[]/*!*/ Args; public readonly ValidationInfo/*!*/ Validation; public MemberBindingInfo(DynamicMetaObject/*!*/[]/*!*/ args, ConditionalBuilder/*!*/ body, ValidationInfo/*!*/ validation) { Body = body; Validation = validation; Args = args; } } class DeleteBindingInfo : MemberBindingInfo { public readonly DeleteMemberBinder/*!*/ Action; public DeleteBindingInfo(DeleteMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args, ConditionalBuilder/*!*/ body, ValidationInfo/*!*/ validation) : base(args, body, validation) { Action = action; } } class SetBindingInfo : MemberBindingInfo { public readonly SetMemberBinder/*!*/ Action; public SetBindingInfo(SetMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args, ConditionalBuilder/*!*/ body, ValidationInfo/*!*/ validation) : base(args, body, validation) { Action = action; } } class GetBindingInfo : MemberBindingInfo { public readonly DynamicMetaObjectBinder/*!*/ Action; public readonly ParameterExpression/*!*/ Self, Result; public GetBindingInfo(DynamicMetaObjectBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args, ParameterExpression/*!*/ self, ParameterExpression/*!*/ result, ConditionalBuilder/*!*/ body, ValidationInfo/*!*/ validationInfo) : base(args, body, validationInfo) { Action = action; Self = self; Result = result; } } #endregion #region Fallback Helpers /// <summary> /// Helper for falling back - if we have a base object fallback to it first (which can /// then fallback to the calling site), otherwise fallback to the calling site. /// </summary> private DynamicMetaObject/*!*/ FallbackGetError(DynamicMetaObjectBinder/*!*/ action, DynamicMetaObject codeContext) { if (_baseMetaObject != null) { return Fallback(action, codeContext); } else if (BindingHelpers.IsNoThrow(action)) { return new DynamicMetaObject( Ast.Field(null, typeof(OperationFailed).GetField("Value")), BindingRestrictions.Empty ); } else if (action is PythonGetMemberBinder) { return new DynamicMetaObject( MakeTypeError(action, GetGetMemberName(action), PythonType), BindingRestrictions.Empty ); } return GetMemberFallback(this, action, codeContext); } /// <summary> /// Helper for falling back - if we have a base object fallback to it first (which can /// then fallback to the calling site), otherwise fallback to the calling site. /// </summary> private DynamicMetaObject/*!*/ FallbackDeleteError(DeleteMemberBinder/*!*/ action, DynamicMetaObject/*!*/[] args) { if (_baseMetaObject != null) { return _baseMetaObject.BindDeleteMember(action); } else if (action is PythonDeleteMemberBinder) { return new DynamicMetaObject( MakeTypeError(action, action.Name, ((IPythonObject)args[0].Value).PythonType), BindingRestrictions.Empty ); } return action.FallbackDeleteMember(this.Restrict(this.GetLimitType())); } #endregion private static Expression/*!*/ GetSlots(DynamicMetaObject/*!*/ self) { FieldInfo fi = self.LimitType.GetField(NewTypeMaker.SlotsAndWeakRefFieldName); if (fi != null) { return Ast.Field( Ast.Convert(self.Expression, self.LimitType), fi ); } return Ast.Call( Ast.Convert(self.Expression, typeof(IPythonObject)), typeof(IPythonObject).GetMethod("GetSlots") ); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Newtonsoft.Json; using System; using System.Collections.Generic; namespace QuantConnect.Brokerages.GDAX.Messages { //several simple objects to facilitate json conversion #pragma warning disable 1591 public class BaseMessage { public string Type { get; set; } public long Sequence { get; set; } public DateTime Time { get; set; } [JsonProperty("product_id")] public string ProductId { get; set; } } public class Done : BaseMessage { public decimal Price { get; set; } [JsonProperty("order_id")] public string OrderId { get; set; } public string Reason { get; set; } public string Side { get; set; } public decimal RemainingSize { get; set; } } public class Matched : BaseMessage { [JsonProperty("trade_id")] public int TradeId { get; set; } [JsonProperty("maker_order_id")] public string MakerOrderId { get; set; } [JsonProperty("taker_order_id")] public string TakerOrderId { get; set; } public decimal Size { get; set; } public decimal Price { get; set; } public string Side { get; set; } [JsonProperty("taker_user_id")] public string TakerUserId { get; set; } [JsonProperty("user_id")] public string UserId { get; set; } [JsonProperty("taker_profile_id")] public string TakerProfileId { get; set; } [JsonProperty("profile_id")] public string ProfileId { get; set; } } public class Heartbeat : BaseMessage { [JsonProperty("last_trade_id")] public int LastTradeId { get; set; } } public class Error : BaseMessage { public string Message { get; set; } public string Reason { get; set; } } public class Subscribe { public string Type { get; set; } [JsonProperty("product_ids")] public IList<string> ProductIds { get; set; } public string Signature { get; set; } public string Key { get; set; } public string Passphrase { get; set; } public string Timestamp { get; set; } } public class Open : BaseMessage { [JsonProperty("order_id")] public string OrderId { get; set; } public decimal Price { get; set; } [JsonProperty("remaining_size")] public decimal RemainingSize { get; set; } public string Side { get; set; } } public class Change : Open { [JsonProperty("new_funds")] public decimal NewFunds { get; set; } [JsonProperty("old_funds")] public decimal OldFunds { get; set; } } public class Order { public string Id { get; set; } public decimal Price { get; set; } public decimal Size { get; set; } [JsonProperty("product_id")] public string ProductId { get; set; } public string Side { get; set; } public string Stp { get; set; } public string Type { get; set; } [JsonProperty("time_in_force")] public string TimeInForce { get; set; } [JsonProperty("post_only")] public bool PostOnly { get; set; } [JsonProperty("reject_reason")] public string RejectReason { get; set; } [JsonProperty("fill_fees")] public decimal FillFees { get; set; } [JsonProperty("filled_size")] public decimal FilledSize { get; set; } [JsonProperty("executed_value")] public decimal ExecutedValue { get; set; } public string Status { get; set; } public bool Settled { get; set; } public string Stop { get; set; } [JsonProperty("stop_price")] public decimal StopPrice { get; set; } } public class Fill { [JsonProperty("created_at")] public DateTime CreatedAt { get; set; } [JsonProperty("trade_id")] public long TradeId { get; set; } [JsonProperty("product_id")] public string ProductId { get; set; } [JsonProperty("order_id")] public string OrderId { get; set; } [JsonProperty("user_id")] public string UserId { get; set; } [JsonProperty("profile_id")] public string ProfileId { get; set; } [JsonProperty("liquidity")] public string Liquidity { get; set; } [JsonProperty("price")] public decimal Price { get; set; } [JsonProperty("size")] public decimal Size { get; set; } [JsonProperty("fee")] public decimal Fee { get; set; } [JsonProperty("side")] public string Side { get; set; } [JsonProperty("settled")] public bool Settled { get; set; } [JsonProperty("usd_volume")] public decimal UsdVolume { get; set; } } public class Account { public string Id { get; set; } public string Currency { get; set; } public decimal Balance { get; set; } public decimal Hold { get; set; } public decimal Available { get; set; } [JsonProperty("profile_id")] public string ProfileId { get; set; } } public class Tick { [JsonProperty("product_id")] public string ProductId { get; set; } [JsonProperty("trade_id")] public string TradeId { get; set; } public decimal Price { get; set; } public decimal Size { get; set; } public decimal Bid { get; set; } public decimal Ask { get; set; } public decimal Volume { get; set; } public DateTime Time { get; set; } } public class Ticker : BaseMessage { [JsonProperty("trade_id")] public string TradeId { get; set; } [JsonProperty("last_size")] public decimal LastSize { get; set; } [JsonProperty("best_bid")] public decimal BestBid { get; set; } [JsonProperty("best_ask")] public decimal BestAsk { get; set; } public decimal Price { get; set; } public string Side { get; set; } } public class Snapshot : BaseMessage { public List<string[]> Bids { get; set; } public List<string[]> Asks { get; set; } } public class L2Update : BaseMessage { public List<string[]> Changes { get; set; } } #pragma warning restore 1591 }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Reflection.Metadata; namespace System.Reflection.PortableExecutable { public sealed class PEHeader { #region Standard fields /// <summary> /// Identifies the format of the image file. /// </summary> public PEMagic Magic { get; private set; } /// <summary> /// The linker major version number. /// </summary> public byte MajorLinkerVersion { get; private set; } /// <summary> /// The linker minor version number. /// </summary> public byte MinorLinkerVersion { get; private set; } /// <summary> /// The size of the code (text) section, or the sum of all code sections if there are multiple sections. /// </summary> public int SizeOfCode { get; private set; } /// <summary> /// The size of the initialized data section, or the sum of all such sections if there are multiple data sections. /// </summary> public int SizeOfInitializedData { get; private set; } /// <summary> /// The size of the uninitialized data section (BSS), or the sum of all such sections if there are multiple BSS sections. /// </summary> public int SizeOfUninitializedData { get; private set; } /// <summary> /// The address of the entry point relative to the image base when the PE file is loaded into memory. /// For program images, this is the starting address. For device drivers, this is the address of the initialization function. /// An entry point is optional for DLLs. When no entry point is present, this field must be zero. /// </summary> public int AddressOfEntryPoint { get; private set; } /// <summary> /// The address that is relative to the image base of the beginning-of-code section when it is loaded into memory. /// </summary> public int BaseOfCode { get; private set; } /// <summary> /// The address that is relative to the image base of the beginning-of-data section when it is loaded into memory. /// </summary> public int BaseOfData { get; private set; } #endregion #region Windows Specific Fields /// <summary> /// The preferred address of the first byte of image when loaded into memory; /// must be a multiple of 64K. /// </summary> public ulong ImageBase { get; private set; } /// <summary> /// The alignment (in bytes) of sections when they are loaded into memory. It must be greater than or equal to <see cref="FileAlignment"/>. /// The default is the page size for the architecture. /// </summary> public int SectionAlignment { get; private set; } /// <summary> /// The alignment factor (in bytes) that is used to align the raw data of sections in the image file. /// The value should be a power of 2 between 512 and 64K, inclusive. The default is 512. /// If the <see cref="SectionAlignment"/> is less than the architecture's page size, /// then <see cref="FileAlignment"/> must match <see cref="SectionAlignment"/>. /// </summary> public int FileAlignment { get; private set; } /// <summary> /// The major version number of the required operating system. /// </summary> public ushort MajorOperatingSystemVersion { get; private set; } /// <summary> /// The minor version number of the required operating system. /// </summary> public ushort MinorOperatingSystemVersion { get; private set; } /// <summary> /// The major version number of the image. /// </summary> public ushort MajorImageVersion { get; private set; } /// <summary> /// The minor version number of the image. /// </summary> public ushort MinorImageVersion { get; private set; } /// <summary> /// The major version number of the subsystem. /// </summary> public ushort MajorSubsystemVersion { get; private set; } /// <summary> /// The minor version number of the subsystem. /// </summary> public ushort MinorSubsystemVersion { get; private set; } /// <summary> /// The size (in bytes) of the image, including all headers, as the image is loaded in memory. /// It must be a multiple of <see cref="SectionAlignment"/>. /// </summary> public int SizeOfImage { get; private set; } /// <summary> /// The combined size of an MS DOS stub, PE header, and section headers rounded up to a multiple of FileAlignment. /// </summary> public int SizeOfHeaders { get; private set; } /// <summary> /// The image file checksum. /// </summary> public uint CheckSum { get; private set; } /// <summary> /// The subsystem that is required to run this image. /// </summary> public Subsystem Subsystem { get; private set; } public DllCharacteristics DllCharacteristics { get; private set; } /// <summary> /// The size of the stack to reserve. Only <see cref="SizeOfStackCommit"/> is committed; /// the rest is made available one page at a time until the reserve size is reached. /// </summary> public ulong SizeOfStackReserve { get; private set; } /// <summary> /// The size of the stack to commit. /// </summary> public ulong SizeOfStackCommit { get; private set; } /// <summary> /// The size of the local heap space to reserve. Only <see cref="SizeOfHeapCommit"/> is committed; /// the rest is made available one page at a time until the reserve size is reached. /// </summary> public ulong SizeOfHeapReserve { get; private set; } /// <summary> /// The size of the local heap space to commit. /// </summary> public ulong SizeOfHeapCommit { get; private set; } /// <summary> /// The number of data-directory entries in the remainder of the <see cref="PEHeader"/>. Each describes a location and size. /// </summary> public int NumberOfRvaAndSizes { get; private set; } #endregion #region Directory Entries public DirectoryEntry ExportTableDirectory { get; private set; } public DirectoryEntry ImportTableDirectory { get; private set; } public DirectoryEntry ResourceTableDirectory { get; private set; } public DirectoryEntry ExceptionTableDirectory { get; private set; } /// <summary> /// The Certificate Table entry points to a table of attribute certificates. /// These certificates are not loaded into memory as part of the image. /// As such, the first field of this entry, which is normally an RVA, is a file pointer instead. /// </summary> public DirectoryEntry CertificateTableDirectory { get; private set; } public DirectoryEntry BaseRelocationTableDirectory { get; private set; } public DirectoryEntry DebugTableDirectory { get; private set; } public DirectoryEntry CopyrightTableDirectory { get; private set; } public DirectoryEntry GlobalPointerTableDirectory { get; private set; } public DirectoryEntry ThreadLocalStorageTableDirectory { get; private set; } public DirectoryEntry LoadConfigTableDirectory { get; private set; } public DirectoryEntry BoundImportTableDirectory { get; private set; } public DirectoryEntry ImportAddressTableDirectory { get; private set; } public DirectoryEntry DelayImportTableDirectory { get; private set; } public DirectoryEntry CorHeaderTableDirectory { get; private set; } #endregion internal PEHeader(ref PEBinaryReader reader) { PEMagic magic = (PEMagic)reader.ReadUInt16(); if (magic != PEMagic.PE32 && magic != PEMagic.PE32Plus) { throw new BadImageFormatException(MetadataResources.UnknownPEMagicValue); } Magic = magic; MajorLinkerVersion = reader.ReadByte(); MinorLinkerVersion = reader.ReadByte(); SizeOfCode = reader.ReadInt32(); SizeOfInitializedData = reader.ReadInt32(); SizeOfUninitializedData = reader.ReadInt32(); AddressOfEntryPoint = reader.ReadInt32(); BaseOfCode = reader.ReadInt32(); if (magic == PEMagic.PE32Plus) { BaseOfData = 0; // not present } else { Debug.Assert(magic == PEMagic.PE32); BaseOfData = reader.ReadInt32(); } if (magic == PEMagic.PE32Plus) { ImageBase = reader.ReadUInt64(); } else { ImageBase = reader.ReadUInt32(); } // NT additional fields: SectionAlignment = reader.ReadInt32(); FileAlignment = reader.ReadInt32(); MajorOperatingSystemVersion = reader.ReadUInt16(); MinorOperatingSystemVersion = reader.ReadUInt16(); MajorImageVersion = reader.ReadUInt16(); MinorImageVersion = reader.ReadUInt16(); MajorSubsystemVersion = reader.ReadUInt16(); MinorSubsystemVersion = reader.ReadUInt16(); // Win32VersionValue (reserved, should be 0) reader.ReadUInt32(); SizeOfImage = reader.ReadInt32(); SizeOfHeaders = reader.ReadInt32(); CheckSum = reader.ReadUInt32(); Subsystem = (Subsystem)reader.ReadUInt16(); DllCharacteristics = (DllCharacteristics)reader.ReadUInt16(); if (magic == PEMagic.PE32Plus) { SizeOfStackReserve = reader.ReadUInt64(); SizeOfStackCommit = reader.ReadUInt64(); SizeOfHeapReserve = reader.ReadUInt64(); SizeOfHeapCommit = reader.ReadUInt64(); } else { SizeOfStackReserve = reader.ReadUInt32(); SizeOfStackCommit = reader.ReadUInt32(); SizeOfHeapReserve = reader.ReadUInt32(); SizeOfHeapCommit = reader.ReadUInt32(); } // loader flags reader.ReadUInt32(); NumberOfRvaAndSizes = reader.ReadInt32(); // directory entries: ExportTableDirectory = new DirectoryEntry(ref reader); ImportTableDirectory = new DirectoryEntry(ref reader); ResourceTableDirectory = new DirectoryEntry(ref reader); ExceptionTableDirectory = new DirectoryEntry(ref reader); CertificateTableDirectory = new DirectoryEntry(ref reader); BaseRelocationTableDirectory = new DirectoryEntry(ref reader); DebugTableDirectory = new DirectoryEntry(ref reader); CopyrightTableDirectory = new DirectoryEntry(ref reader); GlobalPointerTableDirectory = new DirectoryEntry(ref reader); ThreadLocalStorageTableDirectory = new DirectoryEntry(ref reader); LoadConfigTableDirectory = new DirectoryEntry(ref reader); BoundImportTableDirectory = new DirectoryEntry(ref reader); ImportAddressTableDirectory = new DirectoryEntry(ref reader); DelayImportTableDirectory = new DirectoryEntry(ref reader); CorHeaderTableDirectory = new DirectoryEntry(ref reader); // ReservedDirectory (should be 0, 0) new DirectoryEntry(ref reader); } } }
//#define DEBUG using System; using System.Collections.Generic; namespace ICSimulator { public abstract class Connector_Direct : Router { // injectSlot is from Node; injectSlot2 is higher-priority from // network-level re-injection (e.g., placeholder schemes) protected Flit m_injectSlot, m_injectSlot2; public Connector_Direct(Coord myCoord) : base(myCoord) { if (!Config.torus && !Config.edge_loop) throw new Exception("Rings of Rings must be a torus or edge-loop. Set Config.torus or Config.edge_loop to true"); m_injectSlot = null; m_injectSlot2 = null; } // accept one ejected flit into rxbuf void acceptFlit(Flit f) { statsEjectFlit(f); if (f.packet.nrOfArrivedFlits + 1 == f.packet.nrOfFlits) statsEjectPacket(f.packet); m_n.receiveFlit(f); } Flit[] m_ej = new Flit[4] { null, null, null, null }; int m_ej_rr = 0; Flit ejectLocalNew() { for (int dir = 0; dir < 4; dir++) if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.dest.ID == ID && m_ej[dir] == null) { m_ej[dir] = linkIn[dir].Out; linkIn[dir].Out = null; } m_ej_rr++; m_ej_rr %= 4; Flit ret = null; if (m_ej[m_ej_rr] != null) { ret = m_ej[m_ej_rr]; m_ej[m_ej_rr] = null; } #if DEBUG if (ret != null) Console.WriteLine("| ejecting flit {0}.{1} at node {2} cyc {3}", ret.packet.ID, ret.flitNr, coord, Simulator.CurrentRound); #endif return ret; } Flit ejectLocal() { // eject locally-destined flit (highest-ranked, if multiple) Flit ret = null; int bestDir = -1; for (int dir = 0; dir < 4; dir++) if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.state != Flit.State.Placeholder && linkIn[dir].Out.dest.ID == ID && (ret == null || rank(linkIn[dir].Out, ret) < 0)) { ret = linkIn[dir].Out; bestDir = dir; } if (bestDir != -1) linkIn[bestDir].Out = null; #if DEBUG if (ret != null) Console.WriteLine("| ejecting flit {0}.{1} at node {2} cyc {3}", ret.packet.ID, ret.flitNr, coord, Simulator.CurrentRound); #endif return ret; } /* * Injects flits */ void inject(out bool injected) { injected = false; if (input[4] == null) return; if (Config.injectOnlyX) { int i = (Simulator.rand.Next(2) == 1) ? Simulator.DIR_RIGHT : Simulator.DIR_LEFT; if (input[i] == null) { injected = true; input[i] = input[4]; input[4] = null; return; } if (i == Simulator.DIR_RIGHT) i = Simulator.DIR_LEFT; else i = Simulator.DIR_RIGHT; if (input[i] == null) { injected = true; input[i] = input[4]; input[4] = null; } } else { for (int i = 0; i < 4; i++) { if (input[i] == null) { injected = true; input[i] = input[4]; input[4] = null; break; } } } } /* Tells if a flit wants to turn */ bool wantToTurn(Flit f, int dir) { bool wantToTurn = false; switch(dir) { case Simulator.DIR_UP: wantToTurn = (coord.y == f.packet.dest.y); break; case Simulator.DIR_DOWN: wantToTurn = (coord.y == f.packet.dest.y); break; case Simulator.DIR_LEFT: wantToTurn = (coord.x == f.packet.dest.x); break; case Simulator.DIR_RIGHT: wantToTurn = (coord.x == f.packet.dest.x); break; default: throw new Exception("Not a direction"); } return wantToTurn; } int turn_priority(int dir1, int dir2) { Flit f1 = (dir1 == -1) ? null : input[dir1]; Flit f2 = (dir2 == -1) ? null : input[dir2]; int ret = rank(f1, f2); switch (ret) { case 0: return (Simulator.rand.Next(2) == 1) ? dir1 : dir2; //throw new Exception("Tiebraker wasn't decided"); case -1: return dir1; case 1: return dir2; default: throw new Exception("Should I allow for larger values than 1 and -1"); } //return (1 == Simulator.rand.Next(2)) ? dir1 : dir2; } int turnX_priority() { Flit left = input[Simulator.DIR_LEFT]; Flit right = input[Simulator.DIR_RIGHT]; bool turn_left = false; bool turn_right = false; if (left != null) turn_left = wantToTurn(left, Simulator.DIR_LEFT); if (right != null) turn_right = wantToTurn(right, Simulator.DIR_RIGHT); if (turn_left ^ turn_right) { if(turn_left) return Simulator.DIR_LEFT; else return Simulator.DIR_RIGHT; } else if (turn_left && turn_right) { int ret = turn_priority(Simulator.DIR_LEFT, Simulator.DIR_RIGHT); if (ret == Simulator.DIR_LEFT) right.missedTurns++; else left.missedTurns++; return ret; } else return -1; } int turnY_priority() { Flit up = input[Simulator.DIR_UP]; Flit down = input[Simulator.DIR_DOWN]; bool turn_up = false; bool turn_down = false; if (up != null) turn_up = wantToTurn(up, Simulator.DIR_UP); if (down != null) turn_down = wantToTurn(down, Simulator.DIR_DOWN); if (turn_up ^ turn_down) { if(turn_down) return Simulator.DIR_DOWN; else return Simulator.DIR_UP; } else if (turn_up && turn_down) { int ret = turn_priority(Simulator.DIR_DOWN, Simulator.DIR_UP); if (ret == Simulator.DIR_UP) down.missedTurns++; else up.missedTurns++; return ret; } else return -1; } //int[] swapArray = new int[5]; void swap(int dir1, int dir2) { Flit tempFlit = input[dir1]; input[dir1] = input[dir2]; input[dir2] = tempFlit; //swapArray[dir2] = dir1; //swapArray[dir1] = dir2; } int getFreeFlit(int dir1, int dir2) { Flit f1 = (dir1 == -1) ? null : input[dir1]; Flit f2 = (dir2 == -1) ? null : input[dir2]; int ret = rank(f1, f2); switch (ret) { case 0: return (Simulator.rand.Next(2) == 1) ? dir1 : dir2; //throw new Exception("Tiebraker wasn't decided"); case -1: return dir2; case 1: return dir1; default: throw new Exception("Should I allow for larger values than 1 and -1"); } } void route() { int nullCount = 0; for(int i = 0; i < 4; i++) { //swapArray[i] = i; if (input[i] == null) nullCount++; } int turnY = turnY_priority(); int turnX = turnX_priority(); Flit flitX = (turnX != -1) ? input[turnX] : null; Flit flitY = (turnY != -1) ? input[turnY] : null; bool isFreeX = (input[Simulator.DIR_LEFT] == null || input[Simulator.DIR_RIGHT] == null); bool isFreeY = (input[Simulator.DIR_UP] == null || input[Simulator.DIR_DOWN] == null); // NOTE: BIAS maybe need to be randomized which one comes first int freeX = getFreeFlit(Simulator.DIR_LEFT, Simulator.DIR_RIGHT); int freeY = getFreeFlit(Simulator.DIR_DOWN, Simulator.DIR_UP); bool swapX = isFreeX || (turnY == turn_priority(turnY, freeX)); bool swapY = isFreeY || (turnX == turn_priority(turnX, freeY)); if ((turnY != -1) ^ (turnX != -1)) { if (turnY != -1) { if(swapX) { #if DEBUG Console.WriteLine("\tturning flitY {0}.{1} at node {2} cyc {3}", flitY.packet.ID, flitY.flitNr, coord, Simulator.CurrentRound); #endif if (turnY == turn_priority(freeX, turnY)) swap(freeX, turnY); if (input[freeX] == input[turnY]) throw new Exception("Two flits are the same"); //if(input[turnY] != null) // throw new Exception("Swapping didn't work turnY"); } else flitY.missedTurns++; } else if (turnX != -1) { if (swapY) { #if DEBUG Console.WriteLine("\tturning flitX {0}.{1} at node {2} cyc {3}", flitX.packet.ID, flitX.flitNr, coord, Simulator.CurrentRound); #endif if (turnX == turn_priority(freeY, turnX)) swap(freeY, turnX); if (input[freeY] == input[turnX]) throw new Exception("Two flits are the same"); //if(input[turnX] != null) // throw new Exception("Swapping didn't work turnX"); } else flitX.missedTurns++; } } else if(turnY != -1 && turnX != -1) { #if DEBUG Console.WriteLine("\tturning flitX {0}.{1} and flitY {2}.{3} at node {4} cyc {5}", flitX.packet.ID, flitX.flitNr, flitY.packet.ID, flitY.flitNr, coord, Simulator.CurrentRound); #endif swap(turnX, turnY); if (input[turnX] == input[turnY]) throw new Exception("Two flits are the same"); if(input[turnX] == null || input[turnY] == null) throw new Exception("Flits are turning null"); /* //Allow only one to win int winner = turn_priority(flitX, flitY, turnX, turnY); if (winner == turnX) { swap(freeY, turnX); flitY.missedTurns++; } else { swap(freeX, turnY); flitX.missedTurns++; } */ } int finalNullCount = 0; for(int i = 0; i < 4; i++) if(input[i] == null) finalNullCount++; if (nullCount < finalNullCount) throw new Exception("Flits are disappearing"); else if(nullCount > finalNullCount) throw new Exception("Flits are duplicating"); Flit[] temp = new Flit[5]; for(int i = 0; i < 4; i++) { temp[i] = input[i]; } input[Simulator.DIR_UP] = temp[Simulator.DIR_DOWN]; input[Simulator.DIR_DOWN] = temp[Simulator.DIR_UP]; input[Simulator.DIR_LEFT] = temp[Simulator.DIR_RIGHT]; input[Simulator.DIR_RIGHT] = temp[Simulator.DIR_LEFT]; } Flit[] input = new Flit[5]; // keep this as a member var so we don't // have to allocate on every step (why can't // we have arrays on the stack like in C?) protected override void _doStep() { /* Ejection selection and ejection */ Flit eject = null; eject = ejectLocalNew(); /* Setup the inputs */ for (int dir = 0; dir < 4; dir++) { if (linkIn[dir] != null && linkIn[dir].Out != null) { input[dir] = linkIn[dir].Out; input[dir].inDir = dir; } else input[dir] = null; } /* Injection */ Flit inj = null; bool injected = false; /* Pick slot to inject */ if (m_injectSlot2 != null) { inj = m_injectSlot2; m_injectSlot2 = null; } else if (m_injectSlot != null) { inj = m_injectSlot; m_injectSlot = null; } /* Port 4 becomes the injected line */ input[4] = inj; /* If there is data, set the injection direction */ if (inj != null) inj.inDir = -1; /* Go thorugh inputs, find their preferred directions */ for (int i = 0; i < 5; i++) { if (input[i] != null) { PreferredDirection pd = determineDirection(input[i]); if (pd.xDir != Simulator.DIR_NONE) input[i].prefDir = pd.xDir; else input[i].prefDir = pd.yDir; } } /* Inject and route flits in correct directions */ inject(out injected); #if DEBUG for (int dir = 0; dir < 4; dir++) if(input[dir] != null) Console.WriteLine("flit {0}.{1} at node {2} cyc {3} AFTER_INJ", input[dir].packet.ID, input[dir].flitNr, coord, Simulator.CurrentRound); #endif if (injected && input[4] != null) throw new Exception("Not removing injected flit from slot"); route(); #if DEBUG for (int dir = 0; dir < 4; dir++) if(input[dir] != null) Console.WriteLine("flit {0}.{1} at node {2} cyc {3} AFTER_ROUTE", input[dir].packet.ID, input[dir].flitNr, coord, Simulator.CurrentRound); #endif //for (int i = 0; i < 4; i++) //{ // if (input[i] != null) // { // input[i].Deflected = input[i].prefDir != i; // } //} /* If something wasn't injected, move the flit into the injection slots * * If it was injected, take stats */ if (!injected) { if (m_injectSlot == null) m_injectSlot = inj; else m_injectSlot2 = inj; } else statsInjectFlit(inj); /* Put ejected flit in reassembly buffer */ if (eject != null) acceptFlit(eject); /* Assign outputs */ for (int dir = 0; dir < 4; dir++) { if (input[dir] != null) { #if DEBUG Console.WriteLine("flit {0}.{1} at node {2} cyc {3} END", input[dir].packet.ID, input[dir].flitNr, coord, Simulator.CurrentRound); #endif if (linkOut[dir] == null) throw new Exception(String.Format("router {0} does not have link in dir {1}", coord, dir)); linkOut[dir].In = input[dir]; } #if DEBUG //else if(dir == Simulator.DIR_LEFT || dir == Simulator.DIR_RIGHT) // Console.WriteLine("no flit at node {0} cyc {1}", coord, Simulator.CurrentRound); #endif } } public override bool canInjectFlit(Flit f) { return m_injectSlot == null; } public override void InjectFlit(Flit f) { if (m_injectSlot != null) throw new Exception("Trying to inject twice in one cycle"); m_injectSlot = f; } public override void visitFlits(Flit.Visitor fv) { if (m_injectSlot != null) fv(m_injectSlot); if (m_injectSlot2 != null) fv(m_injectSlot2); } //protected abstract int rank(Flit f1, Flit f2); } public class Connector_Direct_Random : Connector_Direct { public Connector_Direct_Random(Coord myCoord) : base(myCoord) { } public override int rank(Flit f1, Flit f2) { return Router_Flit_Random._rank(f1, f2); } } public class Connector_Direct_OldestFirst : Connector_Direct { public Connector_Direct_OldestFirst(Coord myCoord) : base(myCoord) { } public override int rank(Flit f1, Flit f2) { return Router_Flit_OldestFirst._rank(f1, f2); } } public class Connector_Direct_ClosestFirst : Connector_Direct { public Connector_Direct_ClosestFirst(Coord myCoord) : base(myCoord) { } public override int rank(Flit f1, Flit f2) { return Router_Flit_ClosestFirst._rank(f1, f2); } } public class Connector_Direct_GP : Connector_Direct { public Connector_Direct_GP(Coord myCoord) : base(myCoord) { } public override int rank(Flit f1, Flit f2) { return Router_Flit_GP._rank(f1, f2); } } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Text.Util.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Android.Text.Util { /// <summary> /// <para>Linkify take a piece of text and a regular expression and turns all of the regex matches in the text into clickable links. This is particularly useful for matching things like email addresses, web urls, etc. and making them actionable.</para><para>Alone with the pattern that is to be matched, a url scheme prefix is also required. Any pattern match that does not begin with the supplied scheme will have the scheme prepended to the matched text when the clickable url is created. For instance, if you are matching web urls you would supply the scheme <code></code>. If the pattern matches example.com, which does not have a url scheme prefix, the supplied scheme will be prepended to create <code></code> when the clickable url link is created. </para> /// </summary> /// <java-name> /// android/text/util/Linkify /// </java-name> [Dot42.DexImport("android/text/util/Linkify", AccessFlags = 33)] public partial class Linkify /* scope: __dot42__ */ { /// <summary> /// <para>Bit field indicating that web URLs should be matched in methods that take an options mask </para> /// </summary> /// <java-name> /// WEB_URLS /// </java-name> [Dot42.DexImport("WEB_URLS", "I", AccessFlags = 25)] public const int WEB_URLS = 1; /// <summary> /// <para>Bit field indicating that email addresses should be matched in methods that take an options mask </para> /// </summary> /// <java-name> /// EMAIL_ADDRESSES /// </java-name> [Dot42.DexImport("EMAIL_ADDRESSES", "I", AccessFlags = 25)] public const int EMAIL_ADDRESSES = 2; /// <summary> /// <para>Bit field indicating that phone numbers should be matched in methods that take an options mask </para> /// </summary> /// <java-name> /// PHONE_NUMBERS /// </java-name> [Dot42.DexImport("PHONE_NUMBERS", "I", AccessFlags = 25)] public const int PHONE_NUMBERS = 4; /// <summary> /// <para>Bit field indicating that street addresses should be matched in methods that take an options mask </para> /// </summary> /// <java-name> /// MAP_ADDRESSES /// </java-name> [Dot42.DexImport("MAP_ADDRESSES", "I", AccessFlags = 25)] public const int MAP_ADDRESSES = 8; /// <summary> /// <para>Bit mask indicating that all available patterns should be matched in methods that take an options mask </para> /// </summary> /// <java-name> /// ALL /// </java-name> [Dot42.DexImport("ALL", "I", AccessFlags = 25)] public const int ALL = 15; /// <summary> /// <para>Filters out web URL matches that occur after an at-sign (@). This is to prevent turning the domain name in an email address into a web link. </para> /// </summary> /// <java-name> /// sUrlMatchFilter /// </java-name> [Dot42.DexImport("sUrlMatchFilter", "Landroid/text/util/Linkify$MatchFilter;", AccessFlags = 25)] public static readonly global::Android.Text.Util.Linkify.IMatchFilter SUrlMatchFilter; /// <summary> /// <para>Filters out URL matches that don't have enough digits to be a phone number. </para> /// </summary> /// <java-name> /// sPhoneNumberMatchFilter /// </java-name> [Dot42.DexImport("sPhoneNumberMatchFilter", "Landroid/text/util/Linkify$MatchFilter;", AccessFlags = 25)] public static readonly global::Android.Text.Util.Linkify.IMatchFilter SPhoneNumberMatchFilter; /// <summary> /// <para>Transforms matched phone number text into something suitable to be used in a tel: URL. It does this by removing everything but the digits and plus signs. For instance: '+1 (919) 555-1212' becomes '+19195551212' </para> /// </summary> /// <java-name> /// sPhoneNumberTransformFilter /// </java-name> [Dot42.DexImport("sPhoneNumberTransformFilter", "Landroid/text/util/Linkify$TransformFilter;", AccessFlags = 25)] public static readonly global::Android.Text.Util.Linkify.ITransformFilter SPhoneNumberTransformFilter; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Linkify() /* MethodBuilder.Create */ { } /// <summary> /// <para>Scans the text of the provided Spannable and turns all occurrences of the link types indicated in the mask into clickable links. If the mask is nonzero, it also removes any existing URLSpans attached to the Spannable, to avoid problems if you call it repeatedly on the same text. </para> /// </summary> /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/text/Spannable;I)Z", AccessFlags = 25)] public static bool AddLinks(global::Android.Text.ISpannable text, int mask) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Scans the text of the provided Spannable and turns all occurrences of the link types indicated in the mask into clickable links. If the mask is nonzero, it also removes any existing URLSpans attached to the Spannable, to avoid problems if you call it repeatedly on the same text. </para> /// </summary> /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/widget/TextView;I)Z", AccessFlags = 25)] public static bool AddLinks(global::Android.Widget.TextView text, int mask) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/widget/TextView;Ljava/util/regex/Pattern;Ljava/lang/String;)V", AccessFlags = 25)] public static void AddLinks(global::Android.Widget.TextView textView, global::Java.Util.Regex.Pattern pattern, string @string) /* MethodBuilder.Create */ { } /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/widget/TextView;Ljava/util/regex/Pattern;Ljava/lang/String;Landroid/tex" + "t/util/Linkify$MatchFilter;Landroid/text/util/Linkify$TransformFilter;)V", AccessFlags = 25)] public static void AddLinks(global::Android.Widget.TextView textView, global::Java.Util.Regex.Pattern pattern, string @string, global::Android.Text.Util.Linkify.IMatchFilter matchFilter, global::Android.Text.Util.Linkify.ITransformFilter transformFilter) /* MethodBuilder.Create */ { } /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/text/Spannable;Ljava/util/regex/Pattern;Ljava/lang/String;)Z", AccessFlags = 25)] public static bool AddLinks(global::Android.Text.ISpannable spannable, global::Java.Util.Regex.Pattern pattern, string @string) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/text/Spannable;Ljava/util/regex/Pattern;Ljava/lang/String;Landroid/text" + "/util/Linkify$MatchFilter;Landroid/text/util/Linkify$TransformFilter;)Z", AccessFlags = 25)] public static bool AddLinks(global::Android.Text.ISpannable spannable, global::Java.Util.Regex.Pattern pattern, string @string, global::Android.Text.Util.Linkify.IMatchFilter matchFilter, global::Android.Text.Util.Linkify.ITransformFilter transformFilter) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>TransformFilter enables client code to have more control over how matched patterns are represented as URLs.</para><para>For example: when converting a phone number such as (919) 555-1212 into a tel: URL the parentheses, white space, and hyphen need to be removed to produce tel:9195551212. </para> /// </summary> /// <java-name> /// android/text/util/Linkify$TransformFilter /// </java-name> [Dot42.DexImport("android/text/util/Linkify$TransformFilter", AccessFlags = 1545)] public partial interface ITransformFilter /* scope: __dot42__ */ { /// <summary> /// <para>Examines the matched text and either passes it through or uses the data in the Matcher state to produce a replacement.</para><para></para> /// </summary> /// <returns> /// <para>The transformed form of the URL </para> /// </returns> /// <java-name> /// transformUrl /// </java-name> [Dot42.DexImport("transformUrl", "(Ljava/util/regex/Matcher;Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)] string TransformUrl(global::Java.Util.Regex.Matcher match, string url) /* MethodBuilder.Create */ ; } /// <summary> /// <para>MatchFilter enables client code to have more control over what is allowed to match and become a link, and what is not.</para><para>For example: when matching web urls you would like things like to match, as well as just example.com itelf. However, you would not want to match against the domain in . So, when matching against a web url pattern you might also include a MatchFilter that disallows the match if it is immediately preceded by an at-sign (@). </para> /// </summary> /// <java-name> /// android/text/util/Linkify$MatchFilter /// </java-name> [Dot42.DexImport("android/text/util/Linkify$MatchFilter", AccessFlags = 1545)] public partial interface IMatchFilter /* scope: __dot42__ */ { /// <summary> /// <para>Examines the character span matched by the pattern and determines if the match should be turned into an actionable link.</para><para></para> /// </summary> /// <returns> /// <para>Whether this match should be turned into a link </para> /// </returns> /// <java-name> /// acceptMatch /// </java-name> [Dot42.DexImport("acceptMatch", "(Ljava/lang/CharSequence;II)Z", AccessFlags = 1025)] bool AcceptMatch(global::Java.Lang.ICharSequence s, int start, int end) /* MethodBuilder.Create */ ; } } /// <summary> /// <para>This class works as a Tokenizer for MultiAutoCompleteTextView for address list fields, and also provides a method for converting a string of addresses (such as might be typed into such a field) into a series of Rfc822Tokens. </para> /// </summary> /// <java-name> /// android/text/util/Rfc822Tokenizer /// </java-name> [Dot42.DexImport("android/text/util/Rfc822Tokenizer", AccessFlags = 33)] public partial class Rfc822Tokenizer : global::Android.Widget.MultiAutoCompleteTextView.ITokenizer /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Rfc822Tokenizer() /* MethodBuilder.Create */ { } /// <summary> /// <para>This constructor will try to take a string like "Foo Bar (something) &amp;lt;foo\@google.com&amp;gt;, blah\@google.com (something)" and convert it into one or more Rfc822Tokens, output into the supplied collection.</para><para>It does <b>not</b> decode MIME encoded-words; charset conversion must already have taken place if necessary. It will try to be tolerant of broken syntax instead of returning an error. </para> /// </summary> /// <java-name> /// tokenize /// </java-name> [Dot42.DexImport("tokenize", "(Ljava/lang/CharSequence;Ljava/util/Collection;)V", AccessFlags = 9, Signature = "(Ljava/lang/CharSequence;Ljava/util/Collection<Landroid/text/util/Rfc822Token;>;)" + "V")] public static void Tokenize(global::Java.Lang.ICharSequence text, global::Java.Util.ICollection<global::Android.Text.Util.Rfc822Token> @out) /* MethodBuilder.Create */ { } /// <summary> /// <para>This method will try to take a string like "Foo Bar (something) &amp;lt;foo\@google.com&amp;gt;, blah\@google.com (something)" and convert it into one or more Rfc822Tokens. It does <b>not</b> decode MIME encoded-words; charset conversion must already have taken place if necessary. It will try to be tolerant of broken syntax instead of returning an error. </para> /// </summary> /// <java-name> /// tokenize /// </java-name> [Dot42.DexImport("tokenize", "(Ljava/lang/CharSequence;)[Landroid/text/util/Rfc822Token;", AccessFlags = 9)] public static global::Android.Text.Util.Rfc822Token[] Tokenize(global::Java.Lang.ICharSequence text) /* MethodBuilder.Create */ { return default(global::Android.Text.Util.Rfc822Token[]); } /// <summary> /// <para><para>Returns the start of the token that ends at offset <code>cursor</code> within <code>text</code>.</para> </para> /// </summary> /// <java-name> /// findTokenStart /// </java-name> [Dot42.DexImport("findTokenStart", "(Ljava/lang/CharSequence;I)I", AccessFlags = 1)] public virtual int FindTokenStart(global::Java.Lang.ICharSequence text, int cursor) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para><para>Returns the end of the token (minus trailing punctuation) that begins at offset <code>cursor</code> within <code>text</code>.</para> </para> /// </summary> /// <java-name> /// findTokenEnd /// </java-name> [Dot42.DexImport("findTokenEnd", "(Ljava/lang/CharSequence;I)I", AccessFlags = 1)] public virtual int FindTokenEnd(global::Java.Lang.ICharSequence text, int cursor) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Terminates the specified address with a comma and space. This assumes that the specified text already has valid syntax. The Adapter subclass's convertToString() method must make that guarantee. </para> /// </summary> /// <java-name> /// terminateToken /// </java-name> [Dot42.DexImport("terminateToken", "(Ljava/lang/CharSequence;)Ljava/lang/CharSequence;", AccessFlags = 1)] public virtual global::Java.Lang.ICharSequence TerminateToken(global::Java.Lang.ICharSequence text) /* MethodBuilder.Create */ { return default(global::Java.Lang.ICharSequence); } } /// <summary> /// <para>This class stores an RFC 822-like name, address, and comment, and provides methods to convert them to quoted strings. </para> /// </summary> /// <java-name> /// android/text/util/Rfc822Token /// </java-name> [Dot42.DexImport("android/text/util/Rfc822Token", AccessFlags = 33)] public partial class Rfc822Token /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new Rfc822Token with the specified name, address, and comment. </para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public Rfc822Token(string name, string address, string comment) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the name part. </para> /// </summary> /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the address part. </para> /// </summary> /// <java-name> /// getAddress /// </java-name> [Dot42.DexImport("getAddress", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetAddress() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the comment part. </para> /// </summary> /// <java-name> /// getComment /// </java-name> [Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetComment() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Changes the name to the specified name. </para> /// </summary> /// <java-name> /// setName /// </java-name> [Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetName(string name) /* MethodBuilder.Create */ { } /// <summary> /// <para>Changes the address to the specified address. </para> /// </summary> /// <java-name> /// setAddress /// </java-name> [Dot42.DexImport("setAddress", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetAddress(string address) /* MethodBuilder.Create */ { } /// <summary> /// <para>Changes the comment to the specified comment. </para> /// </summary> /// <java-name> /// setComment /// </java-name> [Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetComment(string comment) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the name (with quoting added if necessary), the comment (in parentheses), and the address (in angle brackets). This should be suitable for inclusion in an RFC 822 address list. </para> /// </summary> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the name, conservatively quoting it if there are any characters that are likely to cause trouble outside of a quoted string, or returning it literally if it seems safe. </para> /// </summary> /// <java-name> /// quoteNameIfNecessary /// </java-name> [Dot42.DexImport("quoteNameIfNecessary", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string QuoteNameIfNecessary(string name) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the name, with internal backslashes and quotation marks preceded by backslashes. The outer quote marks themselves are not added by this method. </para> /// </summary> /// <java-name> /// quoteName /// </java-name> [Dot42.DexImport("quoteName", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string QuoteName(string name) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the comment, with internal backslashes and parentheses preceded by backslashes. The outer parentheses themselves are not added by this method. </para> /// </summary> /// <java-name> /// quoteComment /// </java-name> [Dot42.DexImport("quoteComment", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string QuoteComment(string comment) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object o) /* MethodBuilder.Create */ { return default(bool); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal Rfc822Token() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the name part. </para> /// </summary> /// <java-name> /// getName /// </java-name> public string Name { [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetName(); } [Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetName(value); } } /// <summary> /// <para>Returns the address part. </para> /// </summary> /// <java-name> /// getAddress /// </java-name> public string Address { [Dot42.DexImport("getAddress", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetAddress(); } [Dot42.DexImport("setAddress", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetAddress(value); } } /// <summary> /// <para>Returns the comment part. </para> /// </summary> /// <java-name> /// getComment /// </java-name> public string Comment { [Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetComment(); } [Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetComment(value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.PortableExecutable { public class ManagedPEBuilder : PEBuilder { public const int ManagedResourcesDataAlignment = ManagedTextSection.ManagedResourcesDataAlignment; public const int MappedFieldDataAlignment = ManagedTextSection.MappedFieldDataAlignment; private const int DefaultStrongNameSignatureSize = 128; private const string TextSectionName = ".text"; private const string ResourceSectionName = ".rsrc"; private const string RelocationSectionName = ".reloc"; private readonly PEDirectoriesBuilder _peDirectoriesBuilder; private readonly MetadataRootBuilder _metadataRootBuilder; private readonly BlobBuilder _ilStream; private readonly BlobBuilder _mappedFieldDataOpt; private readonly BlobBuilder _managedResourcesOpt; private readonly ResourceSectionBuilder _nativeResourcesOpt; private readonly int _strongNameSignatureSize; private readonly MethodDefinitionHandle _entryPointOpt; private readonly DebugDirectoryBuilder _debugDirectoryBuilderOpt; private readonly CorFlags _corFlags; private int _lazyEntryPointAddress; private Blob _lazyStrongNameSignature; public ManagedPEBuilder( PEHeaderBuilder header, MetadataRootBuilder metadataRootBuilder, BlobBuilder ilStream, BlobBuilder mappedFieldData = null, BlobBuilder managedResources = null, ResourceSectionBuilder nativeResources = null, DebugDirectoryBuilder debugDirectoryBuilder = null, int strongNameSignatureSize = DefaultStrongNameSignatureSize, MethodDefinitionHandle entryPoint = default(MethodDefinitionHandle), CorFlags flags = CorFlags.ILOnly, Func<IEnumerable<Blob>, BlobContentId> deterministicIdProvider = null) : base(header, deterministicIdProvider) { if (header == null) { Throw.ArgumentNull(nameof(header)); } if (metadataRootBuilder == null) { Throw.ArgumentNull(nameof(metadataRootBuilder)); } if (ilStream == null) { Throw.ArgumentNull(nameof(ilStream)); } if (strongNameSignatureSize < 0) { Throw.ArgumentOutOfRange(nameof(strongNameSignatureSize)); } _metadataRootBuilder = metadataRootBuilder; _ilStream = ilStream; _mappedFieldDataOpt = mappedFieldData; _managedResourcesOpt = managedResources; _nativeResourcesOpt = nativeResources; _strongNameSignatureSize = strongNameSignatureSize; _entryPointOpt = entryPoint; _debugDirectoryBuilderOpt = debugDirectoryBuilder ?? CreateDefaultDebugDirectoryBuilder(); _corFlags = flags; _peDirectoriesBuilder = new PEDirectoriesBuilder(); } private DebugDirectoryBuilder CreateDefaultDebugDirectoryBuilder() { if (IsDeterministic) { var builder = new DebugDirectoryBuilder(); builder.AddReproducibleEntry(); return builder; } return null; } protected override ImmutableArray<Section> CreateSections() { var builder = ImmutableArray.CreateBuilder<Section>(3); builder.Add(new Section(TextSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.MemExecute | SectionCharacteristics.ContainsCode)); if (_nativeResourcesOpt != null) { builder.Add(new Section(ResourceSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.ContainsInitializedData)); } if (Header.Machine == Machine.I386 || Header.Machine == 0) { builder.Add(new Section(RelocationSectionName, SectionCharacteristics.MemRead | SectionCharacteristics.MemDiscardable | SectionCharacteristics.ContainsInitializedData)); } return builder.ToImmutable(); } protected override BlobBuilder SerializeSection(string name, SectionLocation location) => name switch { TextSectionName => SerializeTextSection(location), ResourceSectionName => SerializeResourceSection(location), RelocationSectionName => SerializeRelocationSection(location), _ => throw new ArgumentException(SR.Format(SR.UnknownSectionName, name), nameof(name)), }; private BlobBuilder SerializeTextSection(SectionLocation location) { var sectionBuilder = new BlobBuilder(); var metadataBuilder = new BlobBuilder(); var metadataSizes = _metadataRootBuilder.Sizes; var textSection = new ManagedTextSection( imageCharacteristics: Header.ImageCharacteristics, machine: Header.Machine, ilStreamSize: _ilStream.Count, metadataSize: metadataSizes.MetadataSize, resourceDataSize: _managedResourcesOpt?.Count ?? 0, strongNameSignatureSize: _strongNameSignatureSize, debugDataSize: _debugDirectoryBuilderOpt?.Size ?? 0, mappedFieldDataSize: _mappedFieldDataOpt?.Count ?? 0); int methodBodyStreamRva = location.RelativeVirtualAddress + textSection.OffsetToILStream; int mappedFieldDataStreamRva = location.RelativeVirtualAddress + textSection.CalculateOffsetToMappedFieldDataStream(); _metadataRootBuilder.Serialize(metadataBuilder, methodBodyStreamRva, mappedFieldDataStreamRva); DirectoryEntry debugDirectoryEntry; BlobBuilder debugTableBuilderOpt; if (_debugDirectoryBuilderOpt != null) { int debugDirectoryOffset = textSection.ComputeOffsetToDebugDirectory(); debugTableBuilderOpt = new BlobBuilder(_debugDirectoryBuilderOpt.TableSize); _debugDirectoryBuilderOpt.Serialize(debugTableBuilderOpt, location, debugDirectoryOffset); // Only the size of the fixed part of the debug table goes here. debugDirectoryEntry = new DirectoryEntry( location.RelativeVirtualAddress + debugDirectoryOffset, _debugDirectoryBuilderOpt.TableSize); } else { debugTableBuilderOpt = null; debugDirectoryEntry = default(DirectoryEntry); } _lazyEntryPointAddress = textSection.GetEntryPointAddress(location.RelativeVirtualAddress); textSection.Serialize( sectionBuilder, location.RelativeVirtualAddress, _entryPointOpt.IsNil ? 0 : MetadataTokens.GetToken(_entryPointOpt), _corFlags, Header.ImageBase, metadataBuilder, _ilStream, _mappedFieldDataOpt, _managedResourcesOpt, debugTableBuilderOpt, out _lazyStrongNameSignature); _peDirectoriesBuilder.AddressOfEntryPoint = _lazyEntryPointAddress; _peDirectoriesBuilder.DebugTable = debugDirectoryEntry; _peDirectoriesBuilder.ImportAddressTable = textSection.GetImportAddressTableDirectoryEntry(location.RelativeVirtualAddress); _peDirectoriesBuilder.ImportTable = textSection.GetImportTableDirectoryEntry(location.RelativeVirtualAddress); _peDirectoriesBuilder.CorHeaderTable = textSection.GetCorHeaderDirectoryEntry(location.RelativeVirtualAddress); return sectionBuilder; } private BlobBuilder SerializeResourceSection(SectionLocation location) { Debug.Assert(_nativeResourcesOpt != null); var sectionBuilder = new BlobBuilder(); _nativeResourcesOpt.Serialize(sectionBuilder, location); _peDirectoriesBuilder.ResourceTable = new DirectoryEntry(location.RelativeVirtualAddress, sectionBuilder.Count); return sectionBuilder; } private BlobBuilder SerializeRelocationSection(SectionLocation location) { var sectionBuilder = new BlobBuilder(); WriteRelocationSection(sectionBuilder, Header.Machine, _lazyEntryPointAddress); _peDirectoriesBuilder.BaseRelocationTable = new DirectoryEntry(location.RelativeVirtualAddress, sectionBuilder.Count); return sectionBuilder; } private static void WriteRelocationSection(BlobBuilder builder, Machine machine, int entryPointAddress) { Debug.Assert(builder.Count == 0); builder.WriteUInt32((((uint)entryPointAddress + 2) / 0x1000) * 0x1000); builder.WriteUInt32((machine == Machine.IA64) ? 14u : 12u); uint offsetWithinPage = ((uint)entryPointAddress + 2) % 0x1000; uint relocType = (machine == Machine.Amd64 || machine == Machine.IA64 || machine == Machine.Arm64) ? 10u : 3u; ushort s = (ushort)((relocType << 12) | offsetWithinPage); builder.WriteUInt16(s); if (machine == Machine.IA64) { builder.WriteUInt32(relocType << 12); } builder.WriteUInt16(0); // next chunk's RVA } protected internal override PEDirectoriesBuilder GetDirectories() { return _peDirectoriesBuilder; } public void Sign(BlobBuilder peImage, Func<IEnumerable<Blob>, byte[]> signatureProvider) { if (peImage == null) { Throw.ArgumentNull(nameof(peImage)); } if (signatureProvider == null) { Throw.ArgumentNull(nameof(signatureProvider)); } Sign(peImage, _lazyStrongNameSignature, signatureProvider); } } }
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Text; namespace Python.Runtime { /// <summary> /// Base class for Python types that reflect managed exceptions based on /// System.Exception /// </summary> /// <remarks> /// The Python wrapper for managed exceptions LIES about its inheritance /// tree. Although the real System.Exception is a subclass of /// System.Object the Python type for System.Exception does NOT claim that /// it subclasses System.Object. Instead TypeManager.CreateType() uses /// Python's exception.Exception class as base class for System.Exception. /// </remarks> [Serializable] internal class ExceptionClassObject : ClassObject { internal ExceptionClassObject(Type tp) : base(tp) { } internal static Exception ToException(IntPtr ob) { var co = GetManagedObject(ob) as CLRObject; if (co == null) { return null; } var e = co.inst as Exception; if (e == null) { return null; } return e; } /// <summary> /// Exception __repr__ implementation /// </summary> public new static IntPtr tp_repr(IntPtr ob) { Exception e = ToException(ob); if (e == null) { return Exceptions.RaiseTypeError("invalid object"); } string name = e.GetType().Name; string message; if (e.Message != String.Empty) { message = String.Format("{0}('{1}')", name, e.Message); } else { message = String.Format("{0}()", name); } return Runtime.PyUnicode_FromString(message); } /// <summary> /// Exception __str__ implementation /// </summary> public new static IntPtr tp_str(IntPtr ob) { Exception e = ToException(ob); if (e == null) { return Exceptions.RaiseTypeError("invalid object"); } string message = e.ToString(); string fullTypeName = e.GetType().FullName; string prefix = fullTypeName + ": "; if (message.StartsWith(prefix)) { message = message.Substring(prefix.Length); } else if (message.StartsWith(fullTypeName)) { message = message.Substring(fullTypeName.Length); } return Runtime.PyUnicode_FromString(message); } } /// <summary> /// Encapsulates the Python exception APIs. /// </summary> /// <remarks> /// Readability of the Exceptions class improvements as we look toward version 2.7 ... /// </remarks> public static class Exceptions { internal static IntPtr warnings_module; internal static IntPtr exceptions_module; /// <summary> /// Initialization performed on startup of the Python runtime. /// </summary> internal static void Initialize() { string exceptionsModuleName = "builtins"; exceptions_module = Runtime.PyImport_ImportModule(exceptionsModuleName); Exceptions.ErrorCheck(exceptions_module); warnings_module = Runtime.PyImport_ImportModule("warnings"); Exceptions.ErrorCheck(warnings_module); Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { IntPtr op = Runtime.PyObject_GetAttrString(exceptions_module, fi.Name); if (op != IntPtr.Zero) { fi.SetValue(type, op); } else { fi.SetValue(type, IntPtr.Zero); DebugUtil.Print($"Unknown exception: {fi.Name}"); } } Runtime.PyErr_Clear(); } /// <summary> /// Cleanup resources upon shutdown of the Python runtime. /// </summary> internal static void Shutdown() { if (Runtime.Py_IsInitialized() == 0) { return; } Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { var op = (IntPtr)fi.GetValue(type); if (op == IntPtr.Zero) { continue; } Runtime.XDecref(op); fi.SetValue(null, IntPtr.Zero); } Runtime.Py_CLEAR(ref exceptions_module); Runtime.Py_CLEAR(ref warnings_module); } /// <summary> /// Set the 'args' slot on a python exception object that wraps /// a CLR exception. This is needed for pickling CLR exceptions as /// BaseException_reduce will only check the slots, bypassing the /// __getattr__ implementation, and thus dereferencing a NULL /// pointer. /// </summary> /// <param name="ob">The python object wrapping </param> internal static void SetArgsAndCause(IntPtr ob) { // e: A CLR Exception Exception e = ExceptionClassObject.ToException(ob); if (e == null) { return; } IntPtr args; if (!string.IsNullOrEmpty(e.Message)) { args = Runtime.PyTuple_New(1); IntPtr msg = Runtime.PyUnicode_FromString(e.Message); Runtime.PyTuple_SetItem(args, 0, msg); } else { args = Runtime.PyTuple_New(0); } Marshal.WriteIntPtr(ob, ExceptionOffset.args, args); if (e.InnerException != null) { // Note: For an AggregateException, InnerException is only the first of the InnerExceptions. IntPtr cause = CLRObject.GetInstHandle(e.InnerException); Marshal.WriteIntPtr(ob, ExceptionOffset.cause, cause); } } /// <summary> /// Shortcut for (pointer == NULL) -&gt; throw PythonException /// </summary> /// <param name="pointer">Pointer to a Python object</param> internal static void ErrorCheck(BorrowedReference pointer) { if (pointer.IsNull) { throw new PythonException(); } } internal static void ErrorCheck(IntPtr pointer) => ErrorCheck(new BorrowedReference(pointer)); /// <summary> /// Shortcut for (pointer == NULL or ErrorOccurred()) -&gt; throw PythonException /// </summary> internal static void ErrorOccurredCheck(IntPtr pointer) { if (pointer == IntPtr.Zero || ErrorOccurred()) { throw new PythonException(); } } /// <summary> /// ExceptionMatches Method /// </summary> /// <remarks> /// Returns true if the current Python exception matches the given /// Python object. This is a wrapper for PyErr_ExceptionMatches. /// </remarks> public static bool ExceptionMatches(IntPtr ob) { return Runtime.PyErr_ExceptionMatches(ob) != 0; } /// <summary> /// ExceptionMatches Method /// </summary> /// <remarks> /// Returns true if the given Python exception matches the given /// Python object. This is a wrapper for PyErr_GivenExceptionMatches. /// </remarks> public static bool ExceptionMatches(IntPtr exc, IntPtr ob) { int i = Runtime.PyErr_GivenExceptionMatches(exc, ob); return i != 0; } /// <summary> /// SetError Method /// </summary> /// <remarks> /// Sets the current Python exception given a native string. /// This is a wrapper for the Python PyErr_SetString call. /// </remarks> public static void SetError(IntPtr ob, string value) { Runtime.PyErr_SetString(ob, value); } /// <summary> /// SetError Method /// </summary> /// <remarks> /// Sets the current Python exception given a Python object. /// This is a wrapper for the Python PyErr_SetObject call. /// </remarks> public static void SetError(IntPtr type, IntPtr exceptionObject) { Runtime.PyErr_SetObject(new BorrowedReference(type), new BorrowedReference(exceptionObject)); } /// <summary> /// SetError Method /// </summary> /// <remarks> /// Sets the current Python exception given a CLR exception /// object. The CLR exception instance is wrapped as a Python /// object, allowing it to be handled naturally from Python. /// </remarks> public static void SetError(Exception e) { // Because delegates allow arbitrary nesting of Python calling // managed calling Python calling... etc. it is possible that we // might get a managed exception raised that is a wrapper for a // Python exception. In that case we'd rather have the real thing. var pe = e as PythonException; if (pe != null) { Runtime.XIncref(pe.PyType); Runtime.XIncref(pe.PyValue); Runtime.XIncref(pe.PyTB); Runtime.PyErr_Restore(pe.PyType, pe.PyValue, pe.PyTB); return; } IntPtr op = CLRObject.GetInstHandle(e); IntPtr etype = Runtime.PyObject_GetAttr(op, PyIdentifier.__class__); Runtime.PyErr_SetObject(new BorrowedReference(etype), new BorrowedReference(op)); Runtime.XDecref(etype); Runtime.XDecref(op); } /// <summary> /// When called after SetError, sets the cause of the error. /// </summary> /// <param name="cause">The cause of the current error</param> public static void SetCause(PythonException cause) { var currentException = new PythonException(); currentException.Normalize(); cause.Normalize(); Runtime.XIncref(cause.PyValue); Runtime.PyException_SetCause(currentException.PyValue, cause.PyValue); currentException.Restore(); } /// <summary> /// ErrorOccurred Method /// </summary> /// <remarks> /// Returns true if an exception occurred in the Python runtime. /// This is a wrapper for the Python PyErr_Occurred call. /// </remarks> public static bool ErrorOccurred() { return Runtime.PyErr_Occurred() != IntPtr.Zero; } /// <summary> /// Clear Method /// </summary> /// <remarks> /// Clear any exception that has been set in the Python runtime. /// </remarks> public static void Clear() { Runtime.PyErr_Clear(); } //==================================================================== // helper methods for raising warnings //==================================================================== /// <summary> /// Alias for Python's warnings.warn() function. /// </summary> public static void warn(string message, IntPtr exception, int stacklevel) { if (exception == IntPtr.Zero || (Runtime.PyObject_IsSubclass(exception, Exceptions.Warning) != 1)) { Exceptions.RaiseTypeError("Invalid exception"); } Runtime.XIncref(warnings_module); IntPtr warn = Runtime.PyObject_GetAttrString(warnings_module, "warn"); Runtime.XDecref(warnings_module); Exceptions.ErrorCheck(warn); IntPtr args = Runtime.PyTuple_New(3); IntPtr msg = Runtime.PyString_FromString(message); Runtime.XIncref(exception); // PyTuple_SetItem steals a reference IntPtr level = Runtime.PyInt_FromInt32(stacklevel); Runtime.PyTuple_SetItem(args, 0, msg); Runtime.PyTuple_SetItem(args, 1, exception); Runtime.PyTuple_SetItem(args, 2, level); IntPtr result = Runtime.PyObject_CallObject(warn, args); Exceptions.ErrorCheck(result); Runtime.XDecref(warn); Runtime.XDecref(result); Runtime.XDecref(args); } public static void warn(string message, IntPtr exception) { warn(message, exception, 1); } public static void deprecation(string message, int stacklevel) { warn(message, Exceptions.DeprecationWarning, stacklevel); } public static void deprecation(string message) { deprecation(message, 1); } //==================================================================== // Internal helper methods for common error handling scenarios. //==================================================================== /// <summary> /// Raises a TypeError exception and attaches any existing exception as its cause. /// </summary> /// <param name="message">The exception message</param> /// <returns><c>IntPtr.Zero</c></returns> internal static IntPtr RaiseTypeError(string message) { PythonException previousException = null; if (ErrorOccurred()) { previousException = new PythonException(); } Exceptions.SetError(Exceptions.TypeError, message); if (previousException != null) { SetCause(previousException); } return IntPtr.Zero; } // 2010-11-16: Arranged in python (2.6 & 2.7) source header file order /* Predefined exceptions are public static variables on the Exceptions class filled in from the python class using reflection in Initialize() looked up by name, not position. */ public static IntPtr BaseException; public static IntPtr Exception; public static IntPtr StopIteration; public static IntPtr GeneratorExit; public static IntPtr ArithmeticError; public static IntPtr LookupError; public static IntPtr AssertionError; public static IntPtr AttributeError; public static IntPtr EOFError; public static IntPtr FloatingPointError; public static IntPtr EnvironmentError; public static IntPtr IOError; public static IntPtr OSError; public static IntPtr ImportError; public static IntPtr IndexError; public static IntPtr KeyError; public static IntPtr KeyboardInterrupt; public static IntPtr MemoryError; public static IntPtr NameError; public static IntPtr OverflowError; public static IntPtr RuntimeError; public static IntPtr NotImplementedError; public static IntPtr SyntaxError; public static IntPtr IndentationError; public static IntPtr TabError; public static IntPtr ReferenceError; public static IntPtr SystemError; public static IntPtr SystemExit; public static IntPtr TypeError; public static IntPtr UnboundLocalError; public static IntPtr UnicodeError; public static IntPtr UnicodeEncodeError; public static IntPtr UnicodeDecodeError; public static IntPtr UnicodeTranslateError; public static IntPtr ValueError; public static IntPtr ZeroDivisionError; //#ifdef MS_WINDOWS //public static IntPtr WindowsError; //#endif //#ifdef __VMS //public static IntPtr VMSError; //#endif //PyAPI_DATA(PyObject *) PyExc_BufferError; //PyAPI_DATA(PyObject *) PyExc_MemoryErrorInst; //PyAPI_DATA(PyObject *) PyExc_RecursionErrorInst; /* Predefined warning categories */ public static IntPtr Warning; public static IntPtr UserWarning; public static IntPtr DeprecationWarning; public static IntPtr PendingDeprecationWarning; public static IntPtr SyntaxWarning; public static IntPtr RuntimeWarning; public static IntPtr FutureWarning; public static IntPtr ImportWarning; public static IntPtr UnicodeWarning; //PyAPI_DATA(PyObject *) PyExc_BytesWarning; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.UserInterface; using osu.Framework.Platform; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Collections; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets; using osu.Game.Screens.Select; using osu.Game.Tests.Resources; using osuTK.Input; namespace osu.Game.Tests.Visual.SongSelect { public class TestSceneFilterControl : OsuManualInputManagerTestScene { protected override Container<Drawable> Content { get; } = new Container { RelativeSizeAxes = Axes.Both }; private CollectionManager collectionManager; private RulesetStore rulesets; private BeatmapManager beatmapManager; private FilterControl control; [BackgroundDependencyLoader] private void load(GameHost host) { Dependencies.Cache(rulesets = new RealmRulesetStore(Realm)); Dependencies.Cache(beatmapManager = new BeatmapManager(LocalStorage, Realm, rulesets, null, Audio, Resources, host, Beatmap.Default)); Dependencies.Cache(Realm); beatmapManager.Import(TestResources.GetQuickTestBeatmapForImport()).WaitSafely(); base.Content.AddRange(new Drawable[] { collectionManager = new CollectionManager(LocalStorage), Content }); Dependencies.Cache(collectionManager); } [SetUp] public void SetUp() => Schedule(() => { collectionManager.Collections.Clear(); Child = control = new FilterControl { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Height = FilterControl.HEIGHT, }; }); [Test] public void TestEmptyCollectionFilterContainsAllBeatmaps() { assertCollectionDropdownContains("All beatmaps"); assertCollectionHeaderDisplays("All beatmaps"); } [Test] public void TestCollectionAddedToDropdown() { AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } })); AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "2" } })); assertCollectionDropdownContains("1"); assertCollectionDropdownContains("2"); } [Test] public void TestCollectionRemovedFromDropdown() { AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } })); AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "2" } })); AddStep("remove collection", () => collectionManager.Collections.RemoveAt(0)); assertCollectionDropdownContains("1", false); assertCollectionDropdownContains("2"); } [Test] public void TestCollectionRenamed() { AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } })); AddStep("select collection", () => { var dropdown = control.ChildrenOfType<CollectionFilterDropdown>().Single(); dropdown.Current.Value = dropdown.ItemSource.ElementAt(1); }); addExpandHeaderStep(); AddStep("change name", () => collectionManager.Collections[0].Name.Value = "First"); assertCollectionDropdownContains("First"); assertCollectionHeaderDisplays("First"); } [Test] public void TestAllBeatmapFilterDoesNotHaveAddButton() { addExpandHeaderStep(); AddStep("hover all beatmaps", () => InputManager.MoveMouseTo(getAddOrRemoveButton(0))); AddAssert("'All beatmaps' filter does not have add button", () => !getAddOrRemoveButton(0).IsPresent); } [Test] public void TestCollectionFilterHasAddButton() { addExpandHeaderStep(); AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } })); AddStep("hover collection", () => InputManager.MoveMouseTo(getAddOrRemoveButton(1))); AddAssert("collection has add button", () => getAddOrRemoveButton(1).IsPresent); } [Test] public void TestButtonDisabledAndEnabledWithBeatmapChanges() { addExpandHeaderStep(); AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } })); AddStep("select available beatmap", () => Beatmap.Value = beatmapManager.GetWorkingBeatmap(beatmapManager.GetAllUsableBeatmapSets().First().Beatmaps[0])); AddAssert("button enabled", () => getAddOrRemoveButton(1).Enabled.Value); AddStep("set dummy beatmap", () => Beatmap.SetDefault()); AddAssert("button disabled", () => !getAddOrRemoveButton(1).Enabled.Value); } [Test] public void TestButtonChangesWhenAddedAndRemovedFromCollection() { addExpandHeaderStep(); AddStep("select available beatmap", () => Beatmap.Value = beatmapManager.GetWorkingBeatmap(beatmapManager.GetAllUsableBeatmapSets().First().Beatmaps[0])); AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } })); AddAssert("button is plus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.PlusSquare)); AddStep("add beatmap to collection", () => collectionManager.Collections[0].Beatmaps.Add(Beatmap.Value.BeatmapInfo)); AddAssert("button is minus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.MinusSquare)); AddStep("remove beatmap from collection", () => collectionManager.Collections[0].Beatmaps.Clear()); AddAssert("button is plus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.PlusSquare)); } [Test] public void TestButtonAddsAndRemovesBeatmap() { addExpandHeaderStep(); AddStep("select available beatmap", () => Beatmap.Value = beatmapManager.GetWorkingBeatmap(beatmapManager.GetAllUsableBeatmapSets().First().Beatmaps[0])); AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } })); AddAssert("button is plus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.PlusSquare)); addClickAddOrRemoveButtonStep(1); AddAssert("collection contains beatmap", () => collectionManager.Collections[0].Beatmaps.Contains(Beatmap.Value.BeatmapInfo)); AddAssert("button is minus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.MinusSquare)); addClickAddOrRemoveButtonStep(1); AddAssert("collection does not contain beatmap", () => !collectionManager.Collections[0].Beatmaps.Contains(Beatmap.Value.BeatmapInfo)); AddAssert("button is plus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.PlusSquare)); } [Test] public void TestManageCollectionsFilterIsNotSelected() { addExpandHeaderStep(); AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } })); AddStep("select collection", () => { InputManager.MoveMouseTo(getCollectionDropdownItems().ElementAt(1)); InputManager.Click(MouseButton.Left); }); addExpandHeaderStep(); AddStep("click manage collections filter", () => { InputManager.MoveMouseTo(getCollectionDropdownItems().Last()); InputManager.Click(MouseButton.Left); }); AddAssert("collection filter still selected", () => control.CreateCriteria().Collection?.Name.Value == "1"); } private void assertCollectionHeaderDisplays(string collectionName, bool shouldDisplay = true) => AddAssert($"collection dropdown header displays '{collectionName}'", () => shouldDisplay == (control.ChildrenOfType<CollectionFilterDropdown.CollectionDropdownHeader>().Single().ChildrenOfType<SpriteText>().First().Text == collectionName)); private void assertCollectionDropdownContains(string collectionName, bool shouldContain = true) => AddAssert($"collection dropdown {(shouldContain ? "contains" : "does not contain")} '{collectionName}'", // A bit of a roundabout way of going about this, see: https://github.com/ppy/osu-framework/issues/3871 + https://github.com/ppy/osu-framework/issues/3872 () => shouldContain == (getCollectionDropdownItems().Any(i => i.ChildrenOfType<CompositeDrawable>().OfType<IHasText>().First().Text == collectionName))); private IconButton getAddOrRemoveButton(int index) => getCollectionDropdownItems().ElementAt(index).ChildrenOfType<IconButton>().Single(); private void addExpandHeaderStep() => AddStep("expand header", () => { InputManager.MoveMouseTo(control.ChildrenOfType<CollectionFilterDropdown.CollectionDropdownHeader>().Single()); InputManager.Click(MouseButton.Left); }); private void addClickAddOrRemoveButtonStep(int index) => AddStep("click add or remove button", () => { InputManager.MoveMouseTo(getAddOrRemoveButton(index)); InputManager.Click(MouseButton.Left); }); private IEnumerable<Dropdown<CollectionFilterMenuItem>.DropdownMenu.DrawableDropdownMenuItem> getCollectionDropdownItems() => control.ChildrenOfType<CollectionFilterDropdown>().Single().ChildrenOfType<Dropdown<CollectionFilterMenuItem>.DropdownMenu.DrawableDropdownMenuItem>(); } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Numerics; using System.Reflection; // Leave this as it is required by some .NET targets using System.Text; using Scriban.Functions; using Scriban.Helpers; using Scriban.Parsing; using Scriban.Runtime; using Scriban.Syntax; namespace Scriban { #if SCRIBAN_PUBLIC public #else internal #endif partial class TemplateContext { /// <summary> /// Pushes a new object context accessible to the template. This method creates also a new context for local variables. /// </summary> /// <param name="scriptObject">The script object.</param> /// <exception cref="System.ArgumentNullException"></exception> public void PushGlobal(IScriptObject scriptObject) { PushGlobalOnly(scriptObject); PushLocal(); } internal void PushGlobalOnly(IScriptObject scriptObject) { if (scriptObject == null) throw new ArgumentNullException(nameof(scriptObject)); _globalStores.Push(scriptObject); } internal IScriptObject PopGlobalOnly() { if (_globalStores.Count == 1) { throw new InvalidOperationException("Unexpected PopGlobal() not matching a PushGlobal"); } var store = _globalStores.Pop(); return store; } /// <summary> /// Pops the previous object context. This method pops also a local variable context. /// </summary> /// <returns>The previous object context</returns> /// <exception cref="System.InvalidOperationException">Unexpected PopGlobal() not matching a PushGlobal</exception> public IScriptObject PopGlobal() { var store = PopGlobalOnly(); PopLocal(); return store; } public void PushLocal() { PushVariableScope(ScriptVariableScope.Local); } public void PopLocal() { PopVariableScope(ScriptVariableScope.Local); } /// <summary> /// Sets the variable with the specified value. /// </summary> /// <param name="variable">The variable.</param> /// <param name="value">The value.</param> /// <exception cref="System.ArgumentNullException">If variable is null</exception> /// <exception cref="ScriptRuntimeException">If an existing variable is already read-only</exception> public void SetValue(ScriptVariableLoop variable, object value) { if (variable == null) throw new ArgumentNullException(nameof(variable)); if (_currentLocalContext.Loops.Count > 0) { // Try to set the variable var store = _currentLocalContext.Loops.Peek(); if (!store.TrySetValue(this, variable.Span, variable.Name, value, false)) { throw new ScriptRuntimeException(variable.Span, $"Cannot set value on the readonly variable `{variable}`"); // unit test: 105-assign-error2.txt } } else { // unit test: 215-for-special-var-error1.txt throw new ScriptRuntimeException(variable.Span, $"Invalid usage of the loop variable `{variable}` not inside a loop"); } } /// <summary> /// Sets the variable with the specified value. /// </summary> /// <param name="variable">The variable.</param> /// <param name="value">The value.</param> /// <param name="asReadOnly">if set to <c>true</c> the variable set will be read-only.</param> /// <exception cref="System.ArgumentNullException">If variable is null</exception> /// <exception cref="ScriptRuntimeException">If an existing variable is already read-only</exception> public void SetValue(ScriptVariable variable, object value, bool asReadOnly = false) { if (variable == null) throw new ArgumentNullException(nameof(variable)); var finalStore = GetStoreForWrite(variable); // Try to set the variable if (!finalStore.TrySetValue(this, variable.Span, variable.Name, value, asReadOnly)) { throw new ScriptRuntimeException(variable.Span, $"Cannot set value on the readonly variable `{variable}`"); // unit test: 105-assign-error2.txt } } /// <summary> /// Sets the variable with the specified value. /// </summary> /// <param name="variable">The variable.</param> /// <param name="value">The value.</param> /// <param name="asReadOnly">if set to <c>true</c> the variable set will be read-only.</param> /// <param name="force">force setting the value even if it is already readonly</param> /// <exception cref="System.ArgumentNullException">If variable is null</exception> /// <exception cref="ScriptRuntimeException">If an existing variable is already read-only</exception> public void SetValue(ScriptVariable variable, object value, bool asReadOnly, bool force) { if (variable == null) throw new ArgumentNullException(nameof(variable)); var finalStore = GetStoreForWrite(variable); // Try to set the variable if (force) { finalStore.Remove(variable.Name); finalStore.TrySetValue(this, variable.Span, variable.Name, value, asReadOnly); } else if (!finalStore.TrySetValue(this, variable.Span, variable.Name, value, asReadOnly)) { throw new ScriptRuntimeException(variable.Span, $"Cannot set value on the readonly variable `{variable}`"); // unit test: 105-assign-error2.txt } } /// <summary> /// Deletes the variable from the current store. /// </summary> /// <param name="variable">The variable.</param> public void DeleteValue(ScriptVariable variable) { if (variable == null) throw new ArgumentNullException(nameof(variable)); var finalStore = GetStoreForWrite(variable); finalStore.Remove(variable.Name); } /// <summary> /// Sets the variable to read only. /// </summary> /// <param name="variable">The variable.</param> /// <param name="isReadOnly">if set to <c>true</c> the variable will be set to readonly.</param> /// <exception cref="System.ArgumentNullException">If variable is null</exception> /// <remarks> /// This will not throw an exception if a previous variable was readonly. /// </remarks> public void SetReadOnly(ScriptVariable variable, bool isReadOnly = true) { if (variable == null) throw new ArgumentNullException(nameof(variable)); var store = GetStoreForWrite(variable); store.SetReadOnly(variable.Name, isReadOnly); } /// <summary> /// Sets the loop variable with the specified value. /// </summary> /// <param name="variable">The loop variable to set.</param> /// <param name="value">The value.</param> /// <exception cref="System.ArgumentNullException">If target is null</exception> public virtual void SetLoopVariable(ScriptVariable variable, object value) { if (variable == null) throw new ArgumentNullException(nameof(variable)); if (_currentLocalContext.Loops.Count == 0) { throw new InvalidOperationException("Cannot set a loop variable without a loop variable store."); } var store = _currentLocalContext.Loops.Peek(); // Try to set the variable if (!store.TrySetValue(this, variable.Span, variable.Name, value, false)) { throw new ScriptRuntimeException(variable.Span, $"Cannot set value on the variable `{variable}`"); } } private void PushLocalContext(ScriptObject locals = null) { var localContext = _availableLocalContexts.Count > 0 ? _availableLocalContexts.Pop() : new LocalContext(null); localContext.LocalObject = locals; _localContexts.Push(localContext); _currentLocalContext = localContext; } private ScriptObject PopLocalContext() { var oldLocalContext = _localContexts.Pop(); var oldLocals = oldLocalContext.LocalObject; oldLocalContext.LocalObject = null; _availableLocalContexts.Push(oldLocalContext); // There is always an available local context because there is always a global context _currentLocalContext = _localContexts.Peek(); return oldLocals; } /// <summary> /// Gets the value for the specified variable from the current object context/scope. /// </summary> /// <param name="variable">The variable to retrieve the value</param> /// <returns>Value of the variable</returns> public object GetValue(ScriptVariable variable) { if (variable == null) throw new ArgumentNullException(nameof(variable)); var stores = GetStoreForRead(variable); object value = null; foreach (var store in stores) { if (store.TryGetValue(this, variable.Span, variable.Name, out value)) { return value; } } bool found = false; if (TryGetVariable != null) { if (TryGetVariable(this, variable.Span, variable, out value)) { found = true; } } CheckVariableFound(variable, found); return value; } /// <summary> /// Gets the value for the specified global variable from the current object context/scope. /// </summary> /// <param name="variable">The variable to retrieve the value</param> /// <returns>Value of the variable</returns> public object GetValue(ScriptVariableGlobal variable) { if (variable == null) throw new ArgumentNullException(nameof(variable)); object value = null; if (IsInLoop) { var count = _currentLocalContext.Loops.Count; var items = _currentLocalContext.Loops.Items; for (int i = count - 1; i >= 0; i--) { if (items[i].TryGetValue(this, variable.Span, variable.Name, out value)) { return value; } } } { var count = _globalStores.Count; var items = _globalStores.Items; for (int i = count - 1; i >= 0; i--) { if (items[i].TryGetValue(this, variable.Span, variable.Name, out value)) { return value; } } } bool found = false; if (TryGetVariable != null) { if (TryGetVariable(this, variable.Span, variable, out value)) { found = true; } } CheckVariableFound(variable, found); return value; } private IScriptObject GetStoreForWrite(ScriptVariable variable) { var scope = variable.Scope; IScriptObject finalStore = null; switch (scope) { case ScriptVariableScope.Global: // In scientific we always resolve to local storage first IScriptObject storeWithVariable = null; var name = variable.Name; int lastStoreIndex = _globalStores.Count - 1; for (int i = lastStoreIndex; i >= 0; i--) { var store = _globalStores.Items[i]; if (storeWithVariable == null && store.Contains(name)) { storeWithVariable = store; } // We check that for upper store, we actually can write a variable with this name // otherwise we don't allow to create a variable with the same name as a readonly variable if (!store.CanWrite(name)) { var variableType = store == BuiltinObject ? "builtin " : string.Empty; throw new ScriptRuntimeException(variable.Span, $"Cannot set the {variableType}readonly variable `{variable}`"); } } // If we have a store for this variable name use it, otherwise use the first store available. finalStore = storeWithVariable ?? _globalStores.Items[lastStoreIndex]; break; case ScriptVariableScope.Local: if (_currentLocalContext.LocalObject != null) { finalStore = _currentLocalContext.LocalObject; } else if (_globalStores.Count > 0) { finalStore = _globalStores.Peek(); } else { throw new ScriptRuntimeException(variable.Span, $"Invalid usage of the local variable `{variable}` in the current context"); } break; case ScriptVariableScope.Loop: if (_currentLocalContext.Loops.Count > 0) { finalStore = _currentLocalContext.Loops.Peek(); } else { // unit test: 215-for-special-var-error1.txt throw new ScriptRuntimeException(variable.Span, $"Invalid usage of the loop variable `{variable}` not inside a loop"); } break; default: Debug.Assert(false, $"Variable scope `{scope}` is not implemented"); break; } return finalStore; } /// <summary> /// Returns the list of <see cref="ScriptObject"/> depending on the scope of the variable. /// </summary> /// <param name="variable"></param> /// <exception cref="NotImplementedException"></exception> /// <returns>The list of script objects valid for the specified variable scope</returns> private IEnumerable<IScriptObject> GetStoreForRead(ScriptVariable variable) { var scope = variable.Scope; var loopItems = _currentLocalContext.Loops.Items; switch (scope) { case ScriptVariableScope.Global: for (int i = _currentLocalContext.Loops.Count - 1; i >= 0; i--) { yield return loopItems[i]; } for (int i = _globalStores.Count - 1; i >= 0; i--) { yield return _globalStores.Items[i]; } break; case ScriptVariableScope.Local: for (int i = _currentLocalContext.Loops.Count - 1; i >= 0; i--) { yield return loopItems[i]; } if (_currentLocalContext.LocalObject != null) { yield return _currentLocalContext.LocalObject; } else if (_globalStores.Count > 0) { yield return _globalStores.Peek(); } else { throw new ScriptRuntimeException(variable.Span, $"Invalid usage of the local variable `{variable}` in the current context"); } break; case ScriptVariableScope.Loop: if (_currentLocalContext.Loops.Count > 0) { yield return _currentLocalContext.Loops.Peek(); } else { // unit test: 215-for-special-var-error1.txt throw new ScriptRuntimeException(variable.Span, $"Invalid usage of the loop variable `{variable}` not inside a loop"); } break; default: throw new NotImplementedException($"Variable scope `{scope}` is not implemented"); } } private void CheckVariableFound(ScriptVariable variable, bool found) { //ScriptVariable.Arguments is a special "magic" variable which is not always present so ignore this if (StrictVariables && !found && variable != ScriptVariable.Arguments) { throw new ScriptRuntimeException(variable.Span, $"The variable or function `{variable}` was not found"); } } /// <summary> /// Push a new <see cref="ScriptVariableScope"/> for variables /// </summary> /// <param name="scope"></param> private void PushVariableScope(ScriptVariableScope scope) { Debug.Assert(scope != ScriptVariableScope.Global); var store = _availableStores.Count > 0 ? _availableStores.Pop() : new ScriptObject(); if (scope == ScriptVariableScope.Local) { PushLocalContext(store); } else { _currentLocalContext.Loops.Push(store); } } /// <summary> /// Pops a previous <see cref="ScriptVariableScope"/>. /// </summary> /// <param name="scope"></param> private void PopVariableScope(ScriptVariableScope scope) { Debug.Assert(scope != ScriptVariableScope.Global); if (scope == ScriptVariableScope.Local) { var local = PopLocalContext(); local.Clear(); _availableStores.Push(local); } else { if (_currentLocalContext.Loops.Count == 0) { // Should not happen at runtime throw new InvalidOperationException("Invalid number of matching push/pop VariableScope."); } var store = _currentLocalContext.Loops.Pop(); // The store is cleanup once it is pushed back store.Clear(); _availableStores.Push(store); } } private class LocalContext { public LocalContext(ScriptObject localObject) { LocalObject = localObject; Loops = new FastStack<ScriptObject>(4); } public ScriptObject LocalObject; public FastStack<ScriptObject> Loops; } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; public interface ITileMapEditorHost { void BuildIncremental(); void Build(bool force); } [CustomEditor(typeof(tk2dTileMap))] public class tk2dTileMapEditor : Editor, ITileMapEditorHost { tk2dTileMap tileMap { get { return (tk2dTileMap)target; } } tk2dTileMapEditorData editorData; tk2dTileMapSceneGUI sceneGUI; tk2dEditor.BrushRenderer _brushRenderer; tk2dEditor.BrushRenderer brushRenderer { get { if (_brushRenderer == null) _brushRenderer = new tk2dEditor.BrushRenderer(tileMap); return _brushRenderer; } set { if (value != null) { Debug.LogError("Only alloyed to set to null"); return; } if (_brushRenderer != null) { _brushRenderer.Destroy(); _brushRenderer = null; } } } tk2dEditor.BrushBuilder _guiBrushBuilder; tk2dEditor.BrushBuilder guiBrushBuilder { get { if (_guiBrushBuilder == null) _guiBrushBuilder = new tk2dEditor.BrushBuilder(); return _guiBrushBuilder; } set { if (value != null) { Debug.LogError("Only allowed to set to null"); return; } if (_guiBrushBuilder != null) { _guiBrushBuilder = null; } } } int width, height; int partitionSizeX, partitionSizeY; // Sprite collection accessor, cleanup when changed tk2dSpriteCollectionData _spriteCollection = null; tk2dSpriteCollectionData SpriteCollection { get { if (_spriteCollection != tileMap.SpriteCollectionInst) { _spriteCollection = tileMap.SpriteCollectionInst; } return _spriteCollection; } } void OnEnable() { if (Application.isPlaying || !tileMap.AllowEdit) return; LoadTileMapData(); } void OnDestroy() { tk2dGrid.Done(); tk2dEditorSkin.Done(); tk2dPreferences.inst.Save(); tk2dSpriteThumbnailCache.Done(); } void InitEditor() { // Initialize editor LoadTileMapData(); } void OnDisable() { brushRenderer = null; guiBrushBuilder = null; if (sceneGUI != null) { sceneGUI.Destroy(); sceneGUI = null; } if (editorData) { EditorUtility.SetDirty(editorData); } if (tileMap && tileMap.data) { EditorUtility.SetDirty(tileMap.data); } } void LoadTileMapData() { width = tileMap.width; height = tileMap.height; partitionSizeX = tileMap.partitionSizeX; partitionSizeY = tileMap.partitionSizeY; GetEditorData(); if (tileMap.data && editorData && tileMap.Editor__SpriteCollection != null) { // Rebuild the palette editorData.CreateDefaultPalette(tileMap.SpriteCollectionInst, editorData.paletteBrush, editorData.paletteTilesPerRow); } // Rebuild the render utility if (sceneGUI != null) { sceneGUI.Destroy(); } sceneGUI = new tk2dTileMapSceneGUI(this, tileMap, editorData); // Rebuild the brush renderer brushRenderer = null; } public void Build(bool force, bool incremental) { if (force) { //if (buildKey != tileMap.buildKey) //tk2dEditor.TileMap.TileMapUtility.CleanRenderData(tileMap); tk2dTileMap.BuildFlags buildFlags = tk2dTileMap.BuildFlags.EditMode; if (!incremental) buildFlags |= tk2dTileMap.BuildFlags.ForceBuild; tileMap.Build(buildFlags); } } public void Build(bool force) { Build(force, false); } public void BuildIncremental() { Build(true, true); } bool Ready { get { return (tileMap != null && tileMap.data != null && editorData != null & tileMap.Editor__SpriteCollection != null && tileMap.SpriteCollectionInst != null); } } void HighlightTile(Rect rect, Rect tileSize, int tilesPerRow, int x, int y, Color fillColor, Color outlineColor) { Rect highlightRect = new Rect(rect.x + x * tileSize.width, rect.y + y * tileSize.height, tileSize.width, tileSize.height); Vector3[] rectVerts = { new Vector3(highlightRect.x, highlightRect.y, 0), new Vector3(highlightRect.x + highlightRect.width, highlightRect.y, 0), new Vector3(highlightRect.x + highlightRect.width, highlightRect.y + highlightRect.height, 0), new Vector3(highlightRect.x, highlightRect.y + highlightRect.height, 0) }; Handles.DrawSolidRectangleWithOutline(rectVerts, fillColor, outlineColor); } Vector2 tiledataScrollPos = Vector2.zero; int selectedDataTile = -1; void DrawTileDataSetupPanel() { // Sanitize prefabs if (tileMap.data.tilePrefabs == null) tileMap.data.tilePrefabs = new Object[0]; if (tileMap.data.tilePrefabs.Length != SpriteCollection.Count) { System.Array.Resize(ref tileMap.data.tilePrefabs, SpriteCollection.Count); } Rect innerRect = brushRenderer.GetBrushViewRect(editorData.paletteBrush, editorData.paletteTilesPerRow); tiledataScrollPos = BeginHScrollView(tiledataScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f)); innerRect.width *= editorData.brushDisplayScale; innerRect.height *= editorData.brushDisplayScale; tk2dGrid.Draw(innerRect); Rect rect = brushRenderer.DrawBrush(tileMap, editorData.paletteBrush, editorData.brushDisplayScale, true, editorData.paletteTilesPerRow); float displayScale = brushRenderer.LastScale; Rect tileSize = new Rect(0, 0, brushRenderer.TileSizePixels.width * displayScale, brushRenderer.TileSizePixels.height * displayScale); int tilesPerRow = editorData.paletteTilesPerRow; int newSelectedPrefab = selectedDataTile; if (Event.current.type == EventType.MouseUp && rect.Contains(Event.current.mousePosition)) { Vector2 localClickPosition = Event.current.mousePosition - new Vector2(rect.x, rect.y); Vector2 tileLocalPosition = new Vector2(localClickPosition.x / tileSize.width, localClickPosition.y / tileSize.height); int tx = (int)tileLocalPosition.x; int ty = (int)tileLocalPosition.y; newSelectedPrefab = ty * tilesPerRow + tx; } if (Event.current.type == EventType.Repaint) { for (int tileId = 0; tileId < SpriteCollection.Count; ++tileId) { Color noDataFillColor = new Color(0, 0, 0, 0.2f); Color noDataOutlineColor = Color.clear; Color selectedFillColor = new Color(1,0,0,0.05f); Color selectedOutlineColor = Color.red; if (tileMap.data.tilePrefabs[tileId] == null || tileId == selectedDataTile) { Color fillColor = (selectedDataTile == tileId)?selectedFillColor:noDataFillColor; Color outlineColor = (selectedDataTile == tileId)?selectedOutlineColor:noDataOutlineColor; HighlightTile(rect, tileSize, editorData.paletteTilesPerRow, tileId % tilesPerRow, tileId / tilesPerRow, fillColor, outlineColor); } } } EndHScrollView(); if (selectedDataTile >= 0 && selectedDataTile < tileMap.data.tilePrefabs.Length) { tileMap.data.tilePrefabs[selectedDataTile] = EditorGUILayout.ObjectField("Prefab", tileMap.data.tilePrefabs[selectedDataTile], typeof(Object), false); } // Add all additional tilemap data var allTileInfos = tileMap.data.GetOrCreateTileInfo(SpriteCollection.Count); if (selectedDataTile >= 0 && selectedDataTile < allTileInfos.Length) { var tileInfo = allTileInfos[selectedDataTile]; GUILayout.Space(16.0f); tileInfo.stringVal = (tileInfo.stringVal==null)?"":tileInfo.stringVal; tileInfo.stringVal = EditorGUILayout.TextField("String", tileInfo.stringVal); tileInfo.intVal = EditorGUILayout.IntField("Int", tileInfo.intVal); tileInfo.floatVal = EditorGUILayout.FloatField("Float", tileInfo.floatVal); tileInfo.enablePrefabOffset = EditorGUILayout.Toggle("Enable Prefab Offset", tileInfo.enablePrefabOffset); } if (newSelectedPrefab != selectedDataTile) { selectedDataTile = newSelectedPrefab; Repaint(); } } void DrawLayersPanel(bool allowEditing) { GUILayout.BeginVertical(); // constrain selected layer editorData.layer = Mathf.Clamp(editorData.layer, 0, tileMap.data.NumLayers - 1); if (allowEditing) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); tileMap.data.layersFixedZ = GUILayout.Toggle(tileMap.data.layersFixedZ, "Fixed Z", EditorStyles.miniButton, GUILayout.ExpandWidth(false)); if (GUILayout.Button("Add Layer", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { editorData.layer = tk2dEditor.TileMap.TileMapUtility.AddNewLayer(tileMap); } GUILayout.EndHorizontal(); } string zValueLabel = tileMap.data.layersFixedZ ? "Z Value" : "Z Offset"; int numLayers = tileMap.data.NumLayers; int deleteLayer = -1; int moveUp = -1; int moveDown = -1; for (int layer = numLayers - 1; layer >= 0; --layer) { GUILayout.Space(4.0f); if (allowEditing) { GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorHeaderBG); GUILayout.BeginHorizontal(); if (editorData.layer == layer) { string newName = GUILayout.TextField(tileMap.data.Layers[layer].name, EditorStyles.textField, GUILayout.MinWidth(120), GUILayout.ExpandWidth(true)); tileMap.data.Layers[layer].name = newName; } else { if (GUILayout.Button(tileMap.data.Layers[layer].name, EditorStyles.textField, GUILayout.MinWidth(120), GUILayout.ExpandWidth(true))) { editorData.layer = layer; Repaint(); } } GUI.enabled = (layer != 0); if (GUILayout.Button("", tk2dEditorSkin.SimpleButton("btn_down"))) { moveUp = layer; Repaint(); } GUI.enabled = (layer != numLayers - 1); if (GUILayout.Button("", tk2dEditorSkin.SimpleButton("btn_up"))) { moveDown = layer; Repaint(); } GUI.enabled = numLayers > 1; if (GUILayout.Button("", tk2dEditorSkin.GetStyle("TilemapDeleteItem"))) { deleteLayer = layer; Repaint(); } GUI.enabled = true; GUILayout.EndHorizontal(); // Row 2 GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); tk2dGuiUtility.BeginChangeCheck(); tileMap.data.Layers[layer].skipMeshGeneration = !GUILayout.Toggle(!tileMap.data.Layers[layer].skipMeshGeneration, "Render Mesh", EditorStyles.miniButton, GUILayout.ExpandWidth(false)); tileMap.data.Layers[layer].useColor = GUILayout.Toggle(tileMap.data.Layers[layer].useColor, "Color", EditorStyles.miniButton, GUILayout.ExpandWidth(false)); tileMap.data.Layers[layer].generateCollider = GUILayout.Toggle(tileMap.data.Layers[layer].generateCollider, "Collider", EditorStyles.miniButton, GUILayout.ExpandWidth(false)); if (tk2dGuiUtility.EndChangeCheck()) Build(true); GUILayout.EndHorizontal(); // Row 3 tk2dGuiUtility.BeginChangeCheck(); if (layer == 0 && !tileMap.data.layersFixedZ) { GUI.enabled = false; EditorGUILayout.FloatField(zValueLabel, 0.0f); GUI.enabled = true; } else { tileMap.data.Layers[layer].z = EditorGUILayout.FloatField(zValueLabel, tileMap.data.Layers[layer].z); } if (!tileMap.data.layersFixedZ) tileMap.data.Layers[layer].z = Mathf.Max(0, tileMap.data.Layers[layer].z); tileMap.data.Layers[layer].unityLayer = EditorGUILayout.LayerField("Layer", tileMap.data.Layers[layer].unityLayer); tileMap.data.Layers[layer].physicMaterial = (PhysicMaterial)EditorGUILayout.ObjectField("Physic Material", tileMap.data.Layers[layer].physicMaterial, typeof(PhysicMaterial), false); if (tk2dGuiUtility.EndChangeCheck()) Build(true); GUILayout.EndVertical(); } else { GUILayout.BeginHorizontal(tk2dEditorSkin.SC_InspectorHeaderBG); bool layerSelVal = editorData.layer == layer; bool newLayerSelVal = GUILayout.Toggle(layerSelVal, tileMap.data.Layers[layer].name, EditorStyles.toggle, GUILayout.ExpandWidth(true)); if (newLayerSelVal != layerSelVal) { editorData.layer = layer; Repaint(); } GUILayout.FlexibleSpace(); var layerGameObject = tileMap.Layers[layer].gameObject; if (layerGameObject) { bool b = GUILayout.Toggle(tk2dEditorUtility.IsGameObjectActive(layerGameObject), "", tk2dEditorSkin.SimpleCheckbox("icon_eye_inactive", "icon_eye")); if (b != tk2dEditorUtility.IsGameObjectActive(layerGameObject)) tk2dEditorUtility.SetGameObjectActive(layerGameObject, b); } GUILayout.EndHorizontal(); } } if (deleteLayer != -1) { //Undo.RegisterUndo(new Object[] { tileMap, tileMap.data }, "Deleted layer"); tk2dEditor.TileMap.TileMapUtility.DeleteLayer(tileMap, deleteLayer); } if (moveUp != -1) { //Undo.RegisterUndo(new Object[] { tileMap, tileMap.data }, "Moved layer"); tk2dEditor.TileMap.TileMapUtility.MoveLayer(tileMap, moveUp, -1); } if (moveDown != -1) { //Undo.RegisterUndo(new Object[] { tileMap, tileMap.data }, "Moved layer"); tk2dEditor.TileMap.TileMapUtility.MoveLayer(tileMap, moveDown, 1); } GUILayout.EndVertical(); } bool Foldout(ref tk2dTileMapEditorData.SetupMode val, tk2dTileMapEditorData.SetupMode ident, string name) { bool selected = false; if ((val & ident) != 0) selected = true; //GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); bool newSelected = GUILayout.Toggle(selected, name, EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(true)); if (newSelected != selected) { if (selected == false) val = ident; else val = 0; } return newSelected; } int tilePropertiesPreviewIdx = 0; Vector2 paletteSettingsScrollPos = Vector2.zero; void DrawSettingsPanel() { GUILayout.Space(8); // Sprite collection GUILayout.BeginHorizontal(); tk2dSpriteCollectionData newSpriteCollection = tk2dSpriteGuiUtility.SpriteCollectionList("Sprite Collection", tileMap.Editor__SpriteCollection); if (newSpriteCollection != tileMap.Editor__SpriteCollection) { Undo.RegisterSceneUndo("Set TileMap Sprite Collection"); tileMap.Editor__SpriteCollection = newSpriteCollection; newSpriteCollection.InitMaterialIds(); LoadTileMapData(); EditorUtility.SetDirty(tileMap); if (Ready) { Init(tileMap.data); tileMap.ForceBuild(); } } if (tileMap.Editor__SpriteCollection != null && GUILayout.Button(">", EditorStyles.miniButton, GUILayout.Width(19))) { tk2dSpriteCollectionEditorPopup v = EditorWindow.GetWindow( typeof(tk2dSpriteCollectionEditorPopup), false, "Sprite Collection Editor" ) as tk2dSpriteCollectionEditorPopup; string assetPath = AssetDatabase.GUIDToAssetPath(tileMap.Editor__SpriteCollection.spriteCollectionGUID); var spriteCollection = AssetDatabase.LoadAssetAtPath(assetPath, typeof(tk2dSpriteCollection)) as tk2dSpriteCollection; v.SetGeneratorAndSelectedSprite(spriteCollection, tileMap.Editor__SpriteCollection.FirstValidDefinitionIndex); } GUILayout.EndHorizontal(); GUILayout.Space(8); // Tilemap data tk2dTileMapData newData = (tk2dTileMapData)EditorGUILayout.ObjectField("Tile Map Data", tileMap.data, typeof(tk2dTileMapData), false); if (newData != tileMap.data) { Undo.RegisterSceneUndo("Assign TileMap Data"); tileMap.data = newData; LoadTileMapData(); } if (tileMap.data == null) { if (tk2dGuiUtility.InfoBoxWithButtons( "TileMap needs an data object to proceed. " + "Please create one or drag an existing data object into the inspector slot.\n", tk2dGuiUtility.WarningLevel.Info, "Create") != -1) { string assetPath = EditorUtility.SaveFilePanelInProject("Save Tile Map Data", "tileMapData", "asset", ""); if (assetPath.Length > 0) { Undo.RegisterSceneUndo("Create TileMap Data"); tk2dTileMapData tileMapData = ScriptableObject.CreateInstance<tk2dTileMapData>(); AssetDatabase.CreateAsset(tileMapData, assetPath); tileMap.data = tileMapData; EditorUtility.SetDirty(tileMap); Init(tileMapData); LoadTileMapData(); } } } // Editor data tk2dTileMapEditorData newEditorData = (tk2dTileMapEditorData)EditorGUILayout.ObjectField("Editor Data", editorData, typeof(tk2dTileMapEditorData), false); if (newEditorData != editorData) { Undo.RegisterSceneUndo("Assign TileMap Editor Data"); string assetPath = AssetDatabase.GetAssetPath(newEditorData); if (assetPath.Length > 0) { tileMap.editorDataGUID = AssetDatabase.AssetPathToGUID(assetPath); EditorUtility.SetDirty(tileMap); LoadTileMapData(); } } if (editorData == null) { if (tk2dGuiUtility.InfoBoxWithButtons( "TileMap needs an editor data object to proceed. " + "Please create one or drag an existing data object into the inspector slot.\n", tk2dGuiUtility.WarningLevel.Info, "Create") != -1) { string assetPath = EditorUtility.SaveFilePanelInProject("Save Tile Map Editor Data", "tileMapEditorData", "asset", ""); if (assetPath.Length > 0) { Undo.RegisterSceneUndo("Create TileMap Editor Data"); tk2dTileMapEditorData tileMapEditorData = ScriptableObject.CreateInstance<tk2dTileMapEditorData>(); AssetDatabase.CreateAsset(tileMapEditorData, assetPath); tileMap.editorDataGUID = AssetDatabase.AssetPathToGUID(assetPath); EditorUtility.SetDirty(tileMap); LoadTileMapData(); } } } // If not set up, don't bother drawing anything else if (!Ready) return; // this is intentionally read only GUILayout.Space(8); GUILayout.BeginHorizontal(); GUI.enabled = false; EditorGUILayout.ObjectField("Render Data", tileMap.renderData, typeof(GameObject), false); GUI.enabled = true; if (tileMap.renderData != null && GUILayout.Button("Unlink", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { tk2dEditor.TileMap.TileMapUtility.MakeUnique(tileMap); } GUILayout.EndHorizontal(); GUILayout.Space(8); // tile map size if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Dimensions, "Dimensions")) { EditorGUI.indentLevel++; width = Mathf.Clamp(EditorGUILayout.IntField("Width", width), 1, tk2dEditor.TileMap.TileMapUtility.MaxWidth); height = Mathf.Clamp(EditorGUILayout.IntField("Height", height), 1, tk2dEditor.TileMap.TileMapUtility.MaxHeight); partitionSizeX = Mathf.Clamp(EditorGUILayout.IntField("PartitionSizeX", partitionSizeX), 4, 32); partitionSizeY = Mathf.Clamp(EditorGUILayout.IntField("PartitionSizeY", partitionSizeY), 4, 32); // Create a default tilemap with given dimensions if (!tileMap.AreSpritesInitialized()) { tk2dRuntime.TileMap.BuilderUtil.InitDataStore(tileMap); tk2dEditor.TileMap.TileMapUtility.ResizeTileMap(tileMap, width, height, tileMap.partitionSizeX, tileMap.partitionSizeY); } if (width != tileMap.width || height != tileMap.height || partitionSizeX != tileMap.partitionSizeX || partitionSizeY != tileMap.partitionSizeY) { if ((width < tileMap.width || height < tileMap.height)) { tk2dGuiUtility.InfoBox("The new size of the tile map is smaller than the current size." + "Some clipping will occur.", tk2dGuiUtility.WarningLevel.Warning); } GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Apply", EditorStyles.miniButton)) { tk2dEditor.TileMap.TileMapUtility.ResizeTileMap(tileMap, width, height, partitionSizeX, partitionSizeY); } GUILayout.EndHorizontal(); } EditorGUI.indentLevel--; } if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Layers, "Layers")) { EditorGUI.indentLevel++; DrawLayersPanel(true); EditorGUI.indentLevel--; } // tilemap info if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Info, "Info")) { EditorGUI.indentLevel++; int numActiveChunks = 0; if (tileMap.Layers != null) { foreach (var layer in tileMap.Layers) numActiveChunks += layer.NumActiveChunks; } EditorGUILayout.LabelField("Active chunks", numActiveChunks.ToString()); int partitionMemSize = partitionSizeX * partitionSizeY * 4; EditorGUILayout.LabelField("Memory", ((numActiveChunks * partitionMemSize) / 1024).ToString() + "kB" ); int numActiveColorChunks = 0; if (tileMap.ColorChannel != null) numActiveColorChunks += tileMap.ColorChannel.NumActiveChunks; EditorGUILayout.LabelField("Active color chunks", numActiveColorChunks.ToString()); int colorMemSize = (partitionSizeX + 1) * (partitionSizeY + 1) * 4; EditorGUILayout.LabelField("Memory", ((numActiveColorChunks * colorMemSize) / 1024).ToString() + "kB" ); EditorGUI.indentLevel--; } // tile properties if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.TileProperties, "Tile Properties")) { EditorGUI.indentLevel++; // sort method tk2dGuiUtility.BeginChangeCheck(); tileMap.data.tileType = (tk2dTileMapData.TileType)EditorGUILayout.EnumPopup("Tile Type", tileMap.data.tileType); if (tileMap.data.tileType != tk2dTileMapData.TileType.Rectangular) { tk2dGuiUtility.InfoBox("Non-rectangular tile types are still in beta testing.", tk2dGuiUtility.WarningLevel.Info); } tileMap.data.sortMethod = (tk2dTileMapData.SortMethod)EditorGUILayout.EnumPopup("Sort Method", tileMap.data.sortMethod); if (tk2dGuiUtility.EndChangeCheck()) { tileMap.BeginEditMode(); } // reset sizes GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Reset sizes"); GUILayout.FlexibleSpace(); if (GUILayout.Button("Reset", EditorStyles.miniButtonRight)) { Init(tileMap.data); Build(true); } GUILayout.EndHorizontal(); // convert these to pixel units Vector3 texelSize = SpriteCollection.spriteDefinitions[0].texelSize; Vector3 tileOriginPixels = new Vector3(tileMap.data.tileOrigin.x / texelSize.x, tileMap.data.tileOrigin.y / texelSize.y, tileMap.data.tileOrigin.z); Vector3 tileSizePixels = new Vector3(tileMap.data.tileSize.x / texelSize.x, tileMap.data.tileSize.y / texelSize.y, tileMap.data.tileSize.z); Vector3 newTileOriginPixels = EditorGUILayout.Vector3Field("Origin", tileOriginPixels); Vector3 newTileSizePixels = EditorGUILayout.Vector3Field("Size", tileSizePixels); if (newTileOriginPixels != tileOriginPixels || newTileSizePixels != tileSizePixels) { tileMap.data.tileOrigin = new Vector3(newTileOriginPixels.x * texelSize.x, newTileOriginPixels.y * texelSize.y, newTileOriginPixels.z); tileMap.data.tileSize = new Vector3(newTileSizePixels.x * texelSize.x, newTileSizePixels.y * texelSize.y, newTileSizePixels.z); Build(true); } // preview tile origin and size setting Vector2 spritePixelOrigin = Vector2.zero; Vector2 spritePixelSize = Vector2.one; tk2dSpriteDefinition[] spriteDefs = tileMap.SpriteCollectionInst.spriteDefinitions; tk2dSpriteDefinition spriteDef = (tilePropertiesPreviewIdx < spriteDefs.Length) ? spriteDefs[tilePropertiesPreviewIdx] : null; if (!spriteDef.Valid) spriteDef = null; if (spriteDef != null) { spritePixelOrigin = new Vector2(spriteDef.untrimmedBoundsData[0].x / spriteDef.texelSize.x, spriteDef.untrimmedBoundsData[0].y / spriteDef.texelSize.y); spritePixelSize = new Vector2(spriteDef.untrimmedBoundsData[1].x / spriteDef.texelSize.x, spriteDef.untrimmedBoundsData[1].y / spriteDef.texelSize.y); } float zoomFactor = (Screen.width - 32.0f) / (spritePixelSize.x * 2.0f); EditorGUILayout.BeginScrollView(Vector2.zero, GUILayout.Height(spritePixelSize.y * 2.0f * zoomFactor + 32.0f)); Rect innerRect = new Rect(0, 0, spritePixelSize.x * 2.0f * zoomFactor, spritePixelSize.y * 2.0f * zoomFactor); tk2dGrid.Draw(innerRect); if (spriteDef != null) { // Preview tiles tk2dSpriteThumbnailCache.DrawSpriteTexture(new Rect(spritePixelSize.x * 0.5f * zoomFactor, spritePixelSize.y * 0.5f * zoomFactor, spritePixelSize.x * zoomFactor, spritePixelSize.y * zoomFactor), spriteDef); // Preview cursor Vector2 cursorOffset = (spritePixelSize * 0.5f - spritePixelOrigin) * zoomFactor; Vector2 cursorSize = new Vector2(tileSizePixels.x * zoomFactor, tileSizePixels.y * zoomFactor); cursorOffset.x += tileOriginPixels.x * zoomFactor; cursorOffset.y += tileOriginPixels.y * zoomFactor; cursorOffset.x += spritePixelSize.x * 0.5f * zoomFactor; cursorOffset.y += spritePixelSize.y * 0.5f * zoomFactor; float top = spritePixelSize.y * 2.0f * zoomFactor; Vector3[] cursorVerts = new Vector3[] { new Vector3(cursorOffset.x, top - cursorOffset.y, 0), new Vector3(cursorOffset.x + cursorSize.x, top - cursorOffset.y, 0), new Vector3(cursorOffset.x + cursorSize.x, top - (cursorOffset.y + cursorSize.y), 0), new Vector3(cursorOffset.x, top - (cursorOffset.y + cursorSize.y), 0) }; Handles.DrawSolidRectangleWithOutline(cursorVerts, new Color(1.0f, 1.0f, 1.0f, 0.2f), Color.white); } if (GUILayout.Button(new GUIContent("", "Click - preview using different tile"), "label", GUILayout.Width(innerRect.width), GUILayout.Height(innerRect.height))) { int n = spriteDefs.Length; for (int i = 0; i < n; ++i) { if (++tilePropertiesPreviewIdx >= n) tilePropertiesPreviewIdx = 0; if (spriteDefs[tilePropertiesPreviewIdx].Valid) break; } } EditorGUILayout.EndScrollView(); EditorGUI.indentLevel--; } if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.PaletteProperties, "Palette Properties")) { EditorGUI.indentLevel++; int newTilesPerRow = Mathf.Clamp(EditorGUILayout.IntField("Tiles Per Row", editorData.paletteTilesPerRow), 1, SpriteCollection.Count); if (newTilesPerRow != editorData.paletteTilesPerRow) { guiBrushBuilder.Reset(); editorData.paletteTilesPerRow = newTilesPerRow; editorData.CreateDefaultPalette(tileMap.SpriteCollectionInst, editorData.paletteBrush, editorData.paletteTilesPerRow); } GUILayout.BeginHorizontal(); editorData.brushDisplayScale = EditorGUILayout.FloatField("Display Scale", editorData.brushDisplayScale); editorData.brushDisplayScale = Mathf.Clamp(editorData.brushDisplayScale, 1.0f / 16.0f, 4.0f); if (GUILayout.Button("Reset", EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false))) { editorData.brushDisplayScale = 1.0f; Repaint(); } GUILayout.EndHorizontal(); EditorGUILayout.PrefixLabel("Preview"); Rect innerRect = brushRenderer.GetBrushViewRect(editorData.paletteBrush, editorData.paletteTilesPerRow); paletteSettingsScrollPos = BeginHScrollView(paletteSettingsScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f)); innerRect.width *= editorData.brushDisplayScale; innerRect.height *= editorData.brushDisplayScale; tk2dGrid.Draw(innerRect); brushRenderer.DrawBrush(tileMap, editorData.paletteBrush, editorData.brushDisplayScale, true, editorData.paletteTilesPerRow); EndHScrollView(); EditorGUI.indentLevel--; } if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Import, "Import")) { EditorGUI.indentLevel++; if (GUILayout.Button("Import TMX")) { if (tk2dEditor.TileMap.Importer.Import(tileMap, tk2dEditor.TileMap.Importer.Format.TMX)) { Build(true); width = tileMap.width; height = tileMap.height; partitionSizeX = tileMap.partitionSizeX; partitionSizeY = tileMap.partitionSizeY; } } EditorGUI.indentLevel--; } } // Little hack to allow nested scrollviews to behave properly Vector2 hScrollDelta = Vector2.zero; Vector2 BeginHScrollView(Vector2 pos, params GUILayoutOption[] options) { hScrollDelta = Vector2.zero; if (Event.current.type == EventType.ScrollWheel) { hScrollDelta.y = Event.current.delta.y; } return EditorGUILayout.BeginScrollView(pos, options); } void EndHScrollView() { EditorGUILayout.EndScrollView(); if (hScrollDelta != Vector2.zero) { Event.current.type = EventType.ScrollWheel; Event.current.delta = hScrollDelta; } } void DrawColorPaintPanel() { if (!tileMap.HasColorChannel()) { if (GUILayout.Button("Create Color Channel")) { Undo.RegisterUndo(tileMap, "Created Color Channel"); tileMap.CreateColorChannel(); tileMap.BeginEditMode(); } Repaint(); return; } tk2dTileMapToolbar.ColorToolsWindow(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Clear to Color"); if (GUILayout.Button("Clear", GUILayout.ExpandWidth(false))) { tileMap.ColorChannel.Clear(tk2dTileMapToolbar.colorBrushColor); Build(true); } EditorGUILayout.EndHorizontal(); if (tileMap.HasColorChannel()) { EditorGUILayout.Separator(); if (GUILayout.Button("Delete Color Channel")) { Undo.RegisterUndo(tileMap, "Deleted Color Channel"); tileMap.DeleteColorChannel(); tileMap.BeginEditMode(); Repaint(); return; } } } int InlineToolbar(string name, int val, string[] names) { int selectedIndex = val; GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); GUILayout.Label(name, EditorStyles.toolbarButton); GUILayout.FlexibleSpace(); for (int i = 0; i < names.Length; ++i) { bool selected = (i == selectedIndex); bool toggled = GUILayout.Toggle(selected, names[i], EditorStyles.toolbarButton); if (toggled == true) { selectedIndex = i; } } GUILayout.EndHorizontal(); return selectedIndex; } bool showSaveSection = false; bool showLoadSection = false; void DrawLoadSaveBrushSection(tk2dTileMapEditorBrush activeBrush) { // Brush load & save handling bool startedSave = false; bool prevGuiEnabled = GUI.enabled; GUILayout.BeginHorizontal(); if (showLoadSection) GUI.enabled = false; if (GUILayout.Button(showSaveSection?"Cancel":"Save")) { if (showSaveSection == false) startedSave = true; showSaveSection = !showSaveSection; if (showSaveSection) showLoadSection = false; Repaint(); } GUI.enabled = prevGuiEnabled; if (showSaveSection) GUI.enabled = false; if (GUILayout.Button(showLoadSection?"Cancel":"Load")) { showLoadSection = !showLoadSection; if (showLoadSection) showSaveSection = false; } GUI.enabled = prevGuiEnabled; GUILayout.EndHorizontal(); if (showSaveSection) { GUI.SetNextControlName("BrushNameEntry"); activeBrush.name = EditorGUILayout.TextField("Name", activeBrush.name); if (startedSave) GUI.FocusControl("BrushNameEntry"); if (GUILayout.Button("Save")) { if (activeBrush.name.Length == 0) { Debug.LogError("Active brush needs a name"); } else { bool replaced = false; for (int i = 0; i < editorData.brushes.Count; ++i) { if (editorData.brushes[i].name == activeBrush.name) { editorData.brushes[i] = new tk2dTileMapEditorBrush(activeBrush); replaced = true; } } if (!replaced) editorData.brushes.Add(new tk2dTileMapEditorBrush(activeBrush)); showSaveSection = false; } } } if (showLoadSection) { GUILayout.Space(8); if (editorData.brushes.Count == 0) GUILayout.Label("No saved brushes."); GUILayout.BeginVertical(); int deleteBrushId = -1; for (int i = 0; i < editorData.brushes.Count; ++i) { var v = editorData.brushes[i]; GUILayout.BeginHorizontal(); if (GUILayout.Button(v.name, EditorStyles.miniButton)) { showLoadSection = false; editorData.activeBrush = new tk2dTileMapEditorBrush(v); } if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(16))) { deleteBrushId = i; } GUILayout.EndHorizontal(); } if (deleteBrushId != -1) { editorData.brushes.RemoveAt(deleteBrushId); Repaint(); } GUILayout.EndVertical(); } } Vector2 paletteScrollPos = Vector2.zero; Vector2 activeBrushScrollPos = Vector2.zero; void DrawPaintPanel() { var activeBrush = editorData.activeBrush; if (Ready && (activeBrush == null || activeBrush.Empty)) { editorData.InitBrushes(tileMap.SpriteCollectionInst); } // Draw layer selector if (tileMap.data.NumLayers > 1) { GUILayout.BeginVertical(); GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true)); GUILayout.Label("Layers", EditorStyles.toolbarButton); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); DrawLayersPanel(false); EditorGUILayout.Space(); GUILayout.EndVertical(); } #if TK2D_TILEMAP_EXPERIMENTAL DrawLoadSaveBrushSection(activeBrush); #endif // Draw palette if (!showLoadSection && !showSaveSection) { editorData.showPalette = EditorGUILayout.Foldout(editorData.showPalette, "Palette"); if (editorData.showPalette) { // brush name string selectionDesc = ""; if (activeBrush.tiles.Length == 1) { int tile = tk2dRuntime.TileMap.BuilderUtil.GetTileFromRawTile(activeBrush.tiles[0].spriteId); if (tile >= 0 && tile < SpriteCollection.spriteDefinitions.Length) selectionDesc = SpriteCollection.spriteDefinitions[tile].name; } GUILayout.Label(selectionDesc); Rect innerRect = brushRenderer.GetBrushViewRect(editorData.paletteBrush, editorData.paletteTilesPerRow); paletteScrollPos = BeginHScrollView(paletteScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f)); innerRect.width *= editorData.brushDisplayScale; innerRect.height *= editorData.brushDisplayScale; tk2dGrid.Draw(innerRect); // palette Rect rect = brushRenderer.DrawBrush(tileMap, editorData.paletteBrush, editorData.brushDisplayScale, true, editorData.paletteTilesPerRow); float displayScale = brushRenderer.LastScale; Rect tileSize = new Rect(0, 0, brushRenderer.TileSizePixels.width * displayScale, brushRenderer.TileSizePixels.height * displayScale); guiBrushBuilder.HandleGUI(rect, tileSize, editorData.paletteTilesPerRow, tileMap.SpriteCollectionInst, activeBrush); EditorGUILayout.Separator(); EndHScrollView(); } EditorGUILayout.Separator(); } // Draw brush if (!showLoadSection) { editorData.showBrush = EditorGUILayout.Foldout(editorData.showBrush, "Brush"); if (editorData.showBrush) { GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Cursor Tile Opacity"); tk2dTileMapToolbar.workBrushOpacity = EditorGUILayout.Slider(tk2dTileMapToolbar.workBrushOpacity, 0.0f, 1.0f); GUILayout.EndHorizontal(); Rect innerRect = brushRenderer.GetBrushViewRect(editorData.activeBrush, editorData.paletteTilesPerRow); activeBrushScrollPos = BeginHScrollView(activeBrushScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f)); innerRect.width *= editorData.brushDisplayScale; innerRect.height *= editorData.brushDisplayScale; tk2dGrid.Draw(innerRect); brushRenderer.DrawBrush(tileMap, editorData.activeBrush, editorData.brushDisplayScale, false, editorData.paletteTilesPerRow); EndHScrollView(); EditorGUILayout.Separator(); } } } /// <summary> /// Initialize tilemap data to sensible values. /// Mainly, tileSize and tileOffset /// </summary> void Init(tk2dTileMapData tileMapData) { if (tileMap.SpriteCollectionInst != null) { tileMapData.tileSize = tileMap.SpriteCollectionInst.spriteDefinitions[0].untrimmedBoundsData[1]; tileMapData.tileOrigin = this.tileMap.SpriteCollectionInst.spriteDefinitions[0].untrimmedBoundsData[0] - tileMap.SpriteCollectionInst.spriteDefinitions[0].untrimmedBoundsData[1] * 0.5f; } } void GetEditorData() { // Don't guess, load editor data every frame string editorDataPath = AssetDatabase.GUIDToAssetPath(tileMap.editorDataGUID); editorData = Resources.LoadAssetAtPath(editorDataPath, typeof(tk2dTileMapEditorData)) as tk2dTileMapEditorData; } public override void OnInspectorGUI() { if (tk2dEditorUtility.IsPrefab(target)) { tk2dGuiUtility.InfoBox("Editor disabled on prefabs.", tk2dGuiUtility.WarningLevel.Error); return; } if (Application.isPlaying) { tk2dGuiUtility.InfoBox("Editor disabled while game is running.", tk2dGuiUtility.WarningLevel.Error); return; } GetEditorData(); if (tileMap.data == null || editorData == null || tileMap.Editor__SpriteCollection == null) { DrawSettingsPanel(); return; } if (tileMap.renderData != null) { if (tileMap.renderData.transform.position != tileMap.transform.position) { tileMap.renderData.transform.position = tileMap.transform.position; } if (tileMap.renderData.transform.rotation != tileMap.transform.rotation) { tileMap.renderData.transform.rotation = tileMap.transform.rotation; } if (tileMap.renderData.transform.localScale != tileMap.transform.localScale) { tileMap.renderData.transform.localScale = tileMap.transform.localScale; } } if (!tileMap.AllowEdit) { GUILayout.BeginHorizontal(); if (GUILayout.Button("Edit")) { Undo.RegisterSceneUndo("Tilemap Enter Edit Mode"); tileMap.BeginEditMode(); InitEditor(); Repaint(); } if (GUILayout.Button("All", GUILayout.ExpandWidth(false))) { tk2dTileMap[] allTileMaps = Resources.FindObjectsOfTypeAll(typeof(tk2dTileMap)) as tk2dTileMap[]; foreach (var tm in allTileMaps) { if (!EditorUtility.IsPersistent(tm) && !tm.AllowEdit) { tm.BeginEditMode(); EditorUtility.SetDirty(tm); } } InitEditor(); } GUILayout.EndHorizontal(); return; } // Commit GUILayout.BeginHorizontal(); if (GUILayout.Button("Commit")) { Undo.RegisterSceneUndo("Tilemap Leave Edit Mode"); tileMap.EndEditMode(); Repaint(); } if (GUILayout.Button("All", GUILayout.ExpandWidth(false))) { tk2dTileMap[] allTileMaps = Resources.FindObjectsOfTypeAll(typeof(tk2dTileMap)) as tk2dTileMap[]; foreach (var tm in allTileMaps) { if (!EditorUtility.IsPersistent(tm) && tm.AllowEdit) { tm.EndEditMode(); EditorUtility.SetDirty(tm); } } } GUILayout.EndHorizontal(); EditorGUILayout.Separator(); if (tileMap.editorDataGUID.Length > 0 && editorData == null) { // try to load it in LoadTileMapData(); // failed, so the asset is lost if (editorData == null) { tileMap.editorDataGUID = ""; } } if (editorData == null || tileMap.data == null || tileMap.Editor__SpriteCollection == null || !tileMap.AreSpritesInitialized()) { DrawSettingsPanel(); } else { // In case things have changed if (tk2dRuntime.TileMap.BuilderUtil.InitDataStore(tileMap)) Build(true); string[] toolBarButtonNames = System.Enum.GetNames(typeof(tk2dTileMapEditorData.EditMode)); tk2dTileMapEditorData.EditMode newEditMode = (tk2dTileMapEditorData.EditMode)GUILayout.Toolbar((int)editorData.editMode, toolBarButtonNames ); if (newEditMode != editorData.editMode) { // Force updating the scene view when mode changes EditorUtility.SetDirty(target); editorData.editMode = newEditMode; } switch (editorData.editMode) { case tk2dTileMapEditorData.EditMode.Paint: DrawPaintPanel(); break; case tk2dTileMapEditorData.EditMode.Color: DrawColorPaintPanel(); break; case tk2dTileMapEditorData.EditMode.Settings: DrawSettingsPanel(); break; case tk2dTileMapEditorData.EditMode.Data: DrawTileDataSetupPanel(); break; } } } void OnSceneGUI() { if (!Ready) { return; } if (sceneGUI != null) { sceneGUI.OnSceneGUI(); } if (!Application.isPlaying && tileMap.AllowEdit) { // build if necessary if (tk2dRuntime.TileMap.BuilderUtil.InitDataStore(tileMap)) Build(true); else Build(false); } } [MenuItem("GameObject/Create Other/tk2d/TileMap", false, 13850)] static void Create() { tk2dSpriteCollectionData sprColl = null; if (sprColl == null) { // try to inherit from other TileMaps in scene tk2dTileMap sceneTileMaps = GameObject.FindObjectOfType(typeof(tk2dTileMap)) as tk2dTileMap; if (sceneTileMaps) { sprColl = sceneTileMaps.Editor__SpriteCollection; } } if (sprColl == null) { tk2dSpriteCollectionIndex[] spriteCollections = tk2dEditorUtility.GetOrCreateIndex().GetSpriteCollectionIndex(); foreach (var v in spriteCollections) { if (v.managedSpriteCollection) continue; // don't wanna pick a managed one GameObject scgo = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(v.spriteCollectionDataGUID), typeof(GameObject)) as GameObject; var sc = scgo.GetComponent<tk2dSpriteCollectionData>(); if (sc != null && sc.spriteDefinitions != null && sc.spriteDefinitions.Length > 0 && sc.allowMultipleAtlases == false) { sprColl = sc; break; } } if (sprColl == null) { EditorUtility.DisplayDialog("Create TileMap", "Unable to create sprite as no SpriteCollections have been found.", "Ok"); return; } } GameObject go = tk2dEditorUtility.CreateGameObjectInScene("TileMap"); go.transform.position = Vector3.zero; go.transform.rotation = Quaternion.identity; tk2dTileMap tileMap = go.AddComponent<tk2dTileMap>(); tileMap.BeginEditMode(); Selection.activeGameObject = go; Undo.RegisterCreatedObjectUndo(go, "Create TileMap"); } }
/* * 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.IO; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.ScriptEngine.Shared { public class DetectParams { public DetectParams() { Key = UUID.Zero; OffsetPos = new OpenMetaverse.Vector3(); LinkNum = 0; Group = UUID.Zero; Name = String.Empty; Owner = UUID.Zero; Position = new OpenMetaverse.Vector3(); Rotation = new OpenMetaverse.Quaternion(); Type = 0; Velocity = new OpenMetaverse.Vector3(); initializeSurfaceTouch(); } public UUID Key; /// <summary> /// This is the UUID of a bot that is having sensor/listen events /// called on it /// </summary> public UUID BotID; public OpenMetaverse.Vector3 OffsetPos; public int LinkNum; public UUID Group; public string Name; public UUID Owner; public OpenMetaverse.Vector3 Position; public OpenMetaverse.Quaternion Rotation; public int Type; public OpenMetaverse.Vector3 Velocity; private OpenMetaverse.Vector3 touchST; public OpenMetaverse.Vector3 TouchST { get { return touchST; } } private OpenMetaverse.Vector3 touchNormal; public OpenMetaverse.Vector3 TouchNormal { get { return touchNormal; } } private OpenMetaverse.Vector3 touchBinormal; public OpenMetaverse.Vector3 TouchBinormal { get { return touchBinormal; } } private OpenMetaverse.Vector3 touchPos; public OpenMetaverse.Vector3 TouchPos { get { return touchPos; } } private OpenMetaverse.Vector3 touchUV; public OpenMetaverse.Vector3 TouchUV { get { return touchUV; } } private int touchFace; public int TouchFace { get { return touchFace; } } // This can be done in two places including the constructor // so be carefull what gets added here private void initializeSurfaceTouch() { touchST = new OpenMetaverse.Vector3(-1.0f, -1.0f, 0.0f); touchNormal = new OpenMetaverse.Vector3(); touchBinormal = new OpenMetaverse.Vector3(); touchPos = new OpenMetaverse.Vector3(); touchUV = new OpenMetaverse.Vector3(-1.0f, -1.0f, 0.0f); touchFace = -1; } /* * Set up the surface touch detected values */ public SurfaceTouchEventArgs SurfaceTouchArgs { set { if (value == null) { // Initialise to defaults if no value initializeSurfaceTouch(); } else { // Set the values from the touch data provided by the client touchST = value.STCoord; touchUV = value.UVCoord; touchNormal = value.Normal; touchBinormal = value.Binormal; touchPos = value.Position; touchFace = value.FaceIndex; } } } public void Populate(Scene scene) { SceneObjectPart part = scene.GetSceneObjectPart(Key); if (part == null) // Avatar, maybe? { ScenePresence presence = scene.GetScenePresence(Key); if (presence == null) return; Name = presence.Firstname + " " + presence.Lastname; Owner = Key; Position = presence.AbsolutePosition; Rotation = presence.Rotation; Velocity = presence.Velocity; Type = 0x01; // Avatar if (presence.Velocity != Vector3.Zero) Type |= 0x02; // Active Group = presence.ControllingClient.ActiveGroupId; } else //object { part = part.ParentGroup.RootPart; // We detect objects only LinkNum = 0; // Not relevant Group = part.GroupID; Name = part.Name; Owner = part.OwnerID; if (part.Velocity == Vector3.Zero) Type = 0x04; // Passive else Type = 0x02; // Passive foreach (SceneObjectPart p in part.ParentGroup.Children.Values) { if (p.Inventory.ContainsScripts()) { Type |= 0x08; // Scripted break; } } Position = part.AbsolutePosition; Quaternion wr = part.ParentGroup.GroupRotation; Rotation = wr; Velocity = part.Velocity; } } public static DetectParams FromDetectedObject(DetectedObject detobj) { DetectParams parms = new DetectParams(); parms.Key = detobj.keyUUID; parms.Group = detobj.groupUUID; parms.LinkNum = detobj.linkNum; parms.Name = detobj.nameStr; parms.Owner = detobj.ownerUUID; parms.Position = detobj.posVector; parms.Rotation = detobj.rotQuat; parms.Type = detobj.colliderType; parms.Velocity = detobj.velVector; return parms; } } /// <summary> /// Holds all the data required to execute a scripting event. /// </summary> public class EventParams { public EventParams(string eventName, Object[] eventParams, DetectParams[] detectParams) { EventName = eventName; Params = eventParams; DetectParams = detectParams; } public string EventName; public Object[] Params; public DetectParams[] DetectParams; } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Xunit; using HETSAPI; using HETSAPI.Models; using System.Reflection; namespace HETSAPI.Test { /// <summary> /// Class for testing the model Owner /// </summary> public class OwnerModelTests { private readonly Owner instance; /// <summary> /// Setup the test. /// </summary> public OwnerModelTests() { instance = new Owner(); } /// <summary> /// Test an instance of Owner /// </summary> [Fact] public void OwnerInstanceTest() { Assert.IsType<Owner>(instance); } /// <summary> /// Test the property 'Id' /// </summary> [Fact] public void IdTest() { Assert.IsType<int>(instance.Id); } /// <summary> /// Test the property 'OwnerCd' /// </summary> [Fact] public void OwnerCdTest() { // TODO unit test for the property 'OwnerCd' Assert.True(true); } /// <summary> /// Test the property 'OwnerFirstName' /// </summary> [Fact] public void OwnerFirstNameTest() { // TODO unit test for the property 'OwnerFirstName' Assert.True(true); } /// <summary> /// Test the property 'OwnerLastName' /// </summary> [Fact] public void OwnerLastNameTest() { // TODO unit test for the property 'OwnerLastName' Assert.True(true); } /// <summary> /// Test the property 'ContactPerson' /// </summary> [Fact] public void ContactPersonTest() { // TODO unit test for the property 'ContactPerson' Assert.True(true); } /// <summary> /// Test the property 'LocalToArea' /// </summary> [Fact] public void LocalToAreaTest() { // TODO unit test for the property 'LocalToArea' Assert.True(true); } /// <summary> /// Test the property 'MaintenanceContractor' /// </summary> [Fact] public void MaintenanceContractorTest() { // TODO unit test for the property 'MaintenanceContractor' Assert.True(true); } /// <summary> /// Test the property 'Comment' /// </summary> [Fact] public void CommentTest() { // TODO unit test for the property 'Comment' Assert.True(true); } /// <summary> /// Test the property 'WCBNum' /// </summary> [Fact] public void WCBNumTest() { // TODO unit test for the property 'WCBNum' Assert.True(true); } /// <summary> /// Test the property 'WCBExpiryDate' /// </summary> [Fact] public void WCBExpiryDateTest() { // TODO unit test for the property 'WCBExpiryDate' Assert.True(true); } /// <summary> /// Test the property 'CGLCompany' /// </summary> [Fact] public void CGLCompanyTest() { // TODO unit test for the property 'CGLCompany' Assert.True(true); } /// <summary> /// Test the property 'CGLPolicy' /// </summary> [Fact] public void CGLPolicyTest() { // TODO unit test for the property 'CGLPolicy' Assert.True(true); } /// <summary> /// Test the property 'CGLStartDate' /// </summary> [Fact] public void CGLStartDateTest() { // TODO unit test for the property 'CGLStartDate' Assert.True(true); } /// <summary> /// Test the property 'CGLEndDate' /// </summary> [Fact] public void CGLEndDateTest() { // TODO unit test for the property 'CGLEndDate' Assert.True(true); } /// <summary> /// Test the property 'StatusCd' /// </summary> [Fact] public void StatusCdTest() { // TODO unit test for the property 'StatusCd' Assert.True(true); } /// <summary> /// Test the property 'ArchiveCd' /// </summary> [Fact] public void ArchiveCdTest() { // TODO unit test for the property 'ArchiveCd' Assert.True(true); } /// <summary> /// Test the property 'ArchiveReason' /// </summary> [Fact] public void ArchiveReasonTest() { // TODO unit test for the property 'ArchiveReason' Assert.True(true); } /// <summary> /// Test the property 'LocalArea' /// </summary> [Fact] public void LocalAreaTest() { // TODO unit test for the property 'LocalArea' Assert.True(true); } /// <summary> /// Test the property 'PrimaryContact' /// </summary> [Fact] public void PrimaryContactTest() { // TODO unit test for the property 'PrimaryContact' Assert.True(true); } /// <summary> /// Test the property 'Contacts' /// </summary> [Fact] public void ContactsTest() { // TODO unit test for the property 'Contacts' Assert.True(true); } /// <summary> /// Test the property 'Notes' /// </summary> [Fact] public void NotesTest() { // TODO unit test for the property 'Notes' Assert.True(true); } /// <summary> /// Test the property 'Attachments' /// </summary> [Fact] public void AttachmentsTest() { // TODO unit test for the property 'Attachments' Assert.True(true); } /// <summary> /// Test the property 'History' /// </summary> [Fact] public void HistoryTest() { // TODO unit test for the property 'History' Assert.True(true); } /// <summary> /// Test the property 'EquipmentList' /// </summary> [Fact] public void EquipmentListTest() { // TODO unit test for the property 'EquipmentList' Assert.True(true); } } }
// 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 AndSingle() { var test = new SimpleBinaryOpTest__AndSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // 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(); // 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(); // 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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } 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 SimpleBinaryOpTest__AndSingle { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[ElementCount]; private static Single[] _data2 = new Single[ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single> _dataTable; static SimpleBinaryOpTest__AndSingle() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__AndSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.And( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.And( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.And( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.And), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.And), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.And), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.And(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AndSingle(); var result = Sse.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if ((BitConverter.SingleToInt32Bits(left[0]) & BitConverter.SingleToInt32Bits(right[0])) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((BitConverter.SingleToInt32Bits(left[0]) & BitConverter.SingleToInt32Bits(right[0])) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.And)}<Single>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using BTDB.Buffer; using BTDB.Service; using Xunit; namespace BTDBTest { public class ConnectedServiceTest : IDisposable { PipedTwoChannels _pipedTwoChannels; IService _first; IService _second; public ConnectedServiceTest() { _pipedTwoChannels = new PipedTwoChannels(); _first = new Service(_pipedTwoChannels.First); _second = new Service(_pipedTwoChannels.Second); } public void Dispose() { Disconnect(); _first.Dispose(); _second.Dispose(); } void Disconnect() { _pipedTwoChannels.Disconnect(); } public interface IAdder { int Add(int a, int b); } public class Adder : IAdder { public int Add(int a, int b) { return a + b; } } [Fact] public void BasicTest() { _first.RegisterLocalService(new Adder()); Assert.Equal(3, _second.QueryRemoteService<IAdder>().Add(1, 2)); } public interface IIface1 { int Meth1(string param); string Meth2(); bool Meth3(bool a, bool b); void Meth4(); } public interface IIface1Async { Task<int> Meth1(string param); Task<string> Meth2(); Task<bool> Meth3(bool a, bool b); Task Meth4(); } public class Class1 : Adder, IIface1 { internal bool Meth4Called; public int Meth1(string param) { return param.Length; } public string Meth2() { return "Hello World"; } public bool Meth3(bool a, bool b) { return a && b; } public void Meth4() { Meth4Called = true; } } [Fact] public void ServiceWithIAdderAndIIface1() { var service = new Class1(); _first.RegisterLocalService(service); Assert.Equal(5, _second.QueryRemoteService<IAdder>().Add(10000, -9995)); var i1 = _second.QueryRemoteService<IIface1>(); Assert.Equal(2, i1.Meth1("Hi")); Assert.Equal("Hello World", i1.Meth2()); Assert.True(i1.Meth3(true, true)); i1.Meth4(); Assert.True(service.Meth4Called); } [Fact] public void OnNewServiceNotification() { var service = new Class1(); var remoteServiceNames = new List<string>(); _second.OnNewRemoteService.Subscribe(remoteServiceNames.Add); _first.RegisterLocalService(service); remoteServiceNames.Sort(); Assert.Equal(new List<string> { "Class1", "IAdder", "IIface1" }, remoteServiceNames); } [Fact] public void AutomaticConversionToAsyncIface() { var service = new Class1(); _first.RegisterLocalService(service); var i1 = _second.QueryRemoteService<IIface1Async>(); AssertIIface1Async(i1); Assert.True(service.Meth4Called); } static void AssertIIface1Async(IIface1Async i1) { Assert.Equal(2, i1.Meth1("Hi").Result); Assert.Equal("Hello World", i1.Meth2().Result); Assert.True(i1.Meth3(true, true).Result); i1.Meth4().Wait(); } [Fact] public void DelegateAsService() { _first.RegisterLocalService((Func<double, double, double>)((a, b) => a + b)); var d = _second.QueryRemoteService<Func<double, double, double>>(); AreDoubleEqual(31.0, d(10.5, 20.5), 1e-10); } public class Class1Async : IIface1Async { internal bool Meth4Called; public Task<int> Meth1(string param) { var tco = new TaskCompletionSource<int>(); tco.SetResult(param.Length); return tco.Task; } public Task<string> Meth2() { return Task.Factory.StartNew(() => "Hello World"); } public Task<bool> Meth3(bool a, bool b) { return Task.Factory.StartNew(() => a && b); } public Task Meth4() { return Task.Factory.StartNew(() => { Meth4Called = true; }); } } [Fact] public void AsyncIfaceOnServerSide() { var service = new Class1Async(); _first.RegisterLocalService(service); var i1 = _second.QueryRemoteService<IIface1Async>(); AssertIIface1Async(i1); Assert.True(service.Meth4Called); } [Fact] public void MultipleServicesAndIdentity() { _first.RegisterLocalService(new Adder()); _first.RegisterLocalService(new Class1Async()); var adder = _second.QueryRemoteService<IAdder>(); Assert.Same(adder, _second.QueryRemoteService<IAdder>()); var i1 = _second.QueryRemoteService<IIface1>(); Assert.Same(i1, _second.QueryRemoteService<IIface1>()); } [Fact(Skip = "Does not correctly work on Linux or Debug")] public void ClientServiceDeallocedWhenNotneeded() { _first.RegisterLocalService(new Adder()); var weakAdder = new WeakReference(_second.QueryRemoteService<IAdder>()); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.False(weakAdder.IsAlive); var adder = _second.QueryRemoteService<IAdder>(); Assert.Equal(2, adder.Add(1, 1)); } [Fact] public void IfaceToDelegateConversion() { _first.RegisterLocalService(new Adder()); var adder = _second.QueryRemoteService<Func<int, int, int>>(); Assert.Equal(5, adder(2, 3)); } [Fact] public void DelegateToIfaceConversion() { _first.RegisterLocalService((Func<int, int, int>)((a, b) => a + b)); Assert.Equal(30, _second.QueryRemoteService<IAdder>().Add(10, 20)); } public interface IIface2 { int Invoke(string param); int Invoke(int param); } public class Class2 : IIface2 { public int Invoke(string param) { return param.Length; } public int Invoke(int param) { return param * param; } } [Fact] public void BasicMethodOverloading() { _first.RegisterLocalService(new Class2()); var i2 = _second.QueryRemoteService<IIface2>(); Assert.Equal(9, i2.Invoke(3)); Assert.Equal(2, i2.Invoke("Hi")); } public interface IIface3A { int Invoke(string param, string param2); int Invoke(int param2, int param); } public interface IIface3B { int Invoke(string param2, string param); int Invoke(int param, int param2); } public class Class3 : IIface3A { public int Invoke(string param, string param2) { return param.Length + 2 * (param2 ?? "").Length; } public int Invoke(int param2, int param) { return 2 * param2 + param; } } [Fact] public void ChangingNumberAndOrderOfParameters() { _first.RegisterLocalService(new Class3()); var i2 = _second.QueryRemoteService<IIface2>(); Assert.Equal(3, i2.Invoke(3)); Assert.Equal(2, i2.Invoke("Hi")); var i3 = _second.QueryRemoteService<IIface3A>(); Assert.Equal(10, i3.Invoke(3, 4)); Assert.Equal(8, i3.Invoke("Hi", "Dev")); var i3O = _second.QueryRemoteService<IIface3B>(); Assert.Equal(10, i3O.Invoke(4, 3)); Assert.Equal(7, i3O.Invoke("Hi", "Dev")); } [Fact] public void ByteArraySupport() { _first.RegisterLocalService((Func<byte[], byte[]>)(p => p.AsEnumerable().Reverse().ToArray())); var d = _second.QueryRemoteService<Func<byte[], byte[]>>(); Assert.Equal(new byte[] { 255, 3, 2, 1, 0 }, d(new byte[] { 0, 1, 2, 3, 255 })); } [Fact] public void ByteBufferSupport() { _first.RegisterLocalService((Func<ByteBuffer, ByteBuffer>)(p => ByteBuffer.NewAsync(p.ToByteArray().AsEnumerable().Reverse().ToArray()))); var d = _second.QueryRemoteService<Func<byte[], byte[]>>(); Assert.Equal(new byte[] { 255, 3, 2, 1, 0 }, d(new byte[] { 0, 1, 2, 3, 255 })); } [Fact] public void ByteBufferSupport2() { _first.RegisterLocalService((Func<byte[], byte[]>)(p => p.AsEnumerable().Reverse().ToArray())); var d = _second.QueryRemoteService<Func<ByteBuffer, ByteBuffer>>(); Assert.Equal(new byte[] { 255, 3, 2, 1, 0 }, d(ByteBuffer.NewAsync(new byte[] { 0, 1, 2, 3, 255 })).ToByteArray()); } [Fact] public void SimpleConversion() { _first.RegisterLocalService((Func<int, int>)(p => p * p)); var d = _second.QueryRemoteService<Func<short, string>>(); Assert.Equal("81", d(9)); } [Fact] public void PassingException() { _first.RegisterLocalService((Func<int>)(() => { throw new ArgumentException("msg", "te" + "st"); })); var d = _second.QueryRemoteService<Func<int>>(); var e = Assert.Throws<AggregateException>(() => d()); Assert.Single(e.InnerExceptions); var inner = e.InnerExceptions[0]; Assert.IsType<ArgumentException>(inner); Assert.StartsWith("msg", ((ArgumentException)inner).Message); Assert.Equal("test", ((ArgumentException)inner).ParamName); } [Fact] public void DisconnectionShouldCancelRunningMethods() { var e = new AutoResetEvent(false); _first.RegisterLocalService((Func<Task>)(() => Task.Factory.StartNew(() => e.WaitOne(1000)))); var d = _second.QueryRemoteService<Func<Task>>(); var task = d(); task = task.ContinueWith(t => Assert.True(t.IsCanceled)); Disconnect(); task.Wait(1000); e.Set(); } [Fact] public void SupportIListLongAsParameters() { _first.RegisterLocalService((Func<IList<long>, IList<long>>)(p => p.Reverse().ToList())); var d = _second.QueryRemoteService<Func<IList<long>, IList<long>>>(); Assert.Equal(new List<long> { 3, 2, 1 }, d(new List<long> { 1, 2, 3 })); } [Fact] public void SupportIListIntAsParameters() { _first.RegisterLocalService((Func<IList<int>, IList<int>>)(p => p.Reverse().ToList())); var d = _second.QueryRemoteService<Func<IList<int>, IList<int>>>(); Assert.Equal(new List<int> { 3, 2, 1 }, d(new List<int> { 1, 2, 3 })); } [Fact] public void SupportIDictionaryIntAsParameters() { _first.RegisterLocalService((Func<IDictionary<int, int>, IDictionary<int, int>>)(p => p.ToDictionary(kv => kv.Value, kv => kv.Key))); var d = _second.QueryRemoteService<Func<IDictionary<int, int>, IDictionary<int, int>>>(); Assert.Equal(new Dictionary<int, int> { { 1, 5 }, { 2, 6 }, { 3, 7 } }, d(new Dictionary<int, int> { { 5, 1 }, { 6, 2 }, { 7, 3 } })); } public class SimpleDTO { public string Name { get; set; } public double Number { get; set; } } [Fact] public void SupportSimpleDTOAsParameter() { SimpleDTO received = null; _first.RegisterLocalService((Action<SimpleDTO>)(a => received = a)); var d = _second.QueryRemoteService<Action<SimpleDTO>>(); d(new SimpleDTO { Name = "Text", Number = 3.14 }); Assert.NotNull(received); Assert.Equal("Text", received.Name); AreDoubleEqual(3.14, received.Number, 1e-14); } [Fact] public void SupportSimpleDTOAsResult() { _first.RegisterLocalService((Func<SimpleDTO>)(() => new SimpleDTO { Name = "Text", Number = 3.14 })); var d = _second.QueryRemoteService<Func<SimpleDTO>>(); var received = d(); Assert.NotNull(received); Assert.Equal("Text", received.Name); AreDoubleEqual(3.14, received.Number, 1e-14); } [Fact] public void CanReturnAndRegisterOtherTypes() { _first.RegisterLocalService((Func<object>)(() => new SimpleDTO { Name = "Text", Number = 3.14 })); var d = _second.QueryRemoteService<Func<object>>(); _second.RegisterRemoteType(typeof(SimpleDTO)); var received = (SimpleDTO)d(); Assert.NotNull(received); Assert.Equal("Text", received.Name); AreDoubleEqual(3.14, received.Number, 1e-14); } [Fact] public void CanSendAndRegisterOtherTypes() { SimpleDTO received = null; _first.RegisterLocalService((Action<object>)(r => received = (SimpleDTO)r)); _first.RegisterLocalType(typeof(SimpleDTO)); var d = _second.QueryRemoteService<Action<object>>(); d(new SimpleDTO { Name = "Text", Number = 3.14 }); Assert.NotNull(received); Assert.Equal("Text", received.Name); AreDoubleEqual(3.14, received.Number, 1e-14); } [Fact] public void CanReturnComplexObjectsAsTask() { _first.RegisterLocalService((Func<List<int>, Task<List<int>>>)(p => Task.Factory.StartNew(() => p.AsEnumerable().Reverse().ToList()))); var d = _second.QueryRemoteService<Func<List<int>, Task<List<int>>>>(); Assert.Equal(new List<int> { 3, 2, 1 }, d(new List<int> { 1, 2, 3 }).Result); } void AreDoubleEqual(double expected, double value, double precision) { var diff = Math.Abs(expected - value); Assert.InRange(diff, - precision/2, precision/2); } } }
/* Josip Medved <jmedved@jmedved.com> * www.medo64.com * MIT License */ //2017-04-17: New version. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security; using Microsoft.Win32; namespace Medo.Configuration { /// <summary> /// Handling of recently used file list. /// </summary> [DebuggerDisplay("{Count} files")] public class RecentlyUsed { /// <summary> /// Creates a new instance and maximum of 16 files. /// </summary> public RecentlyUsed() : this(null, 16) { } /// <summary> /// Creates a new instance and maximum of 16 files. /// </summary> /// <param name="fileNames">File path enumeration.</param> public RecentlyUsed(IEnumerable<string> fileNames) : this(fileNames, 16) { } /// <summary> /// Creates new instance with "Default" as group name. /// </summary> /// <param name="fileNames">File path enumeration.</param> /// <param name="maximumCount">Maximum number of items to load or save.</param> /// <exception cref="ArgumentOutOfRangeException">Maximum count must be between 1 and 99.</exception> public RecentlyUsed(IEnumerable<string> fileNames, int maximumCount) { if ((maximumCount < 1) || (maximumCount > 99)) { throw new ArgumentOutOfRangeException(nameof(maximumCount), "Maximum count must be between 1 and 99."); } MaximumCount = maximumCount; if (fileNames != null) { foreach (var fileName in fileNames) { BaseItems.Add(new RecentlyUsedFile(fileName)); if (BaseItems.Count >= MaximumCount) { break; } } } } /// <summary> /// Gets maximum number of files. /// </summary> public int MaximumCount { get; } /// <summary> /// Gets number of file names. /// </summary> public int Count { get { return BaseItems.Count; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private List<RecentlyUsedFile> BaseItems = new List<RecentlyUsedFile>(); /// <summary> /// Gets file at given index. /// </summary> /// <param name="index">Index.</param> public RecentlyUsedFile this[int index] { get { return BaseItems[index]; } } /// <summary> /// Returns each recently used file. /// </summary> public IEnumerable<RecentlyUsedFile> Files { get { foreach (var item in BaseItems) { yield return item; } } } /// <summary> /// Returns file path enumeration. /// </summary> public IEnumerable<string> FileNames { get { foreach (var item in Files) { yield return item.FileName; } } } /// <summary> /// Inserts file name on top of list if one does not exist or moves it to top if one does exist. /// </summary> /// <param name="fileName">File name.</param> public bool Push(string fileName) { RecentlyUsedFile file; try { file = new RecentlyUsedFile(fileName); } catch (ArgumentException) { return false; } BaseItems.Insert(0, file); for (var i = BaseItems.Count - 1; i > 0; i--) { //remove same file if somewhere on the list if (BaseItems[i].Equals(file)) { BaseItems.RemoveAt(i); } } if (BaseItems.Count > MaximumCount) { //limit to maximum count BaseItems.RemoveRange(MaximumCount, BaseItems.Count - MaximumCount); } OnChanged(EventArgs.Empty); return true; } /// <summary> /// Removes all occurrances of given file. /// </summary> /// <param name="fileName">File name.</param> public void Remove(string fileName) { var changed = false; for (var i = BaseItems.Count - 1; i >= 0; i--) { if (BaseItems[i].Equals(fileName)) { BaseItems.RemoveAt(i); changed = true; } } if (changed) { OnChanged(EventArgs.Empty); } } /// <summary> /// Removes all occurrances of given file. /// </summary> /// <param name="file">Recently used file.</param> public void Remove(RecentlyUsedFile file) { var changed = false; for (var i = BaseItems.Count - 1; i >= 0; i--) { if (BaseItems[i].Equals(file)) { BaseItems.RemoveAt(i); changed = true; } } if (changed) { OnChanged(EventArgs.Empty); } } /// <summary> /// Removes all files from list. /// </summary> public void Clear() { if (BaseItems.Count > 0) { BaseItems.Clear(); OnChanged(EventArgs.Empty); } } /// <summary> /// Raises Changed event. /// </summary> public event EventHandler Changed; private void OnChanged(EventArgs e) { Changed?.Invoke(this, e); } } /// <summary> /// Single recent file. /// </summary> public class RecentlyUsedFile { /// <summary> /// Creates a new recently used file. /// </summary> /// <param name="fileName">File name.</param> internal RecentlyUsedFile(string fileName) { FileName = new FileInfo(fileName).FullName; //expand local names Title = HideExtension ? Path.GetFileNameWithoutExtension(FileName) : Path.GetFileName(FileName); } /// <summary> /// Gets full file name. /// </summary> public string FileName { get; } /// <summary> /// Gets title of current file. /// </summary> public string Title { get; } /// <summary> /// Gets if file exists. /// </summary> public bool FileExists { get { try { return File.Exists(FileName); } catch (IOException) { } catch (SecurityException) { } return false; } } /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> /// <param name="obj">The object to compare with the current object.</param> public override bool Equals(object obj) { if (obj is RecentlyUsedFile other) { return string.Equals(FileName, other.FileName, StringComparison.OrdinalIgnoreCase); } if (obj is string otherString) { return string.Equals(FileName, otherString, StringComparison.OrdinalIgnoreCase); } return false; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> public override int GetHashCode() { return FileName.GetHashCode(); } /// <summary> /// Returns a file title. /// </summary> public override string ToString() { return Title; } #if NETSTANDARD1_6 || NETSTANDARD2_0 private static bool HideExtension { get { return false; } } #else private static bool HideExtension { get { try { using (var rk = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced", false)) { if (rk != null) { var valueKind = IsRunningOnMono ? RegistryValueKind.DWord : rk.GetValueKind("HideFileExt"); if (valueKind == RegistryValueKind.DWord) { var hideFileExt = (int)(rk.GetValue("HideFileExt", 1)); return (hideFileExt != 0); } } } } catch (SecurityException) { } catch (IOException) { } //key does not exist return false; } } private static bool IsRunningOnMono { get { return (Type.GetType("Mono.Runtime") != null); } } #endif } }
// FileSystemScanner.cs // // Copyright 2005 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // 2010-08-13 Sky Sanders - Modified for Silverlight 3/4 and Windows Phone 7 using System; #if NET4 using System.Linq; #endif namespace ICSharpCode.SharpZipLib.Core { #region EventArgs /// <summary> /// Event arguments for scanning. /// </summary> internal class ScanEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name.</param> public ScanEventArgs(string name) { name_ = name; } #endregion /// <summary> /// The file or directory name for this event. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating if scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments during processing of a single file or directory. /// </summary> internal class ProgressEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name if known.</param> /// <param name="processed">The number of bytes processed so far</param> /// <param name="target">The total number of bytes to process, 0 if not known</param> public ProgressEventArgs(string name, long processed, long target) { name_ = name; processed_ = processed; target_ = target; } #endregion /// <summary> /// The name for this event if known. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating wether scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } /// <summary> /// Get a percentage representing how much of the <see cref="Target"></see> has been processed /// </summary> /// <value>0.0 to 100.0 percent; 0 if target is not known.</value> public float PercentComplete { get { float result; if (target_ <= 0) { result = 0; } else { result = ((float)processed_ / (float)target_) * 100.0f; } return result; } } /// <summary> /// The number of bytes processed so far /// </summary> public long Processed { get { return processed_; } } /// <summary> /// The number of bytes to process. /// </summary> /// <remarks>Target may be 0 or negative if the value isnt known.</remarks> public long Target { get { return target_; } } #region Instance Fields string name_; long processed_; long target_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments for directories. /// </summary> internal class DirectoryEventArgs : ScanEventArgs { #region Constructors /// <summary> /// Initialize an instance of <see cref="DirectoryEventArgs"></see>. /// </summary> /// <param name="name">The name for this directory.</param> /// <param name="hasMatchingFiles">Flag value indicating if any matching files are contained in this directory.</param> public DirectoryEventArgs(string name, bool hasMatchingFiles) : base (name) { hasMatchingFiles_ = hasMatchingFiles; } #endregion /// <summary> /// Get a value indicating if the directory contains any matching files or not. /// </summary> public bool HasMatchingFiles { get { return hasMatchingFiles_; } } #region Instance Fields bool hasMatchingFiles_; #endregion } /// <summary> /// Arguments passed when scan failures are detected. /// </summary> internal class ScanFailureEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanFailureEventArgs"></see> /// </summary> /// <param name="name">The name to apply.</param> /// <param name="e">The exception to use.</param> public ScanFailureEventArgs(string name, Exception e) { name_ = name; exception_ = e; continueRunning_ = true; } #endregion /// <summary> /// The applicable name. /// </summary> public string Name { get { return name_; } } /// <summary> /// The applicable exception. /// </summary> public Exception Exception { get { return exception_; } } /// <summary> /// Get / set a value indicating wether scanning should continue. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; Exception exception_; bool continueRunning_; #endregion } #endregion #region Delegates /// <summary> /// Delegate invoked before starting to process a directory. /// </summary> internal delegate void ProcessDirectoryHandler(object sender, DirectoryEventArgs e); /// <summary> /// Delegate invoked before starting to process a file. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void ProcessFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked during processing of a file or directory /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void ProgressHandler(object sender, ProgressEventArgs e); /// <summary> /// Delegate invoked when a file has been completely processed. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void CompletedFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked when a directory failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void DirectoryFailureHandler(object sender, ScanFailureEventArgs e); /// <summary> /// Delegate invoked when a file failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> internal delegate void FileFailureHandler(object sender, ScanFailureEventArgs e); #endregion /// <summary> /// FileSystemScanner provides facilities scanning of files and directories. /// </summary> internal class FileSystemScanner { #region Constructors /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="filter">The <see cref="PathFilter">file filter</see> to apply when scanning.</param> public FileSystemScanner(string filter) { fileFilter_ = new PathFilter(filter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter"> directory filter</see> to apply.</param> public FileSystemScanner(string fileFilter, string directoryFilter) { fileFilter_ = new PathFilter(fileFilter); directoryFilter_ = new PathFilter(directoryFilter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter) { fileFilter_ = fileFilter; } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> /// <param name="directoryFilter">The directory <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter, IScanFilter directoryFilter) { fileFilter_ = fileFilter; directoryFilter_ = directoryFilter; } #endregion #region Delegates /// <summary> /// Delegate to invoke when a directory is processed. /// </summary> public ProcessDirectoryHandler ProcessDirectory; /// <summary> /// Delegate to invoke when a file is processed. /// </summary> public ProcessFileHandler ProcessFile; /// <summary> /// Delegate to invoke when processing for a file has finished. /// </summary> public CompletedFileHandler CompletedFile; /// <summary> /// Delegate to invoke when a directory failure is detected. /// </summary> public DirectoryFailureHandler DirectoryFailure; /// <summary> /// Delegate to invoke when a file failure is detected. /// </summary> public FileFailureHandler FileFailure; #endregion /// <summary> /// Raise the DirectoryFailure event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="e">The exception detected.</param> bool OnDirectoryFailure(string directory, Exception e) { DirectoryFailureHandler handler = DirectoryFailure; bool result = (handler != null); if ( result ) { ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); handler(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the FileFailure event. /// </summary> /// <param name="file">The file name.</param> /// <param name="e">The exception detected.</param> bool OnFileFailure(string file, Exception e) { FileFailureHandler handler = FileFailure; bool result = (handler != null); if ( result ){ ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); FileFailure(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the ProcessFile event. /// </summary> /// <param name="file">The file name.</param> void OnProcessFile(string file) { ProcessFileHandler handler = ProcessFile; if ( handler!= null ) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the complete file event /// </summary> /// <param name="file">The file name</param> void OnCompleteFile(string file) { CompletedFileHandler handler = CompletedFile; if (handler != null) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the ProcessDirectory event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="hasMatchingFiles">Flag indicating if the directory has matching files.</param> void OnProcessDirectory(string directory, bool hasMatchingFiles) { ProcessDirectoryHandler handler = ProcessDirectory; if ( handler != null ) { DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Scan a directory. /// </summary> /// <param name="directory">The base directory to scan.</param> /// <param name="recurse">True to recurse subdirectories, false to scan a single directory.</param> public void Scan(string directory, bool recurse) { alive_ = true; ScanDir(directory, recurse); } void ScanDir(string directory, bool recurse) { try { #if NET4 var names = (string[]) System.IO.Directory.EnumerateFiles(directory).ToArray(); #else string[] names = System.IO.Directory.GetFiles(directory); #endif bool hasMatch = false; for (int fileIndex = 0; fileIndex < names.Length; ++fileIndex) { if ( !fileFilter_.IsMatch(names[fileIndex]) ) { names[fileIndex] = null; } else { hasMatch = true; } } OnProcessDirectory(directory, hasMatch); if ( alive_ && hasMatch ) { foreach (string fileName in names) { try { if ( fileName != null ) { OnProcessFile(fileName); if ( !alive_ ) { break; } } } catch (Exception e) { if (!OnFileFailure(fileName, e)) { throw; } } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } if ( alive_ && recurse ) { try { #if NET4 var names = (string[])System.IO.Directory.EnumerateDirectories(directory).ToArray(); #else string[] names = System.IO.Directory.GetDirectories(directory); #endif foreach (string fulldir in names) { if ((directoryFilter_ == null) || (directoryFilter_.IsMatch(fulldir))) { ScanDir(fulldir, true); if ( !alive_ ) { break; } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } } } #region Instance Fields /// <summary> /// The file filter currently in use. /// </summary> IScanFilter fileFilter_; /// <summary> /// The directory filter currently in use. /// </summary> IScanFilter directoryFilter_; /// <summary> /// Flag indicating if scanning should continue running. /// </summary> bool alive_; #endregion } }
using UnityEngine; using UnityEditor; using System; using System.Xml; using System.IO; using System.Collections; using System.Collections.Generic; public class EditorCollectibleList{ public CollectibleListPrefab prefab; public string[] nameList=new string[0]; } public class CollectibleManagerWindow : EditorWindow { static private CollectibleManagerWindow window; private static CollectibleListPrefab prefab; private static List<CollectibleTB> collectibleList=new List<CollectibleTB>(); private static List<int> collectibleIDList=new List<int>(); private CollectibleTB newCollectible=null; public static void Init () { // Get existing open window or if none, make a new one: window = (CollectibleManagerWindow)EditorWindow.GetWindow(typeof (CollectibleManagerWindow)); window.minSize=new Vector2(375, 449); window.maxSize=new Vector2(375, 800); EditorCollectibleList eCollectibleList=LoadCollectible(); prefab=eCollectibleList.prefab; collectibleList=prefab.collectibleList; foreach(CollectibleTB collectible in collectibleList){ collectibleIDList.Add(collectible.prefabID); } } public static EditorCollectibleList LoadCollectible(){ GameObject obj=Resources.Load("PrefabList/CollectibleListPrefab", typeof(GameObject)) as GameObject; if(obj==null) obj=CreatePrefab(); CollectibleListPrefab prefab=obj.GetComponent<CollectibleListPrefab>(); if(prefab==null) prefab=obj.AddComponent<CollectibleListPrefab>(); for(int i=0; i<prefab.collectibleList.Count; i++){ if(prefab.collectibleList[i]==null){ prefab.collectibleList.RemoveAt(i); i-=1; } } string[] nameList=new string[prefab.collectibleList.Count]; for(int i=0; i<prefab.collectibleList.Count; i++){ if(prefab.collectibleList[i]!=null){ nameList[i]=prefab.collectibleList[i].collectibleName; } } EditorCollectibleList eCollectibleList=new EditorCollectibleList(); eCollectibleList.prefab=prefab; eCollectibleList.nameList=nameList; return eCollectibleList; } private static GameObject CreatePrefab(){ GameObject obj=new GameObject(); obj.AddComponent<CollectibleListPrefab>(); GameObject prefab=PrefabUtility.CreatePrefab("Assets/TBTK/Resources/PrefabList/CollectibleListPrefab.prefab", obj, ReplacePrefabOptions.ConnectToPrefab); DestroyImmediate(obj); AssetDatabase.Refresh (); return prefab; } int delete=-1; private Vector2 scrollPos; void OnGUI () { if(window==null) Init(); #if !UNITY_4_3 Undo.SetSnapshotTarget(this, "UnitManagerWindow"); #else Undo.RecordObject(this, "UnitManagerWindow"); #endif int currentItemCount=collectibleList.Count; if(GUI.Button(new Rect(window.position.width-120, 5, 110, 25), "CollectibleEditor")){ this.Close(); CollectibleEditorWindow.Init(); } EditorGUI.LabelField(new Rect(5, 10, 150, 17), "Add new unit:"); newCollectible=(CollectibleTB)EditorGUI.ObjectField(new Rect(100, 10, 150, 17), newCollectible, typeof(CollectibleTB), false); if(newCollectible!=null){ if(!collectibleList.Contains(newCollectible)){ int rand=0; while(collectibleIDList.Contains(rand)) rand+=1; collectibleIDList.Add(rand); newCollectible.prefabID=rand; collectibleList.Add(newCollectible); GUI.changed=true; } newCollectible=null; } if(collectibleList.Count>0){ GUI.Box(new Rect(5, 40, 50, 20), "ID"); GUI.Box(new Rect(5+50-1, 40, 60+1, 20), "Icon"); GUI.Box(new Rect(5+110-1, 40, 160+2, 20), "Name"); GUI.Box(new Rect(5+270, 40, window.position.width-300, 20), ""); } scrollPos = GUI.BeginScrollView(new Rect(5, 60, window.position.width-12, window.position.height-50), scrollPos, new Rect(5, 55, window.position.width-30, 15+((collectibleList.Count))*50)); int row=0; for(int i=0; i<collectibleList.Count; i++){ if(i%2==0) GUI.color=new Color(.8f, .8f, .8f, 1); else GUI.color=Color.white; GUI.Box(new Rect(5, 60+i*49, window.position.width-30, 50), ""); GUI.color=Color.white; if(currentSwapID==i) GUI.color=new Color(.9f, .9f, .0f, 1); if(GUI.Button(new Rect(19, 12+60+i*49, 30, 30), collectibleList[i].prefabID.ToString())){ if(currentSwapID==i) currentSwapID=-1; else if(currentSwapID==-1) currentSwapID=i; else{ SwapCollectible(i); GUI.changed=true; } } if(currentSwapID==i) GUI.color=Color.white; if(collectibleList[i]!=null){ collectibleList[i].icon=(Texture)EditorGUI.ObjectField(new Rect(12+50, 3+60+i*49, 44, 44), collectibleList[i].icon, typeof(Texture), false); collectibleList[i].collectibleName=EditorGUI.TextField(new Rect(5+120, 6+60+i*49, 150, 17), collectibleList[i].collectibleName); EditorGUI.LabelField(new Rect(5+120, 6+60+i*49+20, 150, 17), "Prefab:"); EditorGUI.ObjectField(new Rect(5+165, 6+60+i*49+20, 105, 17), collectibleList[i].gameObject, typeof(GameObject), false); } if(delete!=i){ if(GUI.Button(new Rect(window.position.width-55, 12+60+i*49, 25, 25), "X")){ delete=i; } } else{ GUI.color = Color.red; if(GUI.Button(new Rect(window.position.width-90, 12+60+i*49, 60, 25), "Remove")){ if(currentSwapID==i) currentSwapID=-1; collectibleIDList.Remove(collectibleList[i].prefabID); collectibleList.RemoveAt(i); delete=-1; //~ if(onCreepUpdateE!=null) onCreepUpdateE(); GUI.changed=true; } GUI.color = Color.white; } row+=1; } GUI.EndScrollView(); if(GUI.changed || currentItemCount!=collectibleList.Count){ EditorUtility.SetDirty(prefab); for(int i=0; i<collectibleList.Count; i++) EditorUtility.SetDirty(collectibleList[i]); } #if UNITY_LE_4_3 if (GUI.changed || currentItemCount!=collectibleList.Count){ Undo.CreateSnapshot(); Undo.RegisterSnapshot(); } Undo.ClearSnapshotTarget(); #endif } private int currentSwapID=-1; void SwapCollectible(int ID){ CollectibleTB collectible=collectibleList[currentSwapID]; collectibleList[currentSwapID]=collectibleList[ID]; collectibleList[ID]=collectible; currentSwapID=-1; } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Streams; using Microsoft.Extensions.Options; using Orleans.Configuration; using Azure.Messaging.EventHubs; using Azure.Messaging.EventHubs.Producer; namespace Orleans.ServiceBus.Providers { /// <summary> /// Queue adapter factory which allows the PersistentStreamProvider to use EventHub as its backend persistent event queue. /// </summary> public class EventHubAdapterFactory : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache { private readonly ILoggerFactory loggerFactory; /// <summary> /// Data adapter /// </summary> protected readonly IEventHubDataAdapter dataAdapter; /// <summary> /// Orleans logging /// </summary> protected ILogger logger; /// <summary> /// Framework service provider /// </summary> protected IServiceProvider serviceProvider; /// <summary> /// Stream provider settings /// </summary> private EventHubOptions ehOptions; private EventHubStreamCachePressureOptions cacheOptions; private EventHubReceiverOptions receiverOptions; private StreamStatisticOptions statisticOptions; private StreamCacheEvictionOptions cacheEvictionOptions; private IEventHubQueueMapper streamQueueMapper; private string[] partitionIds; private ConcurrentDictionary<QueueId, EventHubAdapterReceiver> receivers; private EventHubProducerClient client; private ITelemetryProducer telemetryProducer; /// <summary> /// Name of the adapter. Primarily for logging purposes /// </summary> public string Name { get; } /// <summary> /// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time. /// </summary> /// <returns>True if this is a rewindable stream adapter, false otherwise.</returns> public bool IsRewindable => true; /// <summary> /// Direction of this queue adapter: Read, Write or ReadWrite. /// </summary> /// <returns>The direction in which this adapter provides data.</returns> public StreamProviderDirection Direction { get; protected set; } = StreamProviderDirection.ReadWrite; /// <summary> /// Creates a message cache for an eventhub partition. /// </summary> protected Func<string, IStreamQueueCheckpointer<string>, ILoggerFactory, ITelemetryProducer, IEventHubQueueCache> CacheFactory { get; set; } /// <summary> /// Creates a partition checkpointer. /// </summary> private IStreamQueueCheckpointerFactory checkpointerFactory; /// <summary> /// Creates a failure handler for a partition. /// </summary> protected Func<string, Task<IStreamFailureHandler>> StreamFailureHandlerFactory { get; set; } /// <summary> /// Create a queue mapper to map EventHub partitions to queues /// </summary> protected Func<string[], IEventHubQueueMapper> QueueMapperFactory { get; set; } /// <summary> /// Create a receiver monitor to report performance metrics. /// Factory function should return an IEventHubReceiverMonitor. /// </summary> protected Func<EventHubReceiverMonitorDimensions, ILoggerFactory, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory { get; set; } //for testing purpose, used in EventHubGeneratorStreamProvider /// <summary> /// Factory to create a IEventHubReceiver /// </summary> protected Func<EventHubPartitionSettings, string, ILogger, ITelemetryProducer, IEventHubReceiver> EventHubReceiverFactory; internal ConcurrentDictionary<QueueId, EventHubAdapterReceiver> EventHubReceivers { get { return this.receivers; } } internal IEventHubQueueMapper EventHubQueueMapper { get { return this.streamQueueMapper; } } public EventHubAdapterFactory( string name, EventHubOptions ehOptions, EventHubReceiverOptions receiverOptions, EventHubStreamCachePressureOptions cacheOptions, StreamCacheEvictionOptions cacheEvictionOptions, StreamStatisticOptions statisticOptions, IEventHubDataAdapter dataAdapter, IServiceProvider serviceProvider, ITelemetryProducer telemetryProducer, ILoggerFactory loggerFactory) { this.Name = name; this.cacheEvictionOptions = cacheEvictionOptions ?? throw new ArgumentNullException(nameof(cacheEvictionOptions)); this.statisticOptions = statisticOptions ?? throw new ArgumentNullException(nameof(statisticOptions)); this.ehOptions = ehOptions ?? throw new ArgumentNullException(nameof(ehOptions)); this.cacheOptions = cacheOptions?? throw new ArgumentNullException(nameof(cacheOptions)); this.dataAdapter = dataAdapter ?? throw new ArgumentNullException(nameof(dataAdapter)); this.receiverOptions = receiverOptions?? throw new ArgumentNullException(nameof(receiverOptions)); this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer)); this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); } public virtual void Init() { this.receivers = new ConcurrentDictionary<QueueId, EventHubAdapterReceiver>(); this.telemetryProducer = this.serviceProvider.GetService<ITelemetryProducer>(); InitEventHubClient(); if (this.CacheFactory == null) { this.CacheFactory = CreateCacheFactory(this.cacheOptions).CreateCache; } if (this.StreamFailureHandlerFactory == null) { //TODO: Add a queue specific default failure handler with reasonable error reporting. this.StreamFailureHandlerFactory = partition => Task.FromResult<IStreamFailureHandler>(new NoOpStreamDeliveryFailureHandler()); } if (this.QueueMapperFactory == null) { this.QueueMapperFactory = partitions => new EventHubQueueMapper(partitions, this.Name); } if (this.ReceiverMonitorFactory == null) { this.ReceiverMonitorFactory = (dimensions, logger, telemetryProducer) => new DefaultEventHubReceiverMonitor(dimensions, telemetryProducer); } this.logger = this.loggerFactory.CreateLogger($"{this.GetType().FullName}.{this.ehOptions.Path}"); } //should only need checkpointer on silo side, so move its init logic when it is used private void InitCheckpointerFactory() { this.checkpointerFactory = this.serviceProvider.GetRequiredServiceByName<IStreamQueueCheckpointerFactory>(this.Name); } /// <summary> /// Create queue adapter. /// </summary> /// <returns></returns> public async Task<IQueueAdapter> CreateAdapter() { if (this.streamQueueMapper == null) { this.partitionIds = await GetPartitionIdsAsync(); this.streamQueueMapper = this.QueueMapperFactory(this.partitionIds); } return this; } /// <summary> /// Create queue message cache adapter /// </summary> /// <returns></returns> public IQueueAdapterCache GetQueueAdapterCache() { return this; } /// <summary> /// Create queue mapper /// </summary> /// <returns></returns> public IStreamQueueMapper GetStreamQueueMapper() { //TODO: CreateAdapter must be called first. Figure out how to safely enforce this return this.streamQueueMapper; } /// <summary> /// Acquire delivery failure handler for a queue /// </summary> /// <param name="queueId"></param> /// <returns></returns> public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId) { return this.StreamFailureHandlerFactory(this.streamQueueMapper.QueueToPartition(queueId)); } /// <summary> /// Writes a set of events to the queue as a single batch associated with the provided streamId. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="streamId"></param> /// <param name="events"></param> /// <param name="token"></param> /// <param name="requestContext"></param> /// <returns></returns> public virtual Task QueueMessageBatchAsync<T>(StreamId streamId, IEnumerable<T> events, StreamSequenceToken token, Dictionary<string, object> requestContext) { EventData eventData = this.dataAdapter.ToQueueMessage(streamId, events, token, requestContext); string partitionKey = this.dataAdapter.GetPartitionKey(streamId); return this.client.SendAsync(new[] { eventData }, new SendEventOptions { PartitionKey = partitionKey }); } /// <summary> /// Creates a queue receiver for the specified queueId /// </summary> /// <param name="queueId"></param> /// <returns></returns> public IQueueAdapterReceiver CreateReceiver(QueueId queueId) { return GetOrCreateReceiver(queueId); } /// <summary> /// Create a cache for a given queue id /// </summary> /// <param name="queueId"></param> public IQueueCache CreateQueueCache(QueueId queueId) { return GetOrCreateReceiver(queueId); } private EventHubAdapterReceiver GetOrCreateReceiver(QueueId queueId) { return this.receivers.GetOrAdd(queueId, q => MakeReceiver(queueId)); } protected virtual void InitEventHubClient() { this.client = ehOptions.TokenCredential != null ? new EventHubProducerClient(ehOptions.FullyQualifiedNamespace, ehOptions.Path, ehOptions.TokenCredential, new EventHubProducerClientOptions { ConnectionOptions = new EventHubConnectionOptions { TransportType = ehOptions.EventHubsTransportType } }) : new EventHubProducerClient(ehOptions.ConnectionString, ehOptions.Path, new EventHubProducerClientOptions { ConnectionOptions = new EventHubConnectionOptions { TransportType = ehOptions.EventHubsTransportType } }); } /// <summary> /// Create a IEventHubQueueCacheFactory. It will create a EventHubQueueCacheFactory by default. /// User can override this function to return their own implementation of IEventHubQueueCacheFactory, /// and other customization of IEventHubQueueCacheFactory if they may. /// </summary> /// <returns></returns> protected virtual IEventHubQueueCacheFactory CreateCacheFactory(EventHubStreamCachePressureOptions eventHubCacheOptions) { var eventHubPath = this.ehOptions.Path; var sharedDimensions = new EventHubMonitorAggregationDimensions(eventHubPath); return new EventHubQueueCacheFactory(eventHubCacheOptions, cacheEvictionOptions, statisticOptions, this.dataAdapter, sharedDimensions); } private EventHubAdapterReceiver MakeReceiver(QueueId queueId) { var config = new EventHubPartitionSettings { Hub = ehOptions, Partition = this.streamQueueMapper.QueueToPartition(queueId), ReceiverOptions = this.receiverOptions }; var receiverMonitorDimensions = new EventHubReceiverMonitorDimensions { EventHubPartition = config.Partition, EventHubPath = config.Hub.Path, }; if (this.checkpointerFactory == null) InitCheckpointerFactory(); return new EventHubAdapterReceiver(config, this.CacheFactory, this.checkpointerFactory.Create, this.loggerFactory, this.ReceiverMonitorFactory(receiverMonitorDimensions, this.loggerFactory, this.telemetryProducer), this.serviceProvider.GetRequiredService<IOptions<LoadSheddingOptions>>().Value, this.telemetryProducer, this.EventHubReceiverFactory); } /// <summary> /// Get partition Ids from eventhub /// </summary> /// <returns></returns> protected virtual async Task<string[]> GetPartitionIdsAsync() { return await client.GetPartitionIdsAsync(); } public static EventHubAdapterFactory Create(IServiceProvider services, string name) { var ehOptions = services.GetOptionsByName<EventHubOptions>(name); var receiverOptions = services.GetOptionsByName<EventHubReceiverOptions>(name); var cacheOptions = services.GetOptionsByName<EventHubStreamCachePressureOptions>(name); var statisticOptions = services.GetOptionsByName<StreamStatisticOptions>(name); var evictionOptions = services.GetOptionsByName<StreamCacheEvictionOptions>(name); IEventHubDataAdapter dataAdapter = services.GetServiceByName<IEventHubDataAdapter>(name) ?? services.GetService<IEventHubDataAdapter>() ?? ActivatorUtilities.CreateInstance<EventHubDataAdapter>(services); var factory = ActivatorUtilities.CreateInstance<EventHubAdapterFactory>(services, name, ehOptions, receiverOptions, cacheOptions, evictionOptions, statisticOptions, dataAdapter); factory.Init(); return factory; } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Diagnostics; namespace AnimatGuiCtrls.Controls { /// <summary> /// Summary description for KeyFrameVideoRange. /// </summary> public class KeyFrameVideoRange : KeyFrame { #region Properties public override enumKeyFrameType KeyFrameType { get { return enumKeyFrameType.Video; } } public override long StartMillisecond { get { return _StartMillisecond; } set { if(value < 0) throw new System.Exception("The start millisecond time for a keyframe can not be less than zero."); if(value > _EndMillisecond) throw new System.Exception("The start millisecond time for a keyframe can not be greater than the end time."); _StartMillisecond = value; } } public override long EndMillisecond { get { return _EndMillisecond; } set { if(value < 0) throw new System.Exception("The end millisecond time for a keyframe can not be less than zero."); if(value < _StartMillisecond) throw new System.Exception("The end millisecond time for a keyframe can not be less than the start time."); _EndMillisecond = value; } } #endregion #region Methods public KeyFrameVideoRange() { _Color = Color.FromArgb(100, 255, 100); _SelectedColor = Color.FromArgb(0, 255, 0); CreatePens(); } public KeyFrameVideoRange(long lStart, long lEnd) { SetTimes(lStart, lEnd); _Color = Color.FromArgb(100, 255, 100); _SelectedColor = Color.FromArgb(0, 255, 0); CreatePens(); } public override void SetTimes(long lStart, long lEnd) { if(lStart < 0 || lEnd < 0) throw new System.Exception("The start/end millisecond time for a keyframe can not be less than zero."); long lTemp; //If the start and end times are swapped then swap them back correctly. if(lEnd < lStart) { lTemp = lStart; lStart = lEnd; lEnd = lTemp; } _StartMillisecond = lStart; _EndMillisecond = lEnd; } public override void Draw(Graphics g, TimeRuler ruler) { if (ruler.Orientation == enumOrientation.orHorizontal) { int x1 = ruler.ScaleValueToPixel((double) _StartMillisecond) - 1; int y1 = ruler.HeaderOffset, y2 = ruler.Height; g.DrawLine(_DrawingPen, x1, y1, x1, y2); x1 = ruler.ScaleValueToPixel((double) _EndMillisecond) - 1; y1 = ruler.HeaderOffset; y2 = ruler.Height; g.DrawLine(_DrawingPen, x1, y1, x1, y2); y1 = ruler.HeaderOffset/2; y2 = ruler.HeaderOffset - y1; x1 = ruler.ScaleValueToPixel((double) _StartMillisecond) - 2; int x2 = ruler.ScaleValueToPixel((double) _EndMillisecond) ; x2 = x2 - x1; g.DrawRectangle(new Pen(new SolidBrush(ruler.ForeColor)), x1, y1, x2, y2); g.FillRectangle(_DrawingBrush, x1, y1, x2, y2); y1 = ruler.HeaderOffset/2; y2 = ruler.HeaderOffset - y1; x1 = ruler.ScaleValueToPixel((double) _StartMillisecond) - (y2/2) - 1; g.FillRectangle(new SolidBrush(ruler.ForeColor), x1, y1, y2, y2); y1 = ruler.HeaderOffset/2; y2 = ruler.HeaderOffset - y1; x1 = ruler.ScaleValueToPixel((double) _EndMillisecond) - (y2/2) - 1; g.FillRectangle(new SolidBrush(ruler.ForeColor), x1, y1, y2, y2); } else { int y1 = ruler.ScaleValueToPixel((double) _StartMillisecond) - 1; int x1 = ruler.HeaderOffset, x2 = ruler.Width; g.DrawLine(_DrawingPen, x1, y1, x2, y1); y1 = ruler.ScaleValueToPixel((double) _EndMillisecond) - 1; x1 = ruler.HeaderOffset; x2 = ruler.Height; g.DrawLine(_DrawingPen, x1, y1, x2, y1); x1 = ruler.HeaderOffset/2; x2 = ruler.HeaderOffset - x1; y1 = ruler.ScaleValueToPixel((double) _StartMillisecond) - 2; int y2 = ruler.ScaleValueToPixel((double) _EndMillisecond) ; y2 = y2 - y1; g.DrawRectangle(new Pen(new SolidBrush(ruler.ForeColor)), x1, y1, x2, y2); g.FillRectangle(_DrawingBrush, x1, y1, x2, y2); x1 = ruler.HeaderOffset/2; x2 = ruler.HeaderOffset - x1; y1 = ruler.ScaleValueToPixel((double) _StartMillisecond) - (x2/2) - 1; g.FillRectangle(new SolidBrush(ruler.ForeColor), x1, y1, x2, x2); x1 = ruler.HeaderOffset/2; y2 = ruler.HeaderOffset - y1; y1 = ruler.ScaleValueToPixel((double) _EndMillisecond) - (x2/2) - 1; g.FillRectangle(new SolidBrush(ruler.ForeColor), x1, y1, x2, x2); } } public override void MoveFrame(System.Windows.Forms.MouseEventArgs e, TimeRuler ruler) { int iMousePosition = ((ruler.Orientation == enumOrientation.orHorizontal) ? e.X : e.Y); long lNewMillisecond = (long) ruler.PixelToScaleValue(iMousePosition); if(lNewMillisecond > ruler.CurrentMillisecond) { int iStartDist = DistanceFromHandle(e, ruler, _StartMillisecond); int iEndDist = DistanceFromHandle(e, ruler, _EndMillisecond); if(iStartDist < iEndDist) { if(_StartMillisecond > ruler.CurrentMillisecond && !ruler.KeyFrames.Overlaps(lNewMillisecond, this._EndMillisecond, this)) _StartMillisecond = lNewMillisecond; } else { if(_EndMillisecond > ruler.CurrentMillisecond && !ruler.KeyFrames.Overlaps(this._StartMillisecond, lNewMillisecond, this)) _EndMillisecond = lNewMillisecond; } ruler.RedrawBitmap(); } } public override void MoveFrame(long lStart, long lEnd, TimeRuler ruler) { if(lStart > ruler.CurrentMillisecond && lEnd > ruler.CurrentMillisecond) { if(_StartMillisecond > ruler.CurrentMillisecond && !ruler.KeyFrames.Overlaps(lStart, this._EndMillisecond, this)) _StartMillisecond = lStart; if(_EndMillisecond > ruler.CurrentMillisecond && !ruler.KeyFrames.Overlaps(this._StartMillisecond, lEnd, this)) _EndMillisecond = lEnd; ruler.RedrawBitmap(); } } #endregion } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Vevo; using Vevo.Domain; using Vevo.Domain.DataInterfaces; using Vevo.Shared.Utilities; using System.Drawing; using Vevo.Domain.Stores; using Vevo.Shared.WebUI; using Vevo.WebUI.Ajax; using Vevo.WebAppLib; using Vevo.WebUI; using Vevo.Domain.Contents; using Vevo.Domain.Products; using Vevo.Domain.EmailTemplates; using Vevo.WebUI.Widget; using Vevo.Base.Domain; public partial class Admin_MainControls_StoreList : AdminAdvancedBaseListControl { #region Private private string _currentID = "0"; private bool _emptyRow = false; private bool IsContainingOnlyEmptyRow { get { return _emptyRow; } set { _emptyRow = value; } } private void SetUpSearchFilter() { IList<TableSchemaItem> list = DataAccessContext.StoreRepository.GetTableSchema(); uxSearchFilter.SetUpSchema( list ); } private void PopulateControls() { if (!MainContext.IsPostBack) { RefreshGrid(); } if (uxGrid.Rows.Count > 0) { DeleteVisible( true ); uxPagingControl.Visible = true; } else { DeleteVisible( false ); uxPagingControl.Visible = false; } if (!IsAdminModifiable()) { uxAddButton.Visible = false; DeleteVisible( false ); } } private void DeleteVisible( bool value ) { uxDeleteButton.Visible = value; if (value) { if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal) { uxDeleteConfirmButton.TargetControlID = "uxDeleteButton"; uxConfirmModalPopup.TargetControlID = "uxDeleteButton"; } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } private void SetUpGridSupportControls() { if (!MainContext.IsPostBack) { uxPagingControl.ItemsPerPages = AdminConfig.StoreItemPerPage; SetUpSearchFilter(); } RegisterGridView( uxGrid, "StoreID" ); RegisterSearchFilter( uxSearchFilter ); RegisterPagingControl( uxPagingControl ); uxSearchFilter.BubbleEvent += new EventHandler( uxSearchFilter_BubbleEvent ); uxPagingControl.BubbleEvent += new EventHandler( uxPagingControl_BubbleEvent ); } private bool VerifyStoreName( string name, string id ) { return DataAccessContext.StoreRepository.GetStoreIDByStoreName( name ) == id; } private void RefreshDeleteButton() { if (IsContainingOnlyEmptyRow) uxDeleteButton.Visible = false; else uxDeleteButton.Visible = true; } private void CreateDummyRow( IList<Store> list ) { Store store = new Store(); store.StoreID = "-1"; list.Add( store ); } private void DeleteStoreInformation( string storeID ) { Culture culture = DataAccessContext.CultureRepository.GetOne( DataAccessContext.CultureRepository.GetIDByName( SystemConst.USCultureName ) ); DeleteContentManagement( culture, storeID ); DeleteEmailTemplate( culture, storeID ); } private void DeleteContentManagement( Culture culture, string storeID ) { IList<ContentMenuItem> menuList = DataAccessContext.ContentMenuItemRepository.GetByStoreID( culture, storeID, "ContentMenuItemID", BoolFilter.ShowAll ); foreach (ContentMenuItem item in menuList) { DataAccessContext.ContentMenuRepository.Delete( item.ReferringMenuID ); DataAccessContext.ContentMenuItemRepository.Delete( item.ContentMenuItemID ); } } private void DeleteEmailTemplate( Culture culture, string storeID ) { IList<EmailTemplateDetail> emailList = DataAccessContext.EmailTemplateDetailRepository.GetAll( culture, "EmailTemplateDetailID", storeID ); foreach (EmailTemplateDetail email in emailList) { DataAccessContext.EmailTemplateDetailRepository.Delete( email.EmailTemplateDetailID ); } } private void SetFooterRowFocus() { Control textBox = uxGrid.FooterRow.FindControl( "uxNameText" ); AjaxUtilities.GetScriptManager( this ).SetFocus( textBox ); } private string GetUrlPath( string url ) { return UrlPath.ExtractWWWandHTTPinUrl( url.Trim() ); } private bool VerifyUrlWithKey( string url ) { return KeyUtilities.Verify( NamedConfig.DomainRegistrationKey, url ); } #endregion #region Protected protected void Page_Load( object sender, EventArgs e ) { SetUpGridSupportControls(); } protected void Page_PreRender( object sender, EventArgs e ) { PopulateControls(); } protected override void RefreshGrid() { int totalItems; IList<Store> list = DataAccessContext.StoreRepository.SearchStore( GridHelper.GetFullSortText(), uxSearchFilter.SearchFilterObj, uxPagingControl.StartIndex, uxPagingControl.EndIndex, out totalItems ); if (list == null || list.Count == 0) { IsContainingOnlyEmptyRow = true; list = new List<Store>(); CreateDummyRow( list ); } else { IsContainingOnlyEmptyRow = false; } uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages ); uxGrid.DataSource = list; uxGrid.DataBind(); RefreshDeleteButton(); if (uxGrid.ShowFooter) { Control nameText = uxGrid.FooterRow.FindControl( "uxNameText" ); Control addButton = uxGrid.FooterRow.FindControl( "uxAddLinkButton" ); WebUtilities.TieButton( this.Page, nameText, addButton ); } } protected void uxDeleteButton_Click( object sender, EventArgs e ) { try { bool deleted = false; foreach (GridViewRow row in uxGrid.Rows) { CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" ); if (deleteCheck.Checked) { string id = uxGrid.DataKeys[row.RowIndex]["StoreID"].ToString().Trim(); DataAccessContext.StoreRepository.Delete( id ); DeleteStoreInformation( id ); DataAccessContext.ConfigurationRepository.DeleteConfigValueByStoreID( id ); DataAccessContext.NewsLetterRepository.DeleteEmailByStore( DataAccessContext.StoreRepository.GetOne( id ) ); DataAccessContext.NewsRepository.DeleteByStoreID( id ); DataAccessContext.ProductRepository.DeleteProductPricesByStoreID( id ); DataAccessContext.ProductRepository.DeleteProductMetaInformationByStoreID( id ); deleted = true; } } uxGrid.EditIndex = -1; if (deleted) { uxMessage.DisplayMessage( Resources.StoreMessages.DeleteSuccess ); } } catch (Exception ex) { uxMessage.DisplayException( ex ); } RefreshGrid(); if (uxGrid.Rows.Count == 0 && uxPagingControl.CurrentPage >= uxPagingControl.NumberOfPages) { uxPagingControl.CurrentPage = uxPagingControl.NumberOfPages; RefreshGrid(); } } protected void uxAddButton_Click( object sender, EventArgs e ) { uxGrid.EditIndex = -1; uxGrid.ShowFooter = true; uxGrid.ShowHeader = true; RefreshGrid(); uxAddButton.Visible = false; SetFooterRowFocus(); } protected Color GetEnabledColor( object isEnabled ) { if (ConvertUtilities.ToBoolean( isEnabled )) return Color.DarkGreen; else return Color.Chocolate; } protected void uxGrid_RowEditing( object sender, GridViewEditEventArgs e ) { uxGrid.EditIndex = e.NewEditIndex; RefreshGrid(); } protected void uxGrid_CancelingEdit( object sender, GridViewCancelEditEventArgs e ) { uxGrid.EditIndex = -1; RefreshGrid(); } private void SetDefaultDisplayCurrencyCode( Store store ) { string baseCurrency = DataAccessContext.Configurations.GetValue( "BaseWebsiteCurrency" ); DataAccessContext.ConfigurationRepository.UpdateValue( DataAccessContext.Configurations["DefaultDisplayCurrencyCode"], baseCurrency, store ); } private void SetProductPrice( Store store ) { DataAccessContext.ProductRepository.CreateProductPricesFromDefaultByStoreID( store.StoreID ); } protected void uxGrid_RowCommand( object sender, GridViewCommandEventArgs e ) { string url = ((TextBox) uxGrid.FooterRow.FindControl( "uxUrlNameText" )).Text; string name = ((TextBox) uxGrid.FooterRow.FindControl( "uxNameText" )).Text; try { if (e.CommandName == "Add") { if (!VerifyStoreName( name, "0" )) { uxMessage.DisplayError( Resources.StoreMessages.DuplicateStoreName ); return; } if (VerifyUrlWithKey( url )) { if (VerifyUrlName( url )) { Store store = new Store(); store.StoreName = name; store.UrlName = GetUrlPath( url ); store.IsEnabled = ((CheckBox) uxGrid.FooterRow.FindControl( "uxIsEnabledCheck" )).Checked; store = DataAccessContext.StoreRepository.Save( store ); store.CreateStoreConfigCollection( store.StoreID ); SetDefaultDisplayCurrencyCode( store ); SetProductPrice( store ); WidgetDirector widgetDirector = new WidgetDirector(); foreach (string widgetConfigName in widgetDirector.WidgetConfigurationNameAll) { DataAccessContext.ConfigurationRepository.UpdateValue( DataAccessContext.Configurations[widgetConfigName], DataAccessContext.Configurations.GetValue( widgetConfigName, Store.Null ), store ); } uxMessage.DisplayMessage( Resources.StoreMessages.AddSuccess ); RefreshGrid(); } else { uxMessage.DisplayError( Resources.StoreMessages.DuplicateUrl ); } } else { uxMessage.DisplayError( Resources.StoreMessages.DomainKeyError ); } } else if (e.CommandName == "Edit") { uxGrid.ShowFooter = false; uxAddButton.Visible = true; } } catch (Exception ex) { uxMessage.DisplayException( ex ); } } protected void uxGrid_RowUpdating( object sender, GridViewUpdateEventArgs e ) { try { string storeID = ((Label) uxGrid.Rows[e.RowIndex].FindControl( "uxStoreIDLabel" )).Text; string name = ((TextBox) uxGrid.Rows[e.RowIndex].FindControl( "uxNameText" )).Text; string url = ((TextBox) uxGrid.Rows[e.RowIndex].FindControl( "uxUrlNameText" )).Text; if (!String.IsNullOrEmpty( storeID )) { _currentID = storeID; if (!VerifyStoreName( name, _currentID ) && !VerifyStoreName( name, "0" )) { uxMessage.DisplayError( Resources.StoreMessages.DuplicateStoreName ); return; } if (VerifyUrlWithKey( url )) { if (VerifyUrlName( url )) { Store store = DataAccessContext.StoreRepository.GetOne( storeID ); store.StoreName = name; store.UrlName = GetUrlPath( url ); store.IsEnabled = ((CheckBox) uxGrid.Rows[e.RowIndex].FindControl( "uxIsEnabledCheck" )).Checked; store = DataAccessContext.StoreRepository.Save( store ); uxMessage.DisplayMessage( Resources.StoreMessages.UpdateSuccess ); // End editing uxGrid.EditIndex = -1; RefreshGrid(); } else uxMessage.DisplayError( Resources.StoreMessages.DuplicateUrl ); } else { uxMessage.DisplayError( Resources.StoreMessages.DomainKeyError ); } } } catch (Exception ex) { uxMessage.DisplayException( ex ); } finally { // Avoid calling Update() automatically by GridView e.Cancel = true; } } protected void uxGrid_DataBound( object sender, EventArgs e ) { if (IsContainingOnlyEmptyRow) { uxGrid.Rows[0].Visible = false; } } #endregion #region Public public bool VerifyUrlName( string url ) { string storeID = DataAccessContext.StoreRepository.GetStoreIDByUrlName( GetUrlPath( url ) ); if (_currentID == "0") //Add mode { return (storeID == "0"); } else //Edit mode { if (storeID != _currentID) { return (storeID == "0"); } else { return true; } } } #endregion }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Tests.Common.Builders.Extensions; using Umbraco.Cms.Tests.Common.Builders.Interfaces; namespace Umbraco.Cms.Tests.Common.Builders { public class MemberBuilder : BuilderBase<Member>, IBuildContentTypes, IWithIdBuilder, IWithKeyBuilder, IWithCreatorIdBuilder, IWithCreateDateBuilder, IWithUpdateDateBuilder, IWithNameBuilder, IWithTrashedBuilder, IWithLevelBuilder, IWithPathBuilder, IWithSortOrderBuilder, IAccountBuilder { private MemberTypeBuilder _memberTypeBuilder; private GenericCollectionBuilder<MemberBuilder, string> _memberGroupsBuilder; private GenericDictionaryBuilder<MemberBuilder, string, object> _additionalDataBuilder; private GenericDictionaryBuilder<MemberBuilder, string, object> _propertyDataBuilder; private int? _id; private Guid? _key; private DateTime? _createDate; private DateTime? _updateDate; private string _name; private int? _creatorId; private int? _level; private string _path; private string _username; private string _rawPasswordValue; private string _passwordConfig; private string _email; private int? _failedPasswordAttempts; private bool? _isApproved; private bool? _isLockedOut; private DateTime? _lastLockoutDate; private DateTime? _lastLoginDate; private DateTime? _lastPasswordChangeDate; private int? _sortOrder; private bool? _trashed; private int? _propertyIdsIncrementingFrom; private IMemberType _memberType; public MemberBuilder WithPropertyIdsIncrementingFrom(int propertyIdsIncrementingFrom) { _propertyIdsIncrementingFrom = propertyIdsIncrementingFrom; return this; } public MemberTypeBuilder AddMemberType() { _memberType = null; var builder = new MemberTypeBuilder(this); _memberTypeBuilder = builder; return builder; } public MemberBuilder WithMemberType(IMemberType memberType) { _memberTypeBuilder = null; _memberType = memberType; return this; } public GenericCollectionBuilder<MemberBuilder, string> AddMemberGroups() { var builder = new GenericCollectionBuilder<MemberBuilder, string>(this); _memberGroupsBuilder = builder; return builder; } public GenericDictionaryBuilder<MemberBuilder, string, object> AddAdditionalData() { var builder = new GenericDictionaryBuilder<MemberBuilder, string, object>(this); _additionalDataBuilder = builder; return builder; } public GenericDictionaryBuilder<MemberBuilder, string, object> AddPropertyData() { var builder = new GenericDictionaryBuilder<MemberBuilder, string, object>(this); _propertyDataBuilder = builder; return builder; } public override Member Build() { var id = _id ?? 0; Guid key = _key ?? Guid.NewGuid(); DateTime createDate = _createDate ?? DateTime.Now; DateTime updateDate = _updateDate ?? DateTime.Now; var name = _name ?? Guid.NewGuid().ToString(); var creatorId = _creatorId ?? 0; var level = _level ?? 1; var path = _path ?? $"-1,{id}"; var sortOrder = _sortOrder ?? 0; var trashed = _trashed ?? false; var username = _username ?? string.Empty; var email = _email ?? string.Empty; var rawPasswordValue = _rawPasswordValue ?? string.Empty; var failedPasswordAttempts = _failedPasswordAttempts ?? 0; var isApproved = _isApproved ?? false; var isLockedOut = _isLockedOut ?? false; DateTime lastLockoutDate = _lastLockoutDate ?? DateTime.Now; DateTime lastLoginDate = _lastLoginDate ?? DateTime.Now; DateTime lastPasswordChangeDate = _lastPasswordChangeDate ?? DateTime.Now; var passwordConfig = _passwordConfig ?? "{\"hashAlgorithm\":\"PBKDF2.ASPNETCORE.V3\"}"; if (_memberTypeBuilder is null && _memberType is null) { throw new InvalidOperationException("A member cannot be constructed without providing a member type. Use AddMemberType() or WithMemberType()."); } IMemberType memberType = _memberType ?? _memberTypeBuilder.Build(); var member = new Member(name, email, username, rawPasswordValue, memberType) { Id = id, Key = key, CreateDate = createDate, UpdateDate = updateDate, CreatorId = creatorId, Level = level, Path = path, SortOrder = sortOrder, Trashed = trashed, PasswordConfiguration = passwordConfig }; if (_propertyIdsIncrementingFrom.HasValue) { var i = _propertyIdsIncrementingFrom.Value; foreach (IProperty property in member.Properties) { property.Id = ++i; } } member.FailedPasswordAttempts = failedPasswordAttempts; member.IsApproved = isApproved; member.IsLockedOut = isLockedOut; member.LastLockoutDate = lastLockoutDate; member.LastLoginDate = lastLoginDate; member.LastPasswordChangeDate = lastPasswordChangeDate; if (_memberGroupsBuilder != null) { member.Groups = _memberGroupsBuilder.Build(); } if (_additionalDataBuilder != null) { IDictionary<string, object> additionalData = _additionalDataBuilder.Build(); foreach (KeyValuePair<string, object> kvp in additionalData) { member.AdditionalData.Add(kvp.Key, kvp.Value); } } if (_propertyDataBuilder != null) { IDictionary<string, object> propertyData = _propertyDataBuilder.Build(); foreach (KeyValuePair<string, object> kvp in propertyData) { member.SetValue(kvp.Key, kvp.Value); } member.ResetDirtyProperties(false); } return member; } public static IEnumerable<IMember> CreateSimpleMembers(IMemberType memberType, int amount) { var list = new List<IMember>(); for (int i = 0; i < amount; i++) { var name = "Member No-" + i; MemberBuilder builder = new MemberBuilder() .WithMemberType(memberType) .WithName(name) .WithEmail("test" + i + "@test.com") .WithLogin("test" + i, "test" + i); builder = builder .AddPropertyData() .WithKeyValue("title", name + " member" + i) .WithKeyValue("bodyText", "This is a subpage" + i) .WithKeyValue("author", "John Doe" + i) .Done(); list.Add(builder.Build()); } return list; } public static Member CreateSimpleMember(IMemberType memberType, string name, string email, string password, string username, Guid? key = null) { MemberBuilder builder = new MemberBuilder() .WithMemberType(memberType) .WithName(name) .WithEmail(email) .WithIsApproved(true) .WithLogin(username, password); if (key.HasValue) { builder = builder.WithKey(key.Value); } builder = builder .AddPropertyData() .WithKeyValue("title", name + " member") .WithKeyValue("bodyText", "Member profile") .WithKeyValue("author", "John Doe") .Done(); return builder.Build(); } public static IEnumerable<IMember> CreateMultipleSimpleMembers(IMemberType memberType, int amount, Action<int, IMember> onCreating = null) { var list = new List<IMember>(); for (var i = 0; i < amount; i++) { var name = "Member No-" + i; Member member = new MemberBuilder() .WithMemberType(memberType) .WithName(name) .WithEmail("test" + i + "@test.com") .WithLogin("test" + i, "test" + i) .AddPropertyData() .WithKeyValue("title", name + " member" + i) .WithKeyValue("bodyText", "Member profile" + i) .WithKeyValue("author", "John Doe" + i) .Done() .Build(); onCreating?.Invoke(i, member); list.Add(member); } return list; } int? IWithIdBuilder.Id { get => _id; set => _id = value; } Guid? IWithKeyBuilder.Key { get => _key; set => _key = value; } int? IWithCreatorIdBuilder.CreatorId { get => _creatorId; set => _creatorId = value; } DateTime? IWithCreateDateBuilder.CreateDate { get => _createDate; set => _createDate = value; } DateTime? IWithUpdateDateBuilder.UpdateDate { get => _updateDate; set => _updateDate = value; } string IWithNameBuilder.Name { get => _name; set => _name = value; } bool? IWithTrashedBuilder.Trashed { get => _trashed; set => _trashed = value; } int? IWithLevelBuilder.Level { get => _level; set => _level = value; } string IWithPathBuilder.Path { get => _path; set => _path = value; } int? IWithSortOrderBuilder.SortOrder { get => _sortOrder; set => _sortOrder = value; } string IWithLoginBuilder.Username { get => _username; set => _username = value; } string IWithLoginBuilder.RawPasswordValue { get => _rawPasswordValue; set => _rawPasswordValue = value; } string IWithLoginBuilder.PasswordConfig { get => _passwordConfig; set => _passwordConfig = value; } string IWithEmailBuilder.Email { get => _email; set => _email = value; } int? IWithFailedPasswordAttemptsBuilder.FailedPasswordAttempts { get => _failedPasswordAttempts; set => _failedPasswordAttempts = value; } bool? IWithIsApprovedBuilder.IsApproved { get => _isApproved; set => _isApproved = value; } bool? IWithIsLockedOutBuilder.IsLockedOut { get => _isLockedOut; set => _isLockedOut = value; } DateTime? IWithIsLockedOutBuilder.LastLockoutDate { get => _lastLockoutDate; set => _lastLockoutDate = value; } DateTime? IWithLastLoginDateBuilder.LastLoginDate { get => _lastLoginDate; set => _lastLoginDate = value; } DateTime? IWithLastPasswordChangeDateBuilder.LastPasswordChangeDate { get => _lastPasswordChangeDate; set => _lastPasswordChangeDate = value; } } }
// // System.Web.HttpCachePolicy // // Authors: // Tim Coleman (tim@timcoleman.com) // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Globalization; using System.IO; using System.Security.Permissions; using System.Text; using System; namespace HTTP.Net { public enum HttpCacheRevalidation { AllCaches = 0x1, ProxyCaches, None, } public enum HttpValidationStatus { Invalid = 0x1, IgnoreThisRequest, Valid } public enum HttpCacheability { NoCache = 0x1, Private, Server, Public, ServerAndPrivate, ServerAndNoCache = 0x3 } public delegate void CustomCacheValidateHandler( MonoContext context, object data, ref HttpValidationStatus validationStatus); public sealed class CustomCachePolicy { internal CustomCachePolicy() { } //HttpCacheVaryByContentEncodings vary_by_content_encodings = new HttpCacheVaryByContentEncodings (); //HttpCacheVaryByHeaders vary_by_headers = new HttpCacheVaryByHeaders (); //HttpCacheVaryByParams vary_by_params = new HttpCacheVaryByParams (); ArrayList validation_callbacks; StringBuilder cache_extension; internal HttpCacheability Cacheability; string etag; bool etag_from_file_dependencies; bool last_modified_from_file_dependencies; // // Used externally // internal bool have_expire_date; internal DateTime expire_date; internal bool have_last_modified; internal DateTime last_modified; //bool LastModifiedFromFileDependencies; HttpCacheRevalidation revalidation; string vary_by_custom; bool HaveMaxAge; TimeSpan MaxAge; bool HaveProxyMaxAge; TimeSpan ProxyMaxAge; ArrayList fields; bool sliding_expiration; int duration; bool allow_response_in_browser_history; bool allow_server_caching = true; bool set_no_store; bool set_no_transform; bool valid_until_expires; bool omit_vary_star; //public HttpCacheVaryByContentEncodings VaryByContentEncodings { // get { return vary_by_content_encodings; } //} //public HttpCacheVaryByHeaders VaryByHeaders { // get { return vary_by_headers; } //} //public HttpCacheVaryByParams VaryByParams { // get { return vary_by_params; } //} internal bool AllowServerCaching { get { return allow_server_caching; } } internal int Duration { get { return duration; } set { duration = value; } } internal bool Sliding { get { return sliding_expiration; } } internal DateTime Expires { get { return expire_date; } } internal ArrayList ValidationCallbacks { get { return validation_callbacks; } } internal bool OmitVaryStar { get { return omit_vary_star; } } internal bool ValidUntilExpires { get { return valid_until_expires; } } internal int ExpireMinutes () { if (!have_expire_date) return 0; return (expire_date - DateTime.Now).Minutes; } public void AddValidationCallback (CustomCacheValidateHandler handler, object data) { if (handler == null) throw new ArgumentNullException ("handler"); if (validation_callbacks == null) validation_callbacks = new ArrayList (); validation_callbacks.Add (new MonoPair (handler, data)); } public void AppendCacheExtension (string extension) { if (extension == null) throw new ArgumentNullException ("extension"); if (cache_extension == null) cache_extension = new StringBuilder (extension); else cache_extension.Append (", " + extension); } // // This one now allows the full range of Cacheabilities. // public void SetCacheability (HttpCacheability cacheability) { if (cacheability < HttpCacheability.NoCache || cacheability > HttpCacheability.ServerAndPrivate) throw new ArgumentOutOfRangeException ("cacheability"); if (Cacheability > 0 && cacheability > Cacheability) return; Cacheability = cacheability; } public void SetCacheability (HttpCacheability cacheability, string field) { if (field == null) throw new ArgumentNullException ("field"); if (cacheability != HttpCacheability.NoCache && cacheability != HttpCacheability.Private) throw new ArgumentException ("Must be NoCache or Private", "cacheability"); if (fields == null) fields = new ArrayList (); fields.Add (new MonoPair (cacheability, field)); } public void SetETag (string etag) { if (etag == null) throw new ArgumentNullException ("etag"); if (this.etag != null) throw new InvalidOperationException ("The ETag header has already been set"); if (etag_from_file_dependencies) throw new InvalidOperationException ("SetEtagFromFileDependencies has already been called"); this.etag = etag; } public void SetETagFromFileDependencies () { if (this.etag != null) throw new InvalidOperationException ("The ETag header has already been set"); etag_from_file_dependencies = true; } public void SetExpires (DateTime date) { if (have_expire_date && date > expire_date) return; have_expire_date = true; expire_date = date; } public void SetLastModified (DateTime date) { if (date > DateTime.Now) throw new ArgumentOutOfRangeException ("date"); if (have_last_modified && date < last_modified) return; have_last_modified = true; last_modified = date; } public void SetLastModifiedFromFileDependencies () { last_modified_from_file_dependencies = true; } public void SetMaxAge (TimeSpan date) { if (date < TimeSpan.Zero) throw new ArgumentOutOfRangeException ("date"); if (HaveMaxAge && MaxAge < date) return; MaxAge = date; HaveMaxAge = true; } public void SetNoServerCaching () { allow_server_caching = false; } public void SetNoStore () { set_no_store = true; } public void SetNoTransforms () { set_no_transform = true; } public void SetProxyMaxAge (TimeSpan delta) { if (delta < TimeSpan.Zero) throw new ArgumentOutOfRangeException ("delta"); if (HaveProxyMaxAge && ProxyMaxAge < delta) return; ProxyMaxAge = delta; HaveProxyMaxAge = true; } public void SetRevalidation (HttpCacheRevalidation revalidation) { if (revalidation < HttpCacheRevalidation.AllCaches || revalidation > HttpCacheRevalidation.None) throw new ArgumentOutOfRangeException ("revalidation"); if (this.revalidation > revalidation) this.revalidation = revalidation; } public void SetSlidingExpiration (bool slide) { sliding_expiration = slide; } public void SetValidUntilExpires (bool validUntilExpires) { valid_until_expires = validUntilExpires; } public void SetVaryByCustom (string custom) { if (custom == null) throw new ArgumentNullException ("custom"); if (vary_by_custom != null) throw new InvalidOperationException ("VaryByCustom has already been set."); vary_by_custom = custom; } internal string GetVaryByCustom () { return vary_by_custom; } public void SetAllowResponseInBrowserHistory (bool allow) { if (Cacheability == HttpCacheability.NoCache || Cacheability == HttpCacheability.ServerAndNoCache) allow_response_in_browser_history = allow; } internal void SetCacheControl(CustomCachePolicy Cache, string value) { if (value == null || value == "") { Cache.SetCacheability(HttpCacheability.NoCache); } else if (String.Compare(value, "public", true, System.Globalization.CultureInfo.InvariantCulture) == 0) { Cache.SetCacheability(HttpCacheability.Public); } else if (String.Compare(value, "private", true, System.Globalization.CultureInfo.InvariantCulture) == 0) { Cache.SetCacheability(HttpCacheability.Private); } else if (String.Compare(value, "no-cache", true, System.Globalization.CultureInfo.InvariantCulture) == 0) { Cache.SetCacheability(HttpCacheability.NoCache); } else throw new ArgumentException("CacheControl"); } internal string GetCacheControl(CustomCachePolicy Cache) { switch (Cache.Cacheability) { case HttpCacheability.Private: return "private"; case HttpCacheability.Public: return "public"; default: return "no-cache"; } } internal void SetHeaders (HttpResponse response, NameValueCollection headers) { bool noCache = false; string cc = null; switch (Cacheability) { case HttpCacheability.Public: cc = "public"; break; case HttpCacheability.NoCache: case HttpCacheability.ServerAndNoCache: noCache = true; cc = "no-cache"; break; case HttpCacheability.Private: case HttpCacheability.ServerAndPrivate: default: cc = "private"; break; } if (noCache) { SetCacheControl(response.Cache, cc); if (!allow_response_in_browser_history) { headers.Add ("Expires", "-1"); headers.Add ("Pragma", "no-cache"); } } else { if (HaveMaxAge) cc = String.Concat (cc, ", max-age=", ((long) MaxAge.TotalSeconds).ToString ()); if (have_expire_date) { string expires = ToUtcTimeString (expire_date); headers.Add ("Expires", expires); } } if (set_no_store) cc = String.Concat (cc, ", no-store"); if (set_no_transform) cc = String.Concat (cc, ", no-transform"); headers.Add ("Cache-Control", cc); if (last_modified_from_file_dependencies || etag_from_file_dependencies) HeadersFromFileDependencies(response); if (etag != null) headers.Add ("ETag", etag); if (have_last_modified) headers.Add ("Last-Modified", ToUtcTimeString(last_modified)); //if (!vary_by_params.IgnoreParams) { // string vb = vary_by_params.GetResponseHeaderValue (); // if (vb != null) // headers.Add ("Vary", vb); //} } internal static string ToUtcTimeString(DateTime dt) { return dt.ToUniversalTime().ToString("ddd, d MMM yyyy HH:mm:ss ", System.Globalization.CultureInfo.InvariantCulture) + "GMT"; } void HeadersFromFileDependencies(HttpResponse response) { string[] fileDeps = response.FileDependencies; if (fileDeps == null || fileDeps.Length == 0) return; bool doEtag = etag != null && etag_from_file_dependencies; if (!doEtag && !last_modified_from_file_dependencies) return; DateTime latest_mod = DateTime.MinValue, mod; StringBuilder etagsb = new StringBuilder(); foreach (string f in fileDeps) { if (!File.Exists(f)) continue; try { mod = File.GetLastWriteTime(f); } catch { // ignore continue; } if (last_modified_from_file_dependencies && mod > latest_mod) latest_mod = mod; if (doEtag) etagsb.AppendFormat("{0}", mod.Ticks.ToString("x")); } if (last_modified_from_file_dependencies && latest_mod > DateTime.MinValue) { last_modified = latest_mod; have_last_modified = true; } if (doEtag && etagsb.Length > 0) etag = etagsb.ToString(); } public void SetOmitVaryStar (bool omit) { omit_vary_star = omit; } } public sealed class MonoPair { public MonoPair(object first, object second) { First = first; Second = second; } public MonoPair() { } public object First; public object Second; } }
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen //Copyright 2006-2011 Jeroen van Menen // // 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 Copyright using NUnit.Framework.SyntaxHelpers; using System; using Moq; using NUnit.Framework; using WatiN.Core.Native; using WatiN.Core.UnitTests.TestUtils; namespace WatiN.Core.UnitTests { [TestFixture] public class ElementStyleTests : BaseWithBrowserTests { private const string EXPECTED_STYLE = "background-color: blue; font-style: italic; font-family: Arial; height: 50px; color: white; font-size: 12px;"; private TextField _element; public override Uri TestPageUri { get { return MainURI; } } [Test] public void GetAttributeValueStyleAsString() { ExecuteTest(browser => { _element = browser.TextField("Textarea1"); AssertStyleText(_element.GetAttributeValue("style").ToLowerInvariant()); }); } [Test] public void ElementStyleToStringReturnsCssText() { ExecuteTest(browser => { _element = browser.TextField("Textarea1"); AssertStyleText(_element.Style.ToString().ToLowerInvariant()); }); } [Test] public void ElementStyleCssText() { ExecuteTest(browser => { _element = browser.TextField("Textarea1"); AssertStyleText(_element.Style.CssText.ToLowerInvariant()); }); } private void AssertStyleText(string cssText) { Assert.That(cssText.Length, Is.EqualTo(EXPECTED_STYLE.Length), "Unexpected length"); var items = EXPECTED_STYLE.Split(Char.Parse(";")); foreach (var item in items) { Assert.That(cssText, Text.Contains(item.ToLowerInvariant().Trim())); } } [Test, ExpectedException(typeof(ArgumentNullException))] public void GetAttributeValueOfNullThrowsArgumenNullException() { // GIVEN var nativeElementMock = new Mock<INativeElement>(); nativeElementMock.Expect(x => x.IsElementReferenceStillValid()).Returns(true); var style = new Style(nativeElementMock.Object); // WHEN style.GetAttributeValue(null); // THEN exception } [Test, ExpectedException(typeof(ArgumentNullException))] public void GetAttributeValueOfEmptyStringThrowsArgumenNullException() { // GIVEN var nativeElementMock = new Mock<INativeElement>(); nativeElementMock.Expect(x => x.IsElementReferenceStillValid()).Returns(true); var style = new Style(nativeElementMock.Object); // WHEN style.GetAttributeValue(string.Empty); // THEN exception } [Test] public void GetAttributeValueBackgroundColor() { ExecuteTest(browser => { // GIVEN _element = browser.TextField("Textarea1"); // WHEN var backgroundColor = _element.Style.GetAttributeValue("backgroundColor"); // THEN Assert.That(new HtmlColor(backgroundColor), Is.EqualTo(HtmlColor.Blue)); }); } [Test] public void GetAttributeValueBackgroundColorByOriginalHTMLattributename() { ExecuteTest(browser => { // GIVEN _element = browser.TextField("Textarea1"); // WHEN var backgroundColor = _element.Style.GetAttributeValue("background-color"); // THEN Assert.That(new HtmlColor(backgroundColor), Is.EqualTo(HtmlColor.Blue)); }); } [Test] public void GetAttributeValueOfUndefinedButValidAttribute() { ExecuteTest(browser => { _element = browser.TextField("Textarea1"); Assert.That(_element.Style.GetAttributeValue("backgroundImage"), Is.EqualTo("none")); }); } [Test] public void GetAttributeValueOfUndefinedAndInvalidAttribute() { ExecuteTest(browser => { _element = browser.TextField("Textarea1"); Assert.IsNull(_element.Style.GetAttributeValue("nonexistingattrib")); }); } [Test] public void BackgroundColor() { ExecuteTest(browser => { // GIVEN _element = browser.TextField("Textarea1"); // WHEN var backgroundColor = _element.Style.BackgroundColor; // THEN Assert.That(backgroundColor, Is.EqualTo(HtmlColor.Blue)); }); } [Test] public void Color() { ExecuteTest(browser => { // GIVEN _element = browser.TextField("Textarea1"); // WHEN var color = _element.Style.Color; // THEN Assert.That(color, Is.EqualTo(HtmlColor.White)); }); } [Test] public void FontFamily() { ExecuteTest(browser => { _element = browser.TextField("Textarea1"); Assert.AreEqual("Arial", _element.Style.FontFamily); }); } [Test] public void FontSize() { ExecuteTest(browser => { _element = browser.TextField("Textarea1"); Assert.AreEqual("12px", _element.Style.FontSize); }); } [Test] public void FontStyle() { ExecuteTest(browser => { _element = browser.TextField("Textarea1"); Assert.AreEqual("italic", _element.Style.FontStyle); }); } [Test] public void Height() { ExecuteTest(browser => { _element = browser.TextField("Textarea1"); if ((browser as FireFox) != null) { Assert.That(_element.Style.Height.Equals("46px")); } else { Assert.That(_element.Style.Height.Equals("50px")); } }); } [Test] public void Should_return_style_set_by_a_style_sheet() { ExecuteTest(browser => { // GIVEN browser.GoTo(StyleTestUri); var divWithExternalStyleApplied = browser.Div("logo"); // WHEN var backgroundUrl = divWithExternalStyleApplied.Style.GetAttributeValue("BACKGROUND-IMAGE"); // THEN Assert.That(backgroundUrl, Text.Contains("watin.jpg")); }); } } }
/* * 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. */ #pragma warning disable 618 // deprecated SpringConfigUrl namespace Apache.Ignite.Core { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Lifecycle; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// This class defines a factory for the main Ignite API. /// <p/> /// Use <see cref="Start()"/> method to start Ignite with default configuration. /// <para/> /// All members are thread-safe and may be used concurrently from multiple threads. /// </summary> public static class Ignition { /** */ internal const string EnvIgniteSpringConfigUrlPrefix = "IGNITE_SPRING_CONFIG_URL_PREFIX"; /** */ private static readonly object SyncRoot = new object(); /** GC warning flag. */ private static int _gcWarn; /** */ private static readonly IDictionary<NodeKey, Ignite> Nodes = new Dictionary<NodeKey, Ignite>(); /** Current DLL name. */ private static readonly string IgniteDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); /** Startup info. */ [ThreadStatic] private static Startup _startup; /** Client mode flag. */ [ThreadStatic] private static bool _clientMode; /// <summary> /// Static initializer. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static Ignition() { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } /// <summary> /// Gets or sets a value indicating whether Ignite should be started in client mode. /// Client nodes cannot hold data in caches. /// </summary> public static bool ClientMode { get { return _clientMode; } set { _clientMode = value; } } /// <summary> /// Starts Ignite with default configuration. By default this method will /// use Ignite configuration defined in <c>{IGNITE_HOME}/config/default-config.xml</c> /// configuration file. If such file is not found, then all system defaults will be used. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite Start() { return Start(new IgniteConfiguration()); } /// <summary> /// Starts all grids specified within given Spring XML configuration file. If Ignite with given name /// is already started, then exception is thrown. In this case all instances that may /// have been started so far will be stopped too. /// </summary> /// <param name="springCfgPath">Spring XML configuration file path or URL. Note, that the path can be /// absolute or relative to IGNITE_HOME.</param> /// <returns>Started Ignite. If Spring configuration contains multiple Ignite instances, then the 1st /// found instance is returned.</returns> public static IIgnite Start(string springCfgPath) { return Start(new IgniteConfiguration {SpringConfigUrl = springCfgPath}); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from first <see cref="IgniteConfigurationSection"/> in the /// application configuration and starts Ignite. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration() { var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var section = cfg.Sections.OfType<IgniteConfigurationSection>().FirstOrDefault(); if (section == null) throw new ConfigurationErrorsException( string.Format("Could not find {0} in current application configuration", typeof(IgniteConfigurationSection).Name)); return Start(section.IgniteConfiguration); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from application configuration /// <see cref="IgniteConfigurationSection"/> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); var section = ConfigurationManager.GetSection(sectionName) as IgniteConfigurationSection; if (section == null) throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'", typeof(IgniteConfigurationSection).Name, sectionName)); return Start(section.IgniteConfiguration); } /// <summary> /// Starts Ignite with given configuration. /// </summary> /// <returns>Started Ignite.</returns> public unsafe static IIgnite Start(IgniteConfiguration cfg) { IgniteArgumentCheck.NotNull(cfg, "cfg"); lock (SyncRoot) { // 1. Check GC settings. CheckServerGc(cfg); // 2. Create context. IgniteUtils.LoadDlls(cfg.JvmDllPath); var cbs = new UnmanagedCallbacks(); IgniteManager.CreateJvmContext(cfg, cbs); var gridName = cfg.GridName; var cfgPath = cfg.SpringConfigUrl == null ? null : Environment.GetEnvironmentVariable(EnvIgniteSpringConfigUrlPrefix) + cfg.SpringConfigUrl; // 3. Create startup object which will guide us through the rest of the process. _startup = new Startup(cfg, cbs); IUnmanagedTarget interopProc = null; try { // 4. Initiate Ignite start. UU.IgnitionStart(cbs.Context, cfgPath, gridName, ClientMode); // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data. var node = _startup.Ignite; interopProc = node.InteropProcessor; // 6. On-start callback (notify lifecycle components). node.OnStart(); Nodes[new NodeKey(_startup.Name)] = node; return node; } catch (Exception) { // 1. Perform keys cleanup. string name = _startup.Name; if (name != null) { NodeKey key = new NodeKey(name); if (Nodes.ContainsKey(key)) Nodes.Remove(key); } // 2. Stop Ignite node if it was started. if (interopProc != null) UU.IgnitionStop(interopProc.Context, gridName, true); // 3. Throw error further (use startup error if exists because it is more precise). if (_startup.Error != null) throw _startup.Error; throw; } finally { _startup = null; if (interopProc != null) UU.ProcessorReleaseStart(interopProc); } } } /// <summary> /// Check whether GC is set to server mode. /// </summary> /// <param name="cfg">Configuration.</param> private static void CheckServerGc(IgniteConfiguration cfg) { if (!cfg.SuppressWarnings && !GCSettings.IsServerGC && Interlocked.CompareExchange(ref _gcWarn, 1, 0) == 0) Console.WriteLine("GC server mode is not enabled, this could lead to less " + "than optimal performance on multi-core machines (to enable see " + "http://msdn.microsoft.com/en-us/library/ms229357(v=vs.110).aspx)."); } /// <summary> /// Prepare callback invoked from Java. /// </summary> /// <param name="inStream">Intput stream with data.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> internal static void OnPrepare(PlatformMemoryStream inStream, PlatformMemoryStream outStream, HandleRegistry handleRegistry) { try { BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(inStream); PrepareConfiguration(reader, outStream); PrepareLifecycleBeans(reader, outStream, handleRegistry); } catch (Exception e) { _startup.Error = e; throw; } } /// <summary> /// Preapare configuration. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Response stream.</param> private static void PrepareConfiguration(BinaryReader reader, PlatformMemoryStream outStream) { // 1. Load assemblies. IgniteConfiguration cfg = _startup.Configuration; LoadAssemblies(cfg.Assemblies); ICollection<string> cfgAssembllies; BinaryConfiguration binaryCfg; BinaryUtils.ReadConfiguration(reader, out cfgAssembllies, out binaryCfg); LoadAssemblies(cfgAssembllies); // 2. Create marshaller only after assemblies are loaded. if (cfg.BinaryConfiguration == null) cfg.BinaryConfiguration = binaryCfg; _startup.Marshaller = new Marshaller(cfg.BinaryConfiguration); // 3. Send configuration details to Java cfg.Write(_startup.Marshaller.StartMarshal(outStream)); } /// <summary> /// Prepare lifecycle beans. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> private static void PrepareLifecycleBeans(BinaryReader reader, PlatformMemoryStream outStream, HandleRegistry handleRegistry) { IList<LifecycleBeanHolder> beans = new List<LifecycleBeanHolder>(); // 1. Read beans defined in Java. int cnt = reader.ReadInt(); for (int i = 0; i < cnt; i++) beans.Add(new LifecycleBeanHolder(CreateLifecycleBean(reader))); // 2. Append beans definied in local configuration. ICollection<ILifecycleBean> nativeBeans = _startup.Configuration.LifecycleBeans; if (nativeBeans != null) { foreach (ILifecycleBean nativeBean in nativeBeans) beans.Add(new LifecycleBeanHolder(nativeBean)); } // 3. Write bean pointers to Java stream. outStream.WriteInt(beans.Count); foreach (LifecycleBeanHolder bean in beans) outStream.WriteLong(handleRegistry.AllocateCritical(bean)); outStream.SynchronizeOutput(); // 4. Set beans to STARTUP object. _startup.LifecycleBeans = beans; } /// <summary> /// Create lifecycle bean. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Lifecycle bean.</returns> private static ILifecycleBean CreateLifecycleBean(BinaryReader reader) { // 1. Instantiate. var bean = IgniteUtils.CreateInstance<ILifecycleBean>(reader.ReadString()); // 2. Set properties. var props = reader.ReadDictionaryAsGeneric<string, object>(); IgniteUtils.SetProperties(bean, props); return bean; } /// <summary> /// Kernal start callback. /// </summary> /// <param name="interopProc">Interop processor.</param> /// <param name="stream">Stream.</param> internal static void OnStart(IUnmanagedTarget interopProc, IBinaryStream stream) { try { // 1. Read data and leave critical state ASAP. BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(stream); // ReSharper disable once PossibleInvalidOperationException var name = reader.ReadString(); // 2. Set ID and name so that Start() method can use them later. _startup.Name = name; if (Nodes.ContainsKey(new NodeKey(name))) throw new IgniteException("Ignite with the same name already started: " + name); _startup.Ignite = new Ignite(_startup.Configuration, _startup.Name, interopProc, _startup.Marshaller, _startup.LifecycleBeans, _startup.Callbacks); } catch (Exception e) { // 5. Preserve exception to throw it later in the "Start" method and throw it further // to abort startup in Java. _startup.Error = e; throw; } } /// <summary> /// Load assemblies. /// </summary> /// <param name="assemblies">Assemblies.</param> private static void LoadAssemblies(IEnumerable<string> assemblies) { if (assemblies != null) { foreach (string s in assemblies) { // 1. Try loading as directory. if (Directory.Exists(s)) { string[] files = Directory.GetFiles(s, "*.dll"); #pragma warning disable 0168 foreach (string dllPath in files) { if (!SelfAssembly(dllPath)) { try { Assembly.LoadFile(dllPath); } catch (BadImageFormatException) { // No-op. } } } #pragma warning restore 0168 continue; } // 2. Try loading using full-name. try { Assembly assembly = Assembly.Load(s); if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 3. Try loading using file path. try { Assembly assembly = Assembly.LoadFrom(s); if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 4. Not found, exception. throw new IgniteException("Failed to load assembly: " + s); } } } /// <summary> /// Whether assembly points to Ignite binary. /// </summary> /// <param name="assembly">Assembly to check..</param> /// <returns><c>True</c> if this is one of GG assemblies.</returns> private static bool SelfAssembly(string assembly) { return assembly.EndsWith(IgniteDllName, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Gets a named Ignite instance. If Ignite name is {@code null} or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p/> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned. /// </param> /// <returns>An instance of named grid.</returns> public static IIgnite GetIgnite(string name) { lock (SyncRoot) { Ignite result; if (!Nodes.TryGetValue(new NodeKey(name), out result)) throw new IgniteException("Ignite instance was not properly started or was already stopped: " + name); return result; } } /// <summary> /// Gets an instance of default no-name grid. Note that /// caller of this method should not assume that it will return the same /// instance every time. /// </summary> /// <returns>An instance of default no-name grid.</returns> public static IIgnite GetIgnite() { return GetIgnite(null); } /// <summary> /// Stops named grid. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. If /// grid name is <c>null</c>, then default no-name Ignite will be stopped. /// </summary> /// <param name="name">Grid name. If <c>null</c>, then default no-name Ignite will be stopped.</param> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.cancel</c>method.</param> /// <returns><c>true</c> if named Ignite instance was indeed found and stopped, <c>false</c> /// othwerwise (the instance with given <c>name</c> was not found).</returns> public static bool Stop(string name, bool cancel) { lock (SyncRoot) { NodeKey key = new NodeKey(name); Ignite node; if (!Nodes.TryGetValue(key, out node)) return false; node.Stop(cancel); Nodes.Remove(key); GC.Collect(); return true; } } /// <summary> /// Stops <b>all</b> started grids. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. /// </summary> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.Cancel()</c> method.</param> public static void StopAll(bool cancel) { lock (SyncRoot) { while (Nodes.Count > 0) { var entry = Nodes.First(); entry.Value.Stop(cancel); Nodes.Remove(entry.Key); } } GC.Collect(); } /// <summary> /// Handles the AssemblyResolve event of the CurrentDomain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">The <see cref="ResolveEventArgs"/> instance containing the event data.</param> /// <returns>Manually resolved assembly, or null.</returns> private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { return LoadedAssembliesResolver.Instance.GetAssembly(args.Name); } /// <summary> /// Grid key. /// </summary> private class NodeKey { /** */ private readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="NodeKey"/> class. /// </summary> /// <param name="name">The name.</param> internal NodeKey(string name) { _name = name; } /** <inheritdoc /> */ public override bool Equals(object obj) { var other = obj as NodeKey; return other != null && Equals(_name, other._name); } /** <inheritdoc /> */ public override int GetHashCode() { return _name == null ? 0 : _name.GetHashCode(); } } /// <summary> /// Value object to pass data between .Net methods during startup bypassing Java. /// </summary> private class Startup { /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="cbs"></param> internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs) { Configuration = cfg; Callbacks = cbs; } /// <summary> /// Configuration. /// </summary> internal IgniteConfiguration Configuration { get; private set; } /// <summary> /// Gets unmanaged callbacks. /// </summary> internal UnmanagedCallbacks Callbacks { get; private set; } /// <summary> /// Lifecycle beans. /// </summary> internal IList<LifecycleBeanHolder> LifecycleBeans { get; set; } /// <summary> /// Node name. /// </summary> internal string Name { get; set; } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get; set; } /// <summary> /// Start error. /// </summary> internal Exception Error { get; set; } /// <summary> /// Gets or sets the ignite. /// </summary> internal Ignite Ignite { get; set; } } } }
using System; using System.Collections.Generic; using Core.Interfaces; using Core.Model; using Core.SystemWrappers; using Crypto.Providers; using Moq; using NUnit.Framework; using SimpleInjector; using Ui.Console; using Ui.Console.Provider; namespace Integration.CreateKey.Test { [TestFixture] public class CreateRsaKeyTest { private Dictionary<string, byte[]> fileOutput; private Mock<FileWrapper> file; private EncodingWrapper encoding; [SetUp] public void SetupCreateRsaKeyTest() { encoding = new EncodingWrapper(); fileOutput = new Dictionary<string, byte[]>(); file = new Mock<FileWrapper>(); file.Setup(f => f.WriteAllBytes(It.IsAny<string>(), It.IsAny<byte[]>())) .Callback<string, byte[]>((path, content) => { fileOutput.Add(path, content); }); Container container = ContainerProvider.GetContainer(); container.Register<FileWrapper>(() => file.Object); } [TearDown] public void TeardownCreateRsaKeyTest() { ContainerProvider.ClearContainer(); } [TestFixture] public class ErrorCases : CreateRsaKeyTest { [Test] public void ShouldNotAllowKeySizeBelow2048Bits() { var exception = Assert.Throws<ArgumentException>(() => { Certifier.Main(new[] {"-c", "key", "-b", "1024", "--privatekey", "private.pem", "--publickey", "public.pem"}); }); Assert.AreEqual("RSA key size too small. At least 2048 bit keys are required.", exception.Message); } [Test] public void ShouldIndicateMissingPrivateKey() { var exception = Assert.Throws<ArgumentException>(() => { Certifier.Main(new[] {"-c", "key", "-b", "2048", "--publickey", "public.pem"}); }); Assert.AreEqual("Private key file or path is required.", exception.Message); } [Test] public void ShouldIndicateMissingPublicKey() { var exception = Assert.Throws<ArgumentException>(() => { Certifier.Main(new[] {"-c", "key", "-b", "2048", "--privatekey", "private.pem"}); }); Assert.AreEqual("Public key file or path is required.", exception.Message); } [Test] public void ShouldIndicateMissingPassword() { var exception = Assert.Throws<ArgumentException>(() => { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-e", "pkcs", "--privatekey", "private.pem", "--publickey", "public.pem"}); }); Assert.AreEqual("Password is required for encryption.", exception.Message); } } [TestFixture] public class CreateKeyPair : CreateRsaKeyTest { [TestFixture] public class Pkcs8Pem : CreateKeyPair { [Test] public void ShouldWritePkcs8PemFormattedPrivateKey() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "pem", "--privatekey", "private.pem", "--publickey", "public.pem"}); byte[] fileContent = fileOutput["private.pem"]; string content = encoding.GetString(fileContent); Assert.IsTrue(content.Length > 1600 && content.Length < 1800); Assert.IsTrue(content.StartsWith($"-----BEGIN PRIVATE KEY-----{Environment.NewLine}")); Assert.IsTrue(content.EndsWith($"-----END PRIVATE KEY-----{Environment.NewLine}")); } [Test] public void ShouldWritePkcs8PemFormattedPublicKey() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "pem", "--privatekey", "private.pem", "--publickey", "public.pem"}); byte[] fileContent = fileOutput["public.pem"]; string content = encoding.GetString(fileContent); Assert.IsTrue(content.Length > 400 && content.Length < 500); Assert.IsTrue(content.StartsWith($"-----BEGIN PUBLIC KEY-----{Environment.NewLine}")); Assert.IsTrue(content.EndsWith($"-----END PUBLIC KEY-----{Environment.NewLine}")); } [Test] public void ShouldCreateValidPkcs8PemFormattedKeyPair() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "pem", "--privatekey", "private.pem", "--publickey", "public.pem"}); byte[] privateKeyFileContent = fileOutput["private.pem"]; byte[] publicKeyFileContent = fileOutput["public.pem"]; string privateKeyContent = encoding.GetString(privateKeyFileContent); string publicKeyContent = encoding.GetString(publicKeyFileContent); var container = ContainerProvider.GetContainer(); var pkcs8FormattingProvider = container.GetInstance<IPemFormattingProvider<IAsymmetricKey>>(); var rsaKeyProvider = container.GetInstance<RsaKeyProvider>(); IAsymmetricKey privateKey = pkcs8FormattingProvider.GetAsDer(privateKeyContent); IAsymmetricKey publicKey = pkcs8FormattingProvider.GetAsDer(publicKeyContent); Assert.IsTrue(rsaKeyProvider.VerifyKeyPair(new AsymmetricKeyPair(privateKey, publicKey))); } [TestFixture] public class PkcsEncrypted : Pkcs8Pem { [Test] public void ShouldWritePkcs8PemFormattedEncryptedPrivateKey() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "pem", "--privatekey", "private.pem", "--publickey", "public.pem", "-e", "pkcs", "-p", "foobar"}); byte[] fileContent = fileOutput["private.pem"]; string content = encoding.GetString(fileContent); Assert.IsTrue(content.Length > 3100 && content.Length < 3300); Assert.IsTrue(content.StartsWith($"-----BEGIN ENCRYPTED PRIVATE KEY-----{Environment.NewLine}")); Assert.IsTrue(content.EndsWith($"-----END ENCRYPTED PRIVATE KEY-----{Environment.NewLine}")); } [Test] public void ShouldWritePkcs8PemFormattedPublicKeyToGivenFile() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "pem", "--privatekey", "private.pem", "--publickey", "public.pem", "-e", "pkcs", "-p", "foobar"}); byte[] fileContent = fileOutput["public.pem"]; string content = encoding.GetString(fileContent); Assert.IsTrue(content.Length > 400 && content.Length < 500); Assert.IsTrue(content.StartsWith($"-----BEGIN PUBLIC KEY-----{Environment.NewLine}")); Assert.IsTrue(content.EndsWith($"-----END PUBLIC KEY-----{Environment.NewLine}")); } [Test] public void ShouldCreateValidKeyPair() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "pem", "--privatekey", "private.pem", "--publickey", "public.pem", "-e", "pkcs", "-p", "foobar"}); byte[] privateKeyFileContent = fileOutput["private.pem"]; byte[] publicKeyFileContent = fileOutput["public.pem"]; string privateKeyContent = encoding.GetString(privateKeyFileContent); string publicKeyContent = encoding.GetString(publicKeyFileContent); var container = ContainerProvider.GetContainer(); var pkcs8FormattingProvider = container.GetInstance<IPemFormattingProvider<IAsymmetricKey>>(); var rsaKeyProvider = container.GetInstance<RsaKeyProvider>(); var encryptionProvider = container.GetInstance<KeyEncryptionProvider>(); IAsymmetricKey privateKey = pkcs8FormattingProvider.GetAsDer(privateKeyContent); IAsymmetricKey publicKey = pkcs8FormattingProvider.GetAsDer(publicKeyContent); IAsymmetricKey decryptedPrivateKey = encryptionProvider.DecryptPrivateKey(privateKey, "foobar"); Assert.IsTrue(rsaKeyProvider.VerifyKeyPair(new AsymmetricKeyPair(decryptedPrivateKey, publicKey))); } } [TestFixture] public class AesEncrypted : Pkcs8Pem { [Test] public void ShouldWritePkcs8PemFormattedEncryptedPrivateKey() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "pem", "--privatekey", "private.pem", "--publickey", "public.pem", "-e", "aes", "-p", "foobar"}); byte[] fileContent = fileOutput["private.pem"]; string content = encoding.GetString(fileContent); Assert.IsTrue(content.Length > 3100 && content.Length < 3300); Assert.IsTrue(content.StartsWith($"-----BEGIN ENCRYPTED PRIVATE KEY-----{Environment.NewLine}")); Assert.IsTrue(content.EndsWith($"-----END ENCRYPTED PRIVATE KEY-----{Environment.NewLine}")); } [Test] public void ShouldWritePkcs8PemFormattedPublicKeyToGivenFile() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "pem", "--privatekey", "private.pem", "--publickey", "public.pem", "-e", "aes", "-p", "foobar"}); byte[] fileContent = fileOutput["public.pem"]; string content = encoding.GetString(fileContent); Assert.IsTrue(content.Length > 400 && content.Length < 500); Assert.IsTrue(content.StartsWith($"-----BEGIN PUBLIC KEY-----{Environment.NewLine}")); Assert.IsTrue(content.EndsWith($"-----END PUBLIC KEY-----{Environment.NewLine}")); } [Test] public void ShouldCreateValidKeyPair() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "pem", "--privatekey", "private.pem", "--publickey", "public.pem", "-e", "aes", "-p", "foobar"}); byte[] privateKeyFileContent = fileOutput["private.pem"]; byte[] publicKeyFileContent = fileOutput["public.pem"]; string privateKeyContent = encoding.GetString(privateKeyFileContent); string publicKeyContent = encoding.GetString(publicKeyFileContent); var container = ContainerProvider.GetContainer(); var pkcs8FormattingProvider = container.GetInstance<IPemFormattingProvider<IAsymmetricKey>>(); var rsaKeyProvider = container.GetInstance<RsaKeyProvider>(); var encryptionProvider = container.GetInstance<KeyEncryptionProvider>(); IAsymmetricKey privateKey = pkcs8FormattingProvider.GetAsDer(privateKeyContent); IAsymmetricKey publicKey = pkcs8FormattingProvider.GetAsDer(publicKeyContent); IAsymmetricKey decryptedPrivateKey = encryptionProvider.DecryptPrivateKey(privateKey, "foobar"); Assert.IsTrue(rsaKeyProvider.VerifyKeyPair(new AsymmetricKeyPair(decryptedPrivateKey, publicKey))); } } } [TestFixture] public class Pkcs8Der : CreateKeyPair { [Test] public void ShouldCreateValidPkcs8DerFormattedKeyPair() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "--privatekey", "private.der", "--publickey", "public.der", "-t", "der"}); byte[] privateKeyFileContent = fileOutput["private.der"]; byte[] publicKeyFileContent = fileOutput["public.der"]; var container = ContainerProvider.GetContainer(); var asymmetricKeyProvider = container.GetInstance<IAsymmetricKeyProvider>(); var rsaKeyProvider = container.GetInstance<IKeyProvider<RsaKey>>(); IAsymmetricKey privateKey = asymmetricKeyProvider.GetPrivateKey(privateKeyFileContent); IAsymmetricKey publicKey = asymmetricKeyProvider.GetPublicKey(publicKeyFileContent); Assert.IsTrue(rsaKeyProvider.VerifyKeyPair(new AsymmetricKeyPair(privateKey, publicKey))); } [TestFixture] public class PkcsEncrypted : Pkcs8Der { [Test] public void ShouldCreateValidKeyPair() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "--privatekey", "private.der", "--publickey", "public.der", "-e", "pkcs", "-p", "foobar", "-t", "der"}); byte[] privateKeyFileContent = fileOutput["private.der"]; byte[] publicKeyFileContent = fileOutput["public.der"]; var container = ContainerProvider.GetContainer(); var asymmetricKeyProvider = container.GetInstance<IAsymmetricKeyProvider>(); var rsaKeyProvider = container.GetInstance<IKeyProvider<RsaKey>>(); var encryptionProvider = container.GetInstance<KeyEncryptionProvider>(); IAsymmetricKey encryptedPrivateKey = asymmetricKeyProvider.GetEncryptedPrivateKey(privateKeyFileContent); IAsymmetricKey privateKey = encryptionProvider.DecryptPrivateKey(encryptedPrivateKey, "foobar"); IAsymmetricKey publicKey = asymmetricKeyProvider.GetPublicKey(publicKeyFileContent); Assert.IsTrue(rsaKeyProvider.VerifyKeyPair(new AsymmetricKeyPair(privateKey, publicKey))); } } [TestFixture] public class AesEncrypted : Pkcs8Der { [Test] public void ShouldCreateValidKeyPair() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "--privatekey", "private.der", "--publickey", "public.der", "-e", "aes", "-p", "foobar", "-t", "der"}); byte[] privateKeyFileContent = fileOutput["private.der"]; byte[] publicKeyFileContent = fileOutput["public.der"]; var container = ContainerProvider.GetContainer(); var asymmetricKeyProvider = container.GetInstance<IAsymmetricKeyProvider>(); var rsaKeyProvider = container.GetInstance<IKeyProvider<RsaKey>>(); var encryptionProvider = container.GetInstance<KeyEncryptionProvider>(); IAsymmetricKey encryptedPrivateKey = asymmetricKeyProvider.GetEncryptedPrivateKey(privateKeyFileContent); IAsymmetricKey privateKey = encryptionProvider.DecryptPrivateKey(encryptedPrivateKey, "foobar"); IAsymmetricKey publicKey = asymmetricKeyProvider.GetPublicKey(publicKeyFileContent); Assert.IsTrue(rsaKeyProvider.VerifyKeyPair(new AsymmetricKeyPair(privateKey, publicKey))); } } } [TestFixture] public class OpenSSh : CreateKeyPair { [Test] public void ShouldWritePkcs8PemFormattedPrivateKey() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "openssh", "--privatekey", "private.pem", "--publickey", "public.openssh"}); byte[] fileContent = fileOutput["private.pem"]; string content = encoding.GetString(fileContent); Assert.IsTrue(content.Length > 1600 && content.Length < 1800); Assert.IsTrue(content.StartsWith($"-----BEGIN PRIVATE KEY-----{Environment.NewLine}")); Assert.IsTrue(content.EndsWith($"-----END PRIVATE KEY-----{Environment.NewLine}")); } [Test] public void ShouldWriteOpenSshFormattedPublicKey() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "openssh", "--privatekey", "private.pem", "--publickey", "public.openssh"}); byte[] fileContent = fileOutput["public.openssh"]; string content = encoding.GetString(fileContent); string[] splitContent = content.Split((' ')); Assert.AreEqual("ssh-rsa", splitContent[0]); } [Test] public void ShouldCreateValidKeyPair() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "openssh", "--privatekey", "private.pem", "--publickey", "public.openssh"}); byte[] fileContent = fileOutput["public.openssh"]; string content = encoding.GetString(fileContent); string[] splitContent = content.Split((' ')); var container = ContainerProvider.GetContainer(); var sshKeyProvider = container.GetInstance<ISshKeyProvider>(); var rsaKeyProvider = container.GetInstance<RsaKeyProvider>(); var pkcs8FormattingProvider = container.GetInstance<IPemFormattingProvider<IAsymmetricKey>>(); string privateKeyContent = encoding.GetString(fileOutput["private.pem"]); IAsymmetricKey privateKey = pkcs8FormattingProvider.GetAsDer(privateKeyContent); IAsymmetricKey publicKey = sshKeyProvider.GetKeyFromSsh(splitContent[1]); Assert.IsTrue(rsaKeyProvider.VerifyKeyPair(new AsymmetricKeyPair(privateKey, publicKey))); } } [TestFixture] public class Ssh2 : CreateKeyPair { [Test] public void ShouldWritePkcs8PemFormattedPrivateKey() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "ssh2", "--privatekey", "private.pem", "--publickey", "public.ssh2"}); byte[] fileContent = fileOutput["private.pem"]; string content = encoding.GetString(fileContent); Assert.IsTrue(content.Length > 1600 && content.Length < 1800); Assert.IsTrue(content.StartsWith($"-----BEGIN PRIVATE KEY-----{Environment.NewLine}")); Assert.IsTrue(content.EndsWith($"-----END PRIVATE KEY-----{Environment.NewLine}")); } [Test] public void ShouldWriteSsh2FormattedPublicKey() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "ssh2", "--privatekey", "private.pem", "--publickey", "public.ssh2"}); byte[] fileContent = fileOutput["public.ssh2"]; string content = encoding.GetString(fileContent); Assert.IsTrue(content.StartsWith($"---- BEGIN SSH2 PUBLIC KEY ----{Environment.NewLine}")); Assert.IsTrue(content.EndsWith($"---- END SSH2 PUBLIC KEY ----")); } [Test] public void ShouldCreateValidKeyPair() { Certifier.Main(new[] {"-c", "key", "-b", "2048", "-t", "ssh2", "--privatekey", "private.pem", "--publickey", "public.ssh2"}); byte[] fileContent = fileOutput["public.ssh2"]; string content = encoding.GetString(fileContent); var container = ContainerProvider.GetContainer(); var sshFormattingProvider = container.GetInstance<ISshFormattingProvider>(); var rsaKeyProvider = container.GetInstance<RsaKeyProvider>(); var pkcs8FormattingProvider = container.GetInstance<IPemFormattingProvider<IAsymmetricKey>>(); string privateKeyContent = encoding.GetString(fileOutput["private.pem"]); IAsymmetricKey privateKey = pkcs8FormattingProvider.GetAsDer(privateKeyContent); IAsymmetricKey publicKey = sshFormattingProvider.GetAsDer(content); Assert.IsTrue(rsaKeyProvider.VerifyKeyPair(new AsymmetricKeyPair(privateKey, publicKey))); } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using UniTestAssert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert; using System.IO; using LTAF.Engine; using System.Threading; using System.Text.RegularExpressions; using System.Resources; using System.Reflection; using Moq; namespace LTAF.UnitTests.UI { [TestClass] public class HtmlElementCollectionTest { private Mock<IBrowserCommandExecutorFactory> _commandExecutorFactory; [TestInitialize] public void FixtureSetup() { _commandExecutorFactory = new Mock<IBrowserCommandExecutorFactory>(); ServiceLocator.BrowserCommandExecutorFactory = _commandExecutorFactory.Object; ServiceLocator.ApplicationPathFinder = new ApplicationPathFinder("http://test"); } [TestMethod] public void WhenCallingExistsById_IfElementExists_ShouldReturnTrue() { // Arrange string html = @" <html id='control1'> <foo id='control2'> <bar id='control3' /> </foo> </html> "; HtmlElement element = HtmlElement.Create(html); //Act, Assert Assert.IsTrue(element.ChildElements.Exists("control3")); } [TestMethod] public void WhenCallingExistsById_IfElementDoesNotExists_ShouldReturnFalse() { //Arrange string html = @" <html id='control1'> <foo id='control2'> <bar id='control3' /> </foo> </html> "; HtmlElement element = HtmlElement.Create(html); //Act,Assert Assert.IsFalse(element.ChildElements.Exists(new HtmlElementFindParams("control4"), 0)); } [TestMethod] public void WhenCallingExistsByRegex_IfElementExists_ShouldReturnTrue() { //Arrange string html = @" <html id='control1'> <foo id='ctl0_control2'> <bar id='ctl1_control2' /> </foo> </html> "; HtmlElement element = HtmlElement.Create(html); //Act,Assert Assert.IsTrue(element.ChildElements.Exists("ctl1.*", MatchMethod.Regex)); } [TestMethod] public void WhenCallingExistsByRegex_IfElementDoesNotExists_ShouldReturnFalse() { //Arrange string html = @" <html id='control1'> <foo id='ctl0_control2'> <bar id='ctl1_control2' /> </foo> </html> "; HtmlElement element = HtmlElement.Create(html); //Act,Assert Assert.IsFalse(element.ChildElements.Exists(new HtmlElementFindParams("ctl3.*", MatchMethod.Regex), 0)); } [TestMethod] public void WhenCallingFindByIdEndsWith_ShouldReturnTheElement() { //Arrange string html = @" <html id='control1'> <foo id='control2'> <bar id='ctl_control3' /> <invalid id='control3' /> </foo> </html> "; HtmlElement element = HtmlElement.Create(html); //Act,Assert Assert.AreEqual("bar", element.ChildElements.Find("control3").TagName); } [TestMethod] public void WhenCallingFindByTag_ShouldReturnTheElement() { //Arrange string html = @" <html id='control1'> <div id='control2'> <div id='control3' /> </div> <div id='control4' /> </html> "; HtmlElement element = HtmlElement.Create(html); //Act,Assert Assert.AreEqual("control3", element.ChildElements.Find("div", 1).Id); Assert.AreEqual("control4", element.ChildElements.Find("div", 2).Id); } [TestMethod] public void WhenCallingFindByIdEndsWithAndIndex_ShouldReturnTheElement() { //Arrange string html = @" <html> <div id='control1'> <div id='control1' foo=bar /> </div> <div id='control1' /> </html> "; HtmlElement element = HtmlElement.Create(html); //Act,Assert HtmlElementFindParams findParams = new HtmlElementFindParams("control1"); findParams.Index = 1; Assert.AreEqual("bar", element.ChildElements.Find(findParams).GetAttributes().Dictionary["foo"]); } [TestMethod] public void WhenCallingFindByTagAndIndex_ShouldReturnTheElement() { //Arrange string html = @" <html> <div id='control1'> <div id='control1' foo='bar' /> </div> <div id='control1' test='a' /> </html> "; HtmlElement element = HtmlElement.Create(html); //Act,Assert HtmlElementFindParams findParams = new HtmlElementFindParams(); findParams.TagName = "div"; findParams.Index = 2; Assert.AreEqual("a", element.ChildElements.Find(findParams).GetAttributes().Dictionary["test"]); } [TestMethod] public void WhenCallingFindByInnerTextAndIndex_ShouldReturnTheElement() { string html = @" <html> <div foo='a' id='control1' > <div id='control2' foo='b'> some text </div> </div> <div id='control3' foo='c'> some text </div> </html> "; HtmlElement element = HtmlElement.Create(html); HtmlElementFindParams findParams = new HtmlElementFindParams(); findParams.InnerText = "some text"; findParams.Index = 1; Assert.AreEqual("control3", element.ChildElements.Find(findParams).Id); } [TestMethod] public void WhenCallingFindByTagInerTextAndIndex_ShouldReturnTheElement() { string html = @" <html> <div foo='a' id='control1' > <span id='control2' foo='b'> some text </span> </div> <div id='control3' foo='c'> some text </div> <span id='control4'> some text </span> </html> "; HtmlElement element = HtmlElement.Create(html); HtmlElementFindParams findParams = new HtmlElementFindParams(); findParams.TagName = "span"; findParams.InnerText = "some text"; findParams.Index = 1; Assert.AreEqual("control4", element.ChildElements.Find(findParams).Id); } [TestMethod] public void WhenCallingFindByTagInerTextAndIndex_IfMultipleSiblingsMatsh_ShouldReturnTheElement() { string html = @" <html> <div foo=foo bar=bar> <span foo=foo bar=bar>text</span> <div foo=foo bar=bar>text</div> <span foo=foo /> <span bar=bar /> <span foo=foo bar=bar>wrong</span> <span foo=foo bar=bar id='span1'>text</span> </div> </html> "; HtmlElement element = HtmlElement.Create(html); HtmlElementFindParams findParams = new HtmlElementFindParams(); findParams.TagName = "span"; findParams.InnerText = "text"; findParams.Index = 1; Assert.AreEqual("span1", element.ChildElements.Find(findParams).Id); } [TestMethod] public void WhenCallingFind_IfElementDoestNotExist_ShouldThrowAnException() { // Arrange string html = @" <html id='control1'> <foo id='control2'> <bar id='control3' /> </foo> </html> "; HtmlElement element = HtmlElement.Create(html); HtmlElementFindParams p = new HtmlElementFindParams("control4"); // Act/Assert ExceptionAssert.Throws<ElementNotFoundException>( () => element.ChildElements.Find(p, 0)); } [TestMethod] public void WhenCallingFindByAllParameters_ShouldReturnElement() { string html = @" <html> <div foo=foo bar=bar> <span foo=foo bar=bar>text</span> <div foo=foo bar=bar>text</div> <span foo=foo /> <span bar=bar /> <span foo=foo bar=bar>wrong</span> <span foo=foo bar=bar id='span1'>text</span> </div> </html> "; HtmlElement element = HtmlElement.Create(html); HtmlElementFindParams findParams = new HtmlElementFindParams(); findParams.Attributes.Add("foo", "foo"); findParams.Attributes.Add("bar", "bar"); findParams.TagName = "span"; findParams.InnerText = "text"; findParams.Index = 1; Assert.AreEqual("span1", element.ChildElements.Find(findParams).Id); } [TestMethod] public void WhenCallingFind_IfTagIsKnown_ShouldReturnAStrongTypedElement() { string html = @" <html id='control1'> <input id='control2' type='button' /> <a id='control3' href='foo' /> <select id='control4' value='bar' /> </html> "; HtmlElement element = HtmlElement.Create(html); Assert.AreEqual(HtmlInputElementType.Button, ((HtmlInputElement)element.ChildElements.Find("control2")).GetAttributes().Type); Assert.AreEqual("foo", ((HtmlAnchorElement)element.ChildElements.Find("control3")).GetAttributes().HRef); Assert.AreEqual("bar", ((HtmlSelectElement)element.ChildElements.Find("control4")).GetAttributes().Value); } [TestMethod] public void WhenCallingFindAllByTag_IfNoMatchesExist_ShouldReturnEmptyCollection() { string html = @" <html> <div id='div1'> </div> </html> "; HtmlElement element = HtmlElement.Create(html); Assert.AreEqual(0, element.ChildElements.FindAll(new HtmlElementFindParams("div2"), 0).Count); } [TestMethod] public void WhenCallingFindAllByTag_IfMatchingElementsAreNested_ShouldReturnCollectionWithAllOfThem() { string html = @" <html> <div id='div1'> <div id='div2'> <div id='div3'> </div> </div> </div> </html> "; HtmlElement element = HtmlElement.Create(html); ReadOnlyCollection<HtmlElement> divs = element.ChildElements.FindAll("div"); Assert.AreEqual(3, divs.Count); Assert.AreEqual("div3", divs[2].Id); } [TestMethod] public void WhenCallingFindAllByTagAndInnerText_ShouldReturnMatchedElements() { string html = @" <html> <div id='div1'> Zoo <div id='div2'>Foo <div id='div3'>Bar </div> </div> </div> </html> "; HtmlElement element = HtmlElement.Create(html); ReadOnlyCollection<HtmlElement> divs = element.ChildElements.FindAll("div", "Bar"); Assert.AreEqual(1, divs.Count); Assert.AreEqual("div3", divs[0].Id); } [TestMethod] public void WhenCallingFindByIdLiteral_ShouldReturnMatchedElement() { string html = @" <html> <div id='ctl0_foo' /> <span id='foo' /> </html> "; HtmlElement element = HtmlElement.Create(html); Assert.AreEqual("span", element.ChildElements.Find("foo", MatchMethod.Literal).TagName); } [TestMethod] public void WhenCallingFindByIdRegex_ShouldReturnMatchedElement() { string html = @" <html> <span id='foo' /> <div id='ctl0_foo' /> </html> "; HtmlElement element = HtmlElement.Create(html); Assert.AreEqual("span", element.ChildElements.Find("^foo$", MatchMethod.Regex).TagName); } [TestMethod] public void WhenCallingFindByIdRegex_IfFullMatch_ShouldReturnMatchedElement() { string html = @" <html> <div id='ctl0_foo' /> <span id='foo' /> </html> "; HtmlElement element = HtmlElement.Create(html); Assert.AreEqual("div", element.ChildElements.Find("foo", MatchMethod.Regex).TagName); } [TestMethod] public void WhenCallingFindByIdRegex_IfMatchesTheBginning_ShouldReturnMatchedElement() { string html = @" <html> <div id='ctl0_foo' /> <span id='foo' /> </html> "; HtmlElement element = HtmlElement.Create(html); Assert.AreEqual("span", element.ChildElements.Find("^foo", MatchMethod.Regex).TagName); } [TestMethod] public void WhenCallingFindByIdRegex_IfMatchContainsWildCards_ShouldReturnMatchedElement() { string html = @" <html> <div id='LoginView1'> <span id='LoginView1_foo' /> </div> </html> "; HtmlElement element = HtmlElement.Create(html); Assert.AreEqual("span", element.ChildElements.Find("LoginView1.*foo", MatchMethod.Regex).TagName); } [TestMethod] public void WhenCallingFindByIdRegex_IfMatchContainsWildCardsAndIdContainsAspNetAutoId_ShouldReturnMatchedElement() { string html = @" <html> <div id='LoginView1'> <span id='LoginView1_ctl03_GridView1_ctl01_foo' /> </div> </html> "; HtmlElement element = HtmlElement.Create(html); Assert.AreEqual("span", element.ChildElements.Find("LoginView1.*foo", MatchMethod.Regex).TagName); } [TestMethod] public void WhenCallingFindByIdRegex_IfNoMatchFound_ShouldThrowError() { //Arrange string html = @" <html> </html> "; //Act,Assert HtmlElement element = HtmlElement.Create(html); HtmlElementFindParams findParams = new HtmlElementFindParams("foo.*bar", MatchMethod.Regex); ExceptionAssert.Throws<ElementNotFoundException>( () => element.ChildElements.Find(findParams, 0)); } [TestMethod] public void WhenCallingFindByIdRegex_IfCaseDoNotMatch_ShouldReturnTheElement() { string html = @" <html> <div id='LoginView1'> <span id='LoginView1_ctl03_GridView1_ctl01_foo' /> </div> </html> "; HtmlElement element = HtmlElement.Create(html); Assert.AreEqual("span", element.ChildElements.Find("LOGINVIEW1.*GRIDVIEW1.*FOO", MatchMethod.Regex).TagName); } [TestMethod] public void WhenCallingFindByIdRegexWithWildards_IfDoNotMatch_ShouldThrowAnError() { //Arrange string html = @" <html> <div id='LoginView1'> <span id='LoginView1_ctl03_GridView1_ctl01_foo' /> </div> </html> "; HtmlElement element = HtmlElement.Create(html); //Act,Assert ExceptionAssert.Throws<ElementNotFoundException>( () => element.ChildElements.Find(new HtmlElementFindParams("LoginView1.*GridView1.*bar", MatchMethod.Regex), 0)); } [TestMethod] public void WhenCallingFind_IfLoadingSourceFromLiveDotCom_ShouldLocateElements() { // live.com Assembly unitTestAssembly = Assembly.GetExecutingAssembly(); using (StreamReader reader = new StreamReader(unitTestAssembly.GetManifestResourceStream("LTAF.UnitTests.UI.TestFiles.TextFile1.txt"))) { string html = reader.ReadToEnd(); HtmlElement element = HtmlElement.Create(html, null, true); Assert.AreEqual("Sign in", element.ChildElements.Find("ppToolBar").ChildElements.Find("signIn").CachedInnerText); } } [TestMethod] public void WhenCallingFind_IfLoadingSourceFromHotmailDotCom_ShouldLocateElements() { // Hotmail.com Assembly unitTestAssembly = Assembly.GetExecutingAssembly(); using (StreamReader reader = new StreamReader(unitTestAssembly.GetManifestResourceStream("LTAF.UnitTests.UI.TestFiles.TextFile2.txt"))) { string html = reader.ReadToEnd(); HtmlElement element = HtmlElement.Create(html, null, true); Assert.AreEqual("fa:layout", element.ChildElements.Find("ContactEdit").TagName); HtmlElement name = element.ChildElements.Find("FirstLastName"); Assert.AreEqual("Federico Silva Armas", name.CachedInnerText); Assert.AreEqual("BoldText", name.GetAttributes().Dictionary["class"]); Assert.AreEqual("Contacts", element.ChildElements.Find("SearchContacts").ChildElements.Find("span", 0).CachedInnerText); Assert.AreEqual("text", element.ChildElements.Find("FindBySubjectInput").GetAttributes().Dictionary["type"]); } } [TestMethod] public void WhenRefreshing_ShouldNotGetGetAttributes() { MockCommandExecutor commandExecutor = new MockCommandExecutor(); _commandExecutorFactory.Setup(m => m.CreateBrowserCommandExecutor(It.IsAny<string>(), It.IsAny<HtmlPage>())).Returns(commandExecutor); var testPage = new HtmlPage(); string html = @" <html id='control1'> <span id='MySpan' randomAttribute='foo'> Span text </span> </html> "; commandExecutor.SetBrowserInfo(new LTAF.Engine.BrowserInfo() { Data = @"<span id='MySpan' randomAttribute='bar'> Span text </span>" }); var element = HtmlElement.Create(html, testPage, false); var span = element.ChildElements.Find("MySpan"); span.ChildElements.Refresh(); Assert.IsNull(commandExecutor.ExecutedCommands[0].Handler.Arguments); } [TestMethod] public void WhenRefreshing_IfPassingOneAttribute_ShouldRefreshDomIncludingThatAttribute() { MockCommandExecutor commandExecutor = new MockCommandExecutor(); _commandExecutorFactory.Setup(m => m.CreateBrowserCommandExecutor(It.IsAny<string>(), It.IsAny<HtmlPage>())).Returns(commandExecutor); var testPage = new HtmlPage(); string html = @" <html id='control1'> <span id='MySpan' randomAttribute='foo'> Span text </span> </html> "; commandExecutor.SetBrowserInfo(new LTAF.Engine.BrowserInfo() { Data = @"<span id='MySpan' randomAttribute='bar'> Span text </span>" }); var element = HtmlElement.Create(html, testPage, false); var span = element.ChildElements.Find("MySpan"); span.ChildElements.Refresh(new string[] { "randomAttribute" }); Assert.AreEqual("randomattribute", commandExecutor.ExecutedCommands[0].Handler.Arguments[0]); } [TestMethod] public void WhenRefreshing_IfPassingTwoAttribute_ShouldRefreshDomIncludingThoseAttributes() { MockCommandExecutor commandExecutor = new MockCommandExecutor(); _commandExecutorFactory.Setup(m => m.CreateBrowserCommandExecutor(It.IsAny<string>(), It.IsAny<HtmlPage>())).Returns(commandExecutor); var testPage = new HtmlPage(); string html = @" <html id='control1'> <span id='MySpan' randomAttribute='foo'> Span text </span> </html> "; commandExecutor.SetBrowserInfo(new LTAF.Engine.BrowserInfo() { Data = @"<span id='MySpan' randomAttribute='bar'> Span text </span>" }); var element = HtmlElement.Create(html, testPage, false); var span = element.ChildElements.Find("MySpan"); span.ChildElements.Refresh(new string[] { "randomAttribute", "anotherAttribute" }); Assert.AreEqual("randomattribute-anotherattribute", commandExecutor.ExecutedCommands[0].Handler.Arguments[0]); } [TestMethod] public void WhenCallingFindAfter_ShouldNotSearchDescendants() { //Arrange string html = @" <html id='control1'> <div id='CURRENT'> <input id='target' type='button' /> <a id='control3' href='foo' /> <select id='TARGET' value='bar' /> </div> </html> "; HtmlElement root = HtmlElement.Create(html); var current = root.ChildElements.Find("CURRENT"); //Act,Assert ExceptionAssert.ThrowsElementNotFound( () => root.ChildElements.FindAfter(current, new HtmlElementFindParams("TARGET"))); } [TestMethod] public void WhenCallingFindAfter_ShouldNotReturnPriorSiblings() { //Arrange string html = @" <html id='control1'> <input id='control2' type='button' /> <a id='control3' href='foo' /> <select id='control4' value='bar' /> </html> "; HtmlElement root = HtmlElement.Create(html); var control3 = root.ChildElements.Find("control3"); //Act,Assert ExceptionAssert.ThrowsElementNotFound( () => root.ChildElements.FindAfter(control3, new HtmlElementFindParams("control2"))); } [TestMethod] public void WhenCallingFindAfter_ShouldReturnsFollowingSiblings() { string html = @" <html id='control1'> <input id='control2' type='button' /> <a id='CURRENT' href='foo' /> <select id='control4' value='bar' /> <select id='control5' value='bar' /> </html> "; HtmlElement root = HtmlElement.Create(html); var current = root.ChildElements.Find("CURRENT"); Assert.AreEqual("control4", root.ChildElements.FindAfter(current, new HtmlElementFindParams("control4")).Id); Assert.AreEqual("control5", root.ChildElements.FindAfter(current, new HtmlElementFindParams("control5")).Id); } [TestMethod] public void WhenCallingFindAfter_IfMatchIsOutsideOFCollection_ShouldReturnError() { //Arrange string html = @" <html id='control1'> <input id='control2' type='button' /> <span id='COLLECTION'> <a id='CURRENT' href='foo' /> </span> <span id='TARGET'/> <select id='control4' value='bar' /> <select id='control5' value='bar' /> </html> "; HtmlElement root = HtmlElement.Create(html); var collection = root.ChildElements.Find("COLLECTION").ChildElements; var current = root.ChildElements.Find("CURRENT"); //Act,Assert ExceptionAssert.ThrowsElementNotFound( () => collection.FindAfter(current, "TARGET")); } [TestMethod] public void WhenCallingFindAfter_IfCannotFindElementAndRootIsThePage_ShouldThrowError() { //Arrange string html = @" <html id='control1'> <input id='control2' type='button' /> <span id='something'> <a id='CURRENT' href='foo' /> </span> <span id='something'/> <select id='control4' value='bar' /> <select id='control5' value='bar' /> </html> "; HtmlElement root = HtmlElement.Create(html); var current = root.ChildElements.Find("CURRENT"); HtmlElementCollection pageCollection = new HtmlElementCollection(root.ChildElements, root.ParentPage, null); //Act,Assert ExceptionAssert.ThrowsElementNotFound( () => pageCollection.FindAfter(current, "TARGET")); } [TestMethod] public void WhenCallingFindAfter_IfRootIsThePage_ShouldReturnElement() { string html = @" <html id='control1'> <input id='control2' type='button' /> <span id='something'> <a id='CURRENT' href='foo' /> </span> <span id='TARGET'/> <select id='control4' value='bar' /> <select id='control5' value='bar' /> </html> "; HtmlElement root = HtmlElement.Create(html); var current = root.ChildElements.Find("CURRENT"); HtmlElementCollection pageCollection = new HtmlElementCollection(root.ChildElements, root.ParentPage, null); Assert.AreEqual("TARGET", pageCollection.FindAfter(current, "TARGET").Id); } [TestMethod] public void WhenCallingFindAfter_ShouldReturnFollowingChildrenOfSiblings() { string html = @" <html id='control1'> <input id='somecontrol0' type='button' /> <a id='current' href='foo' /> <span id='sibling'> <span id='somecontrol1' /> <span id='somecontrol2' /> </span> <span id='sibling2'> <span id='somecontrol1' /> <span id='targetControl' /> </span> </html> "; HtmlElement root = HtmlElement.Create(html); var control3 = root.ChildElements.Find("current"); Assert.AreEqual("targetControl", root.ChildElements.FindAfter(control3, new HtmlElementFindParams("targetControl")).Id); } [TestMethod] public void WhenCallingFindAfter_IfMatchIsPriorChildrenOfSiblings_ShouldThrowError() { //Arrange string html = @" <html id='control1'> <input id='somecontrol0' type='button' /> <span id='sibling2'> <span id='somecontrol1' /> <span id='targetControl' /> </span> <a id='current' href='foo' /> <span id='sibling'> <span id='somecontrol1' /> <span id='somecontrol2' /> </span> <span id='sibling2'> <span id='somecontrol1' /> </span> </html> "; HtmlElement root = HtmlElement.Create(html); var control3 = root.ChildElements.Find("current"); //Act,Assert ExceptionAssert.ThrowsElementNotFound( () => root.ChildElements.FindAfter(control3, new HtmlElementFindParams("targetControl"))); } [TestMethod] public void WhenCallingFindAfter_ShouldReturnChildrenOfAncestorsSiblings() { string html = @" <html id='control1'> <input id='somecontrol0' type='button' /> <a id='somecontrol5' href='foo' /> <span id='TARGET' title='before'/> <span id='priorSibling'> <span id='somecontrol1' /> <span id='TARGET' title='before'/> </span> <span id='sibling'> <span id='somecontrol1' /> <span id='CURRENT' /> <span id='somecontrol3' /> </span> <span id='sibling2'> <span id='somecontrol1' /> <span id='TARGET' title='after'/> </span> </html> "; HtmlElement root = HtmlElement.Create(html); var control3 = root.ChildElements.Find("CURRENT"); Assert.AreEqual("TARGET", root.ChildElements.FindAfter(control3, new HtmlElementFindParams("TARGET")).Id); Assert.AreEqual("after", root.ChildElements.FindAfter(control3, new HtmlElementFindParams("TARGET")).GetAttributes().Title); } [TestMethod] public void WhenCallingFindAfter_ShouldReturnSiblingsOfParent() { string html = @" <html id='control1'> <span id='something'> <span id='CURRENT' title='before'>NewLast</span> <span id='somecontrol1' /> </span> <INPUT id='ListView1_ctrl6_ctl03_DeleteButton'/> </html> "; HtmlElement root = HtmlElement.Create(html); var control3 = root.ChildElements.Find("span", "NewLast", 0); Assert.AreEqual("ListView1_ctrl6_ctl03_DeleteButton", root.ChildElements.FindAfter(control3, "DeleteButton").Id); } [TestMethod] public void WhenCallingFindAfter_IfParentOfCurrentMatches_ShouldNotBeReturned() { string html = @" <html id='control1'> <span id='TARGET' title='before'> <span id='somecontrol1' /> <span id='CURRENT' /> <span id='somecontrol3' /> </span> <span id='sibling2'> <span id='somecontrol1' /> <span id='TARGET' title='after'/> </span> </html> "; HtmlElement root = HtmlElement.Create(html); var current = root.ChildElements.Find("CURRENT"); Assert.AreEqual("TARGET", root.ChildElements.FindAfter(current, new HtmlElementFindParams("TARGET")).Id); Assert.AreEqual("after", root.ChildElements.FindAfter(current, new HtmlElementFindParams("TARGET")).GetAttributes().Title); } [TestMethod] public void WhenCallingFindAfter_IfPrecedingElementIsAfterTheCollection_ShouldThrowError() { //Arrange string html = @" <html id='control1'> <span id='TARGET' /> <span id='ParentOfCollection'> <span id='currentCollection'> <span id='somecontrol1' /> <span id='someOtherControl' /> </span> </span> <span id='anotherCollection'> <span id='CURRENT' /> <span id='Somecontrol' title='before'> <span id='somecontrol1' /> <span id='TARGET' /> <span id='somecontrol3' /> </span> </span> </html> "; HtmlElement root = HtmlElement.Create(html); var currentCollection = root.ChildElements.Find("ParentOfCollection").ChildElements; var currentElement = root.ChildElements.Find("CURRENT"); //Act,Assert ExceptionAssert.Throws <ArgumentException>( () => currentCollection.FindAfter(currentElement, new HtmlElementFindParams("TARGET"))); } [TestMethod] public void WhenCallingFindAfter_IfPrecedingElementIsBeforeTheCollection_ShouldThrowError() { //Arrange string html = @" <html id='control1'> <span id='TARGET' /> <span id='CURRENT' /> <span id='ParentOfCollection'> <span id='currentCollection'> <span id='somecontrol1' /> <span id='someOtherControl' /> </span> </span> <span id='anotherCollection'> <span id='Somecontrol' title='before'> <span id='somecontrol1' /> <span id='TARGET' /> <span id='somecontrol3' /> </span> </span> </html> "; HtmlElement root = HtmlElement.Create(html); var currentCollection = root.ChildElements.Find("ParentOfCollection").ChildElements; var currentElement = root.ChildElements.Find("CURRENT"); //Act,Assert ExceptionAssert.Throws<ArgumentException>( () => currentCollection.FindAfter(currentElement, new HtmlElementFindParams("TARGET"))); } [TestMethod] public void WhenFindingByAttributes_IfMatchingAttributesAsLiteral_ShouldReturnElement() { string html = @" <html> <body> <input id='foo' class='style1' /> </body> </html> "; HtmlElement root = HtmlElement.Create(html); HtmlElementFindParams args = new HtmlElementFindParams(); args.Attributes.Add("class", "style1"); Assert.AreEqual("foo", root.ChildElements.Find(args, 0).Id); } [TestMethod] public void WhenCallingExistsByAttributes_IfAttributesDoNotMatchAsLiterals_ShouldReturnFalse() { string html = @" <html> <body> <input id='foo' class='style1' /> </body> </html> "; HtmlElement root = HtmlElement.Create(html); HtmlElementFindParams args = new HtmlElementFindParams(); args.Attributes.Add("class", "style2"); Assert.IsFalse(root.ChildElements.Exists(args, 0)); } [TestMethod] public void WhenCallingExistsByAttributes_IfAttributesMatchWithContains_ShouldReturnTrue() { string html = @" <html> <body> <input id='foo' class='style1 style2 style3' /> </body> </html> "; HtmlElement root = HtmlElement.Create(html); HtmlElementFindParams args = new HtmlElementFindParams(); args.Attributes.Add("class", "style2", MatchMethod.Contains); Assert.IsTrue(root.ChildElements.Exists(args, 0)); } [TestMethod] public void WhenCallingExistsByAttributes_IfAttributesNotMatchWithContains_ShouldReturnFalse() { string html = @" <html> <body> <input id='foo' class='style1 style2 style3' /> </body> </html> "; HtmlElement root = HtmlElement.Create(html); HtmlElementFindParams args = new HtmlElementFindParams(); args.Attributes.Add("class", "style4", MatchMethod.Contains); Assert.IsFalse(root.ChildElements.Exists(args, 0)); } [TestMethod] public void WhenCallingExistsByAttributes_IfAttributesMatchWithEndsWith_ShouldReturnTrue() { string html = @" <html> <body> <input id='foo' class='style1 style2 style3' /> </body> </html> "; HtmlElement root = HtmlElement.Create(html); HtmlElementFindParams args = new HtmlElementFindParams(); args.Attributes.Add("class", "style3", MatchMethod.EndsWith); Assert.IsTrue(root.ChildElements.Exists(args, 0)); } [TestMethod] public void WhenCallingExistsByAttributes_IfAttributeNotMatchWithEndsWith_ShouldReturnFalse() { string html = @" <html> <body> <input id='foo' class='style1 style2 style3' /> </body> </html> "; HtmlElement root = HtmlElement.Create(html); HtmlElementFindParams args = new HtmlElementFindParams(); args.Attributes.Add("class", "style1", MatchMethod.EndsWith); Assert.IsFalse(root.ChildElements.Exists(args, 0)); } [TestMethod] public void WhenCallingExistsByAttributes_IfAllAttributesMatch_ShouldReturnTrue() { string html = @" <html> <body> <input id='foo' class='style1 style2 style3' style='height:30px;width:20px' /> </body> </html> "; HtmlElement root = HtmlElement.Create(html); HtmlElementFindParams args = new HtmlElementFindParams(); args.Attributes.Add("class", "style2", MatchMethod.Contains); args.Attributes.Add("style", "width:20px", MatchMethod.Regex); Assert.IsTrue(root.ChildElements.Exists(args, 0)); } [TestMethod] public void WhenCallingExistsByAttributes_IfAllAttributesNotMatch_ShouldReturnFalse() { string html = @" <html> <body> <input id='foo' class='style1 style2 style3' style='height:30px;width:20px' /> </body> </html> "; HtmlElement root = HtmlElement.Create(html); HtmlElementFindParams args = new HtmlElementFindParams(); args.Attributes.Add("class", "style2", MatchMethod.Contains); args.Attributes.Add("style", "width:10px", MatchMethod.Regex); Assert.IsFalse(root.ChildElements.Exists(args, 0)); } [TestMethod] public void WhenFindingByAttributes_IfTimeoutToFindIsZero_ShouldNotRefreshTheCollection() { //Arrange string html = @" <html> <body> <input id='input1' type='textbox' /> <input id='input2' type='submit' /> </body> </html> "; var browserCommandExecutor = new Mock<IBrowserCommandExecutor>(); _commandExecutorFactory.Setup(m => m.CreateBrowserCommandExecutor(It.IsAny<string>(), It.IsAny<HtmlPage>())).Returns(browserCommandExecutor.Object); HtmlPage page = new HtmlPage(new Uri("http://foo")); HtmlElement root = HtmlElement.Create(html, page, true); root.ChildElements.Find(new { @type = "submit" }); } } }
using Midi.Chunks; using Midi.Events; using Midi.Events.ChannelEvents; using Midi.Events.MetaEvents; using Midi.Util; using Midi.Util.Option; /* Copyright (c) 2013 Christoph Fabritz 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.IO; using System.Linq; using System.Text; namespace Midi { public class FileParser { private static readonly UTF7Encoding StringEncoder = new UTF7Encoding(); public static MidiData Parse(FileStream inputFileStream) { var inputBinaryReader = new BinaryReader(inputFileStream); // Order of ReadBytes() ist critical! var headerChunkId = StringEncoder.GetString(inputBinaryReader.ReadBytes(4)); var headerChunkSize = BitConverter.ToInt32(inputBinaryReader.ReadBytes(4).Reverse().ToArray(), 0); var headerChunkData = inputBinaryReader.ReadBytes(headerChunkSize); var formatType = BitConverter.ToUInt16(headerChunkData.Take(2).Reverse().ToArray(), 0); var numberOfTracks = BitConverter.ToUInt16(headerChunkData.Skip(2).Take(2).Reverse().ToArray(), 0); var timeDivision = BitConverter.ToUInt16(headerChunkData.Skip(4).Take(2).Reverse().ToArray(), 0); var headerChunk = new HeaderChunk(formatType, timeDivision) { ChunkId = headerChunkId }; var tracks = Enumerable.Range(0, numberOfTracks).Select(trackNumber => { // ReSharper disable once UnusedVariable var trackChunkId = StringEncoder.GetString(inputBinaryReader.ReadBytes(4)); var trackChunkSize = BitConverter.ToInt32(inputBinaryReader.ReadBytes(4).Reverse().ToArray(), 0); var trackChunkData = inputBinaryReader.ReadBytes(trackChunkSize); return Tuple.Create(trackChunkSize, trackChunkData); }).ToList() .Select(rawTrack => new TrackChunk(ParseEvents(rawTrack.Item2.ToList(), rawTrack.Item1))).ToList(); return new MidiData(headerChunk, tracks); } private static List<MidiEvent> ParseEvents(List<byte> trackData, int chunkSize) { var i = 0; var lastMidiChannel = (byte)0x00; var results = new List<MidiEvent>(); while (i < chunkSize) { var tuple = NextEvent(trackData, i, lastMidiChannel); i += tuple.Item2; lastMidiChannel = tuple.Item3; if (tuple.Item1 is Some<MidiEvent>) results.Add((tuple.Item1 as Some<MidiEvent>).value); } return results; } private static Tuple<Option<MidiEvent>, int, byte> NextEvent(List<byte> trackData, int startIndex, byte lastMidiChannel) { var i = startIndex - 1; MidiEvent midiEvent = null; { int deltaTime; { var lengthTemp = new List<byte>(); do { i += 1; lengthTemp.Add(trackData.ElementAt(i)); } while (trackData.ElementAt(i) > 0x7F); deltaTime = VariableLengthUtil.decode_to_int(lengthTemp); } i += 1; var eventTypeValue = trackData.ElementAt(i); // MIDI Channel Events if ((eventTypeValue & 0xF0) < 0xF0) { var midiChannelEventType = (byte)(eventTypeValue & 0xF0); var midiChannel = (byte)(eventTypeValue & 0x0F); i += 1; var parameter1 = trackData.ElementAt(i); byte parameter2; // One or two parameter type switch (midiChannelEventType) { // One parameter types case 0xC0: midiEvent = new ProgramChangeEvent(deltaTime, midiChannel, parameter1); lastMidiChannel = midiChannel; break; case 0xD0: midiEvent = new ChannelAftertouchEvent(deltaTime, midiChannel, parameter1); lastMidiChannel = midiChannel; break; // Two parameter types case 0x80: i += 1; parameter2 = trackData.ElementAt(i); midiEvent = new NoteOffEvent(deltaTime, midiChannel, parameter1, parameter2); lastMidiChannel = midiChannel; break; case 0x90: i += 1; parameter2 = trackData.ElementAt(i); midiEvent = new NoteOnEvent(deltaTime, midiChannel, parameter1, parameter2); lastMidiChannel = midiChannel; break; case 0xA0: i += 1; parameter2 = trackData.ElementAt(i); midiEvent = new NoteAftertouchEvent(deltaTime, midiChannel, parameter1, parameter2); lastMidiChannel = midiChannel; break; case 0xB0: i += 1; parameter2 = trackData.ElementAt(i); midiEvent = new ControllerEvent(deltaTime, midiChannel, parameter1, parameter2); lastMidiChannel = midiChannel; break; case 0xE0: i += 1; parameter2 = trackData.ElementAt(i); midiEvent = new PitchBendEvent(deltaTime, midiChannel, parameter1, parameter2); lastMidiChannel = midiChannel; break; // Might be a Control Change Messages LSB default: midiEvent = new ControllerEvent(deltaTime, lastMidiChannel, eventTypeValue, parameter1); break; } i += 1; } // Meta Events else if (eventTypeValue == 0xFF) { i += 1; var metaEventType = trackData.ElementAt(i); i += 1; var metaEventLength = trackData.ElementAt(i); i += 1; var metaEventData = Enumerable.Range(i, metaEventLength).Select(trackData.ElementAt).ToArray(); switch (metaEventType) { case 0x00: midiEvent = new SequenceNumberEvent(BitConverter.ToUInt16(metaEventData.Reverse().ToArray(), 0)); break; case 0x01: midiEvent = new TextEvent(deltaTime, StringEncoder.GetString(metaEventData)); break; case 0x02: midiEvent = new CopyrightNoticeEvent(StringEncoder.GetString(metaEventData)); break; case 0x03: midiEvent = new SequenceOrTrackNameEvent(StringEncoder.GetString(metaEventData)); break; case 0x04: midiEvent = new InstrumentNameEvent(deltaTime, StringEncoder.GetString(metaEventData)); break; case 0x05: midiEvent = new LyricsEvent(deltaTime, StringEncoder.GetString(metaEventData)); break; case 0x06: midiEvent = new MarkerEvent(deltaTime, StringEncoder.GetString(metaEventData)); break; case 0x07: midiEvent = new CuePointEvent(deltaTime, StringEncoder.GetString(metaEventData)); break; case 0x20: midiEvent = new MIDIChannelPrefixEvent(deltaTime, metaEventData[0]); break; case 0x2F: midiEvent = new EndOfTrackEvent(deltaTime); break; case 0x51: var tempo = (metaEventData[2] & 0x0F) + ((metaEventData[2] & 0xF0) * 16) + ((metaEventData[1] & 0x0F) * 256) + ((metaEventData[1] & 0xF0) * 4096) + ((metaEventData[0] & 0x0F) * 65536) + ((metaEventData[0] & 0xF0) * 1048576); midiEvent = new SetTempoEvent(deltaTime, tempo); break; case 0x54: midiEvent = new SMPTEOffsetEvent(deltaTime, metaEventData[0], metaEventData[1], metaEventData[2], metaEventData[3], metaEventData[4]); break; case 0x58: midiEvent = new TimeSignatureEvent(deltaTime, metaEventData[0], metaEventData[1], metaEventData[2], metaEventData[3]); break; case 0x59: midiEvent = new KeySignatureEvent(deltaTime, metaEventData[0], metaEventData[1]); break; case 0x7F: midiEvent = new SequencerSpecificEvent(deltaTime, metaEventData); break; } i += metaEventLength; } // System Exclusive Events else if (eventTypeValue == 0xF0 || eventTypeValue == 0xF7) { var lengthTemp = new List<byte>(); do { i += 1; lengthTemp.Add(trackData.ElementAt(i)); } while (trackData.ElementAt(i) > 0x7F); var eventLength = VariableLengthUtil.decode_to_int(lengthTemp); i += 1; var eventData = Enumerable.Range(i, eventLength).Select(trackData.ElementAt); midiEvent = new SysexEvent(deltaTime, eventTypeValue, eventData); i += eventLength; } } return midiEvent != null ? new Tuple<Option<MidiEvent>, int, byte>(new Some<MidiEvent>(midiEvent), i - startIndex, lastMidiChannel) : new Tuple<Option<MidiEvent>, int, byte>(new None<MidiEvent>(), i - startIndex, lastMidiChannel); } } }
//Apache2, 2012, Hernan J Gonzalez, https://github.com/leonbloy/pngcs namespace Hjg.Pngcs { using System; using System.Collections.Generic; using System.IO; using Chunks; using Hjg.Pngcs.Zlib; /// <summary> /// Writes a PNG image, line by line. /// </summary> public class PngWriter { /// <summary> /// Basic image info, inmutable /// </summary> public readonly ImageInfo ImgInfo; /// <summary> /// filename, or description - merely informative, can be empty /// </summary> protected readonly String filename; private FilterWriteStrategy filterStrat; /** * Deflate algortithm compression strategy */ public EDeflateCompressStrategy CompressionStrategy { get; set; } /// <summary> /// zip compression level (0 - 9) /// </summary> /// <remarks> /// default:6 /// /// 9 is the maximum compression /// </remarks> public int CompLevel { get; set; } /// <summary> /// true: closes stream after ending write /// </summary> public bool ShouldCloseStream { get; set; } /// <summary> /// Maximum size of IDAT chunks /// </summary> /// <remarks> /// 0=use default (PngIDatChunkOutputStream 32768) /// </remarks> public int IdatMaxSize { get; set; } // /// <summary> /// A high level wrapper of a ChunksList : list of written/queued chunks /// </summary> private readonly PngMetadata metadata; /// <summary> /// written/queued chunks /// </summary> private readonly ChunksListForWrite chunksList; /// <summary> /// raw current row, as array of bytes,counting from 1 (index 0 is reserved for filter type) /// </summary> protected byte[] rowb; /// <summary> /// previuos raw row /// </summary> protected byte[] rowbprev; // rowb previous /// <summary> /// raw current row, after filtered /// </summary> protected byte[] rowbfilter; /// <summary> /// number of chunk group (0-6) last writen, or currently writing /// </summary> /// <remarks>see ChunksList.CHUNK_GROUP_NNN</remarks> public int CurrentChunkGroup { get; private set; } private int rowNum = -1; // current line number private readonly Stream outputStream; private PngIDatChunkOutputStream datStream; private AZlibOutputStream datStreamDeflated; private int[] histox = new int[256]; // auxiliar buffer, histogram, only used by reportResultsForFilter // this only influences the 1-2-4 bitdepth format - and if we pass a ImageLine to writeRow, this is ignored private bool unpackedMode; private bool needsPack; // autocomputed /// <summary> /// Constructs a PngWriter from a outputStream, with no filename information /// </summary> /// <param name="outputStream"></param> /// <param name="imgInfo"></param> public PngWriter(Stream outputStream, ImageInfo imgInfo) : this(outputStream, imgInfo, "[NO FILENAME AVAILABLE]") { } /// <summary> /// Constructs a PngWriter from a outputStream, with optional filename or description /// </summary> /// <remarks> /// After construction nothing is writen yet. You still can set some /// parameters (compression, filters) and queue chunks before start writing the pixels. /// /// See also <c>FileHelper.createPngWriter()</c> /// </remarks> /// <param name="outputStream">Opened stream for binary writing</param> /// <param name="imgInfo">Basic image parameters</param> /// <param name="filename">Optional, can be the filename or a description.</param> public PngWriter(Stream outputStream, ImageInfo imgInfo, String filename) { this.filename = (filename == null) ? "" : filename; this.outputStream = outputStream; this.ImgInfo = imgInfo; // defaults settings this.CompLevel = 6; this.ShouldCloseStream = true; this.IdatMaxSize = 0; // use default this.CompressionStrategy = EDeflateCompressStrategy.Filtered; // prealloc //scanline = new int[imgInfo.SamplesPerRowPacked]; rowb = new byte[imgInfo.BytesPerRow + 1]; rowbprev = new byte[rowb.Length]; rowbfilter = new byte[rowb.Length]; chunksList = new ChunksListForWrite(ImgInfo); metadata = new PngMetadata(chunksList); filterStrat = new FilterWriteStrategy(ImgInfo, FilterType.FILTER_DEFAULT); unpackedMode = false; needsPack = unpackedMode && imgInfo.Packed; } /// <summary> /// init: is called automatically before writing the first row /// </summary> private void init() { datStream = new PngIDatChunkOutputStream(this.outputStream, this.IdatMaxSize); datStreamDeflated = ZlibStreamFactory.createZlibOutputStream(datStream, this.CompLevel, this.CompressionStrategy, true); WriteSignatureAndIHDR(); WriteFirstChunks(); } private void reportResultsForFilter(int rown, FilterType type, bool tentative) { for (int i = 0; i < histox.Length; i++) histox[i] = 0; int s = 0, v; for (int i = 1; i <= ImgInfo.BytesPerRow; i++) { v = rowbfilter[i]; if (v < 0) s -= (int)v; else s += (int)v; histox[v & 0xFF]++; } filterStrat.fillResultsForFilter(rown, type, s, histox, tentative); } private void WriteEndChunk() { PngChunkIEND c = new PngChunkIEND(ImgInfo); c.CreateRawChunk().WriteChunk(outputStream); } private void WriteFirstChunks() { int nw = 0; CurrentChunkGroup = ChunksList.CHUNK_GROUP_1_AFTERIDHR; nw = chunksList.writeChunks(outputStream, CurrentChunkGroup); CurrentChunkGroup = ChunksList.CHUNK_GROUP_2_PLTE; nw = chunksList.writeChunks(outputStream, CurrentChunkGroup); if (nw > 0 && ImgInfo.Greyscale) throw new PngjOutputException("cannot write palette for this format"); if (nw == 0 && ImgInfo.Indexed) throw new PngjOutputException("missing palette"); CurrentChunkGroup = ChunksList.CHUNK_GROUP_3_AFTERPLTE; nw = chunksList.writeChunks(outputStream, CurrentChunkGroup); CurrentChunkGroup = ChunksList.CHUNK_GROUP_4_IDAT; } private void WriteLastChunks() { // not including end CurrentChunkGroup = ChunksList.CHUNK_GROUP_5_AFTERIDAT; chunksList.writeChunks(outputStream, CurrentChunkGroup); // should not be unwriten chunks List<PngChunk> pending = chunksList.GetQueuedChunks(); if (pending.Count > 0) throw new PngjOutputException(pending.Count + " chunks were not written! Eg: " + pending[0].ToString()); CurrentChunkGroup = ChunksList.CHUNK_GROUP_6_END; } /// <summary> /// Write id signature and also "IHDR" chunk /// </summary> /// private void WriteSignatureAndIHDR() { CurrentChunkGroup = ChunksList.CHUNK_GROUP_0_IDHR; PngHelperInternal.WriteBytes(outputStream, Hjg.Pngcs.PngHelperInternal.PNG_ID_SIGNATURE); // signature PngChunkIHDR ihdr = new PngChunkIHDR(ImgInfo); // http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html ihdr.Cols = ImgInfo.Cols; ihdr.Rows = ImgInfo.Rows; ihdr.Bitspc = ImgInfo.BitDepth; int colormodel = 0; if (ImgInfo.Alpha) colormodel += 0x04; if (ImgInfo.Indexed) colormodel += 0x01; if (!ImgInfo.Greyscale) colormodel += 0x02; ihdr.Colormodel = colormodel; ihdr.Compmeth = 0; // compression method 0=deflate ihdr.Filmeth = 0; // filter method (0) ihdr.Interlaced = 0; // never interlace ihdr.CreateRawChunk().WriteChunk(outputStream); } protected void encodeRowFromByte(byte[] row) { if (row.Length == ImgInfo.SamplesPerRowPacked && !needsPack) { // some duplication of code - because this case is typical and it works faster this way int j = 1; if (ImgInfo.BitDepth <= 8) { foreach (byte x in row) { // optimized rowb[j++] = x; } } else { // 16 bitspc foreach (byte x in row) { // optimized rowb[j] = x; j += 2; } } } else { // perhaps we need to pack? if (row.Length >= ImgInfo.SamplesPerRow && needsPack) ImageLine.packInplaceByte(ImgInfo, row, row, false); // row is packed in place! if (ImgInfo.BitDepth <= 8) { for (int i = 0, j = 1; i < ImgInfo.SamplesPerRowPacked; i++) { rowb[j++] = row[i]; } } else { // 16 bitspc for (int i = 0, j = 1; i < ImgInfo.SamplesPerRowPacked; i++) { rowb[j++] = row[i]; rowb[j++] = 0; } } } } protected void encodeRowFromInt(int[] row) { if (row.Length == ImgInfo.SamplesPerRowPacked && !needsPack) { // some duplication of code - because this case is typical and it works faster this way int j = 1; if (ImgInfo.BitDepth <= 8) { foreach (int x in row) { // optimized rowb[j++] = (byte)x; } } else { // 16 bitspc foreach (int x in row) { // optimized rowb[j++] = (byte)(x >> 8); rowb[j++] = (byte)(x); } } } else { // perhaps we need to pack? if (row.Length >= ImgInfo.SamplesPerRow && needsPack) ImageLine.packInplaceInt(ImgInfo, row, row, false); // row is packed in place! if (ImgInfo.BitDepth <= 8) { for (int i = 0, j = 1; i < ImgInfo.SamplesPerRowPacked; i++) { rowb[j++] = (byte)(row[i]); } } else { // 16 bitspc for (int i = 0, j = 1; i < ImgInfo.SamplesPerRowPacked; i++) { rowb[j++] = (byte)(row[i] >> 8); rowb[j++] = (byte)(row[i]); } } } } private void FilterRow(int rown) { // warning: filters operation rely on: "previos row" (rowbprev) is // initialized to 0 the first time if (filterStrat.shouldTestAll(rown)) { FilterRowNone(); reportResultsForFilter(rown, FilterType.FILTER_NONE, true); FilterRowSub(); reportResultsForFilter(rown, FilterType.FILTER_SUB, true); FilterRowUp(); reportResultsForFilter(rown, FilterType.FILTER_UP, true); FilterRowAverage(); reportResultsForFilter(rown, FilterType.FILTER_AVERAGE, true); FilterRowPaeth(); reportResultsForFilter(rown, FilterType.FILTER_PAETH, true); } FilterType filterType = filterStrat.gimmeFilterType(rown, true); rowbfilter[0] = (byte)(int)filterType; switch (filterType) { case Hjg.Pngcs.FilterType.FILTER_NONE: FilterRowNone(); break; case Hjg.Pngcs.FilterType.FILTER_SUB: FilterRowSub(); break; case Hjg.Pngcs.FilterType.FILTER_UP: FilterRowUp(); break; case Hjg.Pngcs.FilterType.FILTER_AVERAGE: FilterRowAverage(); break; case Hjg.Pngcs.FilterType.FILTER_PAETH: FilterRowPaeth(); break; default: throw new PngjOutputException("Filter type " + filterType + " not implemented"); } reportResultsForFilter(rown, filterType, false); } private void prepareEncodeRow(int rown) { if (datStream == null) init(); rowNum++; if (rown >= 0 && rowNum != rown) throw new PngjOutputException("rows must be written in order: expected:" + rowNum + " passed:" + rown); // swap byte[] tmp = rowb; rowb = rowbprev; rowbprev = tmp; } private void filterAndSend(int rown) { FilterRow(rown); datStreamDeflated.Write(rowbfilter, 0, ImgInfo.BytesPerRow + 1); } private void FilterRowAverage() { int i, j, imax; imax = ImgInfo.BytesPerRow; for (j = 1 - ImgInfo.BytesPixel, i = 1; i <= imax; i++, j++) { rowbfilter[i] = (byte)(rowb[i] - ((rowbprev[i]) + (j > 0 ? rowb[j] : (byte)0)) / 2); } } private void FilterRowNone() { for (int i = 1; i <= ImgInfo.BytesPerRow; i++) { rowbfilter[i] = (byte)rowb[i]; } } private void FilterRowPaeth() { int i, j, imax; imax = ImgInfo.BytesPerRow; for (j = 1 - ImgInfo.BytesPixel, i = 1; i <= imax; i++, j++) { rowbfilter[i] = (byte)(rowb[i] - PngHelperInternal.FilterPaethPredictor(j > 0 ? rowb[j] : (byte)0, rowbprev[i], j > 0 ? rowbprev[j] : (byte)0)); } } private void FilterRowSub() { int i, j; for (i = 1; i <= ImgInfo.BytesPixel; i++) { rowbfilter[i] = (byte)rowb[i]; } for (j = 1, i = ImgInfo.BytesPixel + 1; i <= ImgInfo.BytesPerRow; i++, j++) { rowbfilter[i] = (byte)(rowb[i] - rowb[j]); } } private void FilterRowUp() { for (int i = 1; i <= ImgInfo.BytesPerRow; i++) { rowbfilter[i] = (byte)(rowb[i] - rowbprev[i]); } } private long SumRowbfilter() { // sums absolute value long s = 0; for (int i = 1; i <= ImgInfo.BytesPerRow; i++) if (rowbfilter[i] < 0) s -= (long)rowbfilter[i]; else s += (long)rowbfilter[i]; return s; } /// <summary> /// copy chunks from reader - copy_mask : see ChunksToWrite.COPY_XXX /// If we are after idat, only considers those chunks after IDAT in PngReader /// TODO: this should be more customizable /// </summary> /// private void CopyChunks(PngReader reader, int copy_mask, bool onlyAfterIdat) { bool idatDone = CurrentChunkGroup >= ChunksList.CHUNK_GROUP_4_IDAT; if (onlyAfterIdat && reader.CurrentChunkGroup < ChunksList.CHUNK_GROUP_6_END) throw new PngjException("tried to copy last chunks but reader has not ended"); foreach (PngChunk chunk in reader.GetChunksList().GetChunks()) { int group = chunk.ChunkGroup; if (group < ChunksList.CHUNK_GROUP_4_IDAT && idatDone) continue; bool copy = false; if (chunk.Crit) { if (chunk.Id.Equals(ChunkHelper.PLTE)) { if (ImgInfo.Indexed && ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_PALETTE)) copy = true; if (!ImgInfo.Greyscale && ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_ALL)) copy = true; } } else { // ancillary bool text = (chunk is PngChunkTextVar); bool safe = chunk.Safe; // notice that these if are not exclusive if (ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_ALL)) copy = true; if (safe && ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_ALL_SAFE)) copy = true; if (chunk.Id.Equals(ChunkHelper.tRNS) && ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_TRANSPARENCY)) copy = true; if (chunk.Id.Equals(ChunkHelper.pHYs) && ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_PHYS)) copy = true; if (text && ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_TEXTUAL)) copy = true; if (ChunkHelper.maskMatch(copy_mask, ChunkCopyBehaviour.COPY_ALMOSTALL) && !(ChunkHelper.IsUnknown(chunk) || text || chunk.Id.Equals(ChunkHelper.hIST) || chunk.Id .Equals(ChunkHelper.tIME))) copy = true; if (chunk is PngChunkSkipped) copy = false; } if (copy) { chunksList.Queue(PngChunk.CloneChunk(chunk, ImgInfo)); } } } public void CopyChunksFirst(PngReader reader, int copy_mask) { CopyChunks(reader, copy_mask, false); } public void CopyChunksLast(PngReader reader, int copy_mask) { CopyChunks(reader, copy_mask, true); } /// <summary> /// Computes compressed size/raw size, approximate /// </summary> /// <remarks>Actually: compressed size = total size of IDAT data , raw size = uncompressed pixel bytes = rows * (bytesPerRow + 1) /// </remarks> /// <returns></returns> public double ComputeCompressionRatio() { if (CurrentChunkGroup < ChunksList.CHUNK_GROUP_6_END) throw new PngjException("must be called after End()"); double compressed = (double)datStream.GetCountFlushed(); double raw = (ImgInfo.BytesPerRow + 1) * ImgInfo.Rows; return compressed / raw; } /// <summary> /// Finalizes the image creation and closes the file stream. </summary> /// <remarks> /// This MUST be called after writing the lines. /// </remarks> /// public void End() { if (rowNum != ImgInfo.Rows - 1) throw new PngjOutputException("all rows have not been written"); try { datStreamDeflated.Close(); datStream.Close(); WriteLastChunks(); WriteEndChunk(); if (this.ShouldCloseStream) outputStream.Close(); } catch (IOException e) { throw new PngjOutputException(e); } } /// <summary> /// Filename or description, from the optional constructor argument. /// </summary> /// <returns></returns> public String GetFilename() { return filename; } /// <summary> /// this uses the row number from the imageline! /// </summary> /// public void WriteRow(ImageLine imgline, int rownumber) { SetUseUnPackedMode(imgline.SamplesUnpacked); if (imgline.SampleType == ImageLine.ESampleType.INT) WriteRowInt(imgline.Scanline, rownumber); else WriteRowByte(imgline.ScanlineB, rownumber); } public void WriteRow(int[] newrow) { WriteRow(newrow, -1); } public void WriteRow(int[] newrow, int rown) { WriteRowInt(newrow, rown); } /// <summary> /// Writes a full image row. /// </summary> /// <remarks> /// This must be called sequentially from n=0 to /// n=rows-1 One integer per sample , in the natural order: R G B R G B ... (or /// R G B A R G B A... if has alpha) The values should be between 0 and 255 for /// 8 bitspc images, and between 0- 65535 form 16 bitspc images (this applies /// also to the alpha channel if present) The array can be reused. /// </remarks> /// <param name="newrow">Array of pixel values</param> /// <param name="rown">Number of row, from 0 (top) to rows-1 (bottom)</param> public void WriteRowInt(int[] newrow, int rown) { prepareEncodeRow(rown); encodeRowFromInt(newrow); filterAndSend(rown); } public void WriteRowByte(byte[] newrow, int rown) { prepareEncodeRow(rown); encodeRowFromByte(newrow); filterAndSend(rown); } /** * Writes all the pixels, calling writeRowInt() for each image row */ public void WriteRowsInt(int[][] image) { for (int i = 0; i < ImgInfo.Rows; i++) WriteRowInt(image[i], i); } /** * Writes all the pixels, calling writeRowByte() for each image row */ public void WriteRowsByte(byte[][] image) { for (int i = 0; i < ImgInfo.Rows; i++) WriteRowByte(image[i], i); } public PngMetadata GetMetadata() { return metadata; } public ChunksListForWrite GetChunksList() { return chunksList; } /// <summary> /// Sets internal prediction filter type, or strategy to choose it. /// </summary> /// <remarks> /// This must be called just after constructor, before starting writing. /// /// Recommended values: DEFAULT (default) or AGGRESIVE /// </remarks> /// <param name="filterType">One of the five prediction types or strategy to choose it</param> public void SetFilterType(FilterType filterType) { filterStrat = new FilterWriteStrategy(ImgInfo, filterType); } public bool IsUnpackedMode() { return unpackedMode; } public void SetUseUnPackedMode(bool useUnpackedMode) { this.unpackedMode = useUnpackedMode; needsPack = unpackedMode && ImgInfo.Packed; } } }
using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Threading; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Store { /* * 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 DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using IndexWriter = Lucene.Net.Index.IndexWriter; using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using OpenMode = Lucene.Net.Index.OpenMode; using Query = Lucene.Net.Search.Query; using Term = Lucene.Net.Index.Term; using TermQuery = Lucene.Net.Search.TermQuery; [TestFixture] public class TestLockFactory : LuceneTestCase { // Verify: we can provide our own LockFactory implementation, the right // methods are called at the right time, locks are created, etc. [Test] public virtual void TestCustomLockFactory() { Directory dir = new MockDirectoryWrapper(Random, new RAMDirectory()); MockLockFactory lf = new MockLockFactory(this); dir.SetLockFactory(lf); // Lock prefix should have been set: Assert.IsTrue(lf.LockPrefixSet, "lock prefix was not set by the RAMDirectory"); IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); // add 100 documents (so that commit lock is used) for (int i = 0; i < 100; i++) { AddDoc(writer); } // Both write lock and commit lock should have been created: Assert.AreEqual(1, lf.LocksCreated.Count, "# of unique locks created (after instantiating IndexWriter)"); Assert.IsTrue(lf.MakeLockCount >= 1, "# calls to makeLock is 0 (after instantiating IndexWriter)"); foreach (String lockName in lf.LocksCreated.Keys) { MockLockFactory.MockLock @lock = (MockLockFactory.MockLock)lf.LocksCreated[lockName]; Assert.IsTrue(@lock.LockAttempts > 0, "# calls to Lock.obtain is 0 (after instantiating IndexWriter)"); } writer.Dispose(); } // Verify: we can use the NoLockFactory with RAMDirectory w/ no // exceptions raised: // Verify: NoLockFactory allows two IndexWriters [Test] public virtual void TestRAMDirectoryNoLocking() { MockDirectoryWrapper dir = new MockDirectoryWrapper(Random, new RAMDirectory()); dir.SetLockFactory(NoLockFactory.GetNoLockFactory()); dir.WrapLockFactory = false; // we are gonna explicitly test we get this back Assert.IsTrue(typeof(NoLockFactory).IsInstanceOfType(dir.LockFactory), "RAMDirectory.setLockFactory did not take"); IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); writer.Commit(); // required so the second open succeed // Create a 2nd IndexWriter. this is normally not allowed but it should run through since we're not // using any locks: IndexWriter writer2 = null; try { writer2 = new IndexWriter(dir, (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetOpenMode(OpenMode.APPEND)); } catch (Exception e) { Console.Out.Write(e.StackTrace); Assert.Fail("Should not have hit an IOException with no locking"); } writer.Dispose(); if (writer2 != null) { writer2.Dispose(); } } // Verify: SingleInstanceLockFactory is the default lock for RAMDirectory // Verify: RAMDirectory does basic locking correctly (can't create two IndexWriters) [Test] public virtual void TestDefaultRAMDirectory() { Directory dir = new RAMDirectory(); Assert.IsTrue(typeof(SingleInstanceLockFactory).IsInstanceOfType(dir.LockFactory), "RAMDirectory did not use correct LockFactory: got " + dir.LockFactory); IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); // Create a 2nd IndexWriter. this should fail: IndexWriter writer2 = null; try { writer2 = new IndexWriter(dir, (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetOpenMode(OpenMode.APPEND)); Assert.Fail("Should have hit an IOException with two IndexWriters on default SingleInstanceLockFactory"); } #pragma warning disable 168 catch (IOException e) #pragma warning restore 168 { } writer.Dispose(); if (writer2 != null) { writer2.Dispose(); } } [Test] public virtual void TestSimpleFSLockFactory() { // test string file instantiation new SimpleFSLockFactory("test"); } // Verify: do stress test, by opening IndexReaders and // IndexWriters over & over in 2 threads and making sure // no unexpected exceptions are raised: [Test] [Nightly] public virtual void TestStressLocks() { _testStressLocks(null, CreateTempDir("index.TestLockFactory6")); } // Verify: do stress test, by opening IndexReaders and // IndexWriters over & over in 2 threads and making sure // no unexpected exceptions are raised, but use // NativeFSLockFactory: [Test] [Nightly] public virtual void TestStressLocksNativeFSLockFactory() { DirectoryInfo dir = CreateTempDir("index.TestLockFactory7"); _testStressLocks(new NativeFSLockFactory(dir), dir); } public virtual void _testStressLocks(LockFactory lockFactory, DirectoryInfo indexDir) { Directory dir = NewFSDirectory(indexDir, lockFactory); // First create a 1 doc index: IndexWriter w = new IndexWriter(dir, (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetOpenMode(OpenMode.CREATE)); AddDoc(w); w.Dispose(); WriterThread writer = new WriterThread(this, 100, dir); SearcherThread searcher = new SearcherThread(this, 100, dir); writer.Start(); searcher.Start(); while (writer.IsAlive || searcher.IsAlive) { Thread.Sleep(1000); } Assert.IsTrue(!writer.HitException, "IndexWriter hit unexpected exceptions"); Assert.IsTrue(!searcher.HitException, "IndexSearcher hit unexpected exceptions"); dir.Dispose(); // Cleanup System.IO.Directory.Delete(indexDir.FullName, true); } // Verify: NativeFSLockFactory works correctly [Test] public virtual void TestNativeFSLockFactory() { var f = new NativeFSLockFactory(CreateTempDir("testNativeFsLockFactory")); f.LockPrefix = "test"; var l = f.MakeLock("commit"); var l2 = f.MakeLock("commit"); Assert.IsTrue(l.Obtain(), "failed to obtain lock, got exception: {0}", l.FailureReason); Assert.IsTrue(!l2.Obtain(), "succeeded in obtaining lock twice"); l.Dispose(); Assert.IsTrue(l2.Obtain(), "failed to obtain 2nd lock after first one was freed, got exception: {0}", l2.FailureReason); l2.Dispose(); // Make sure we can obtain first one again, test isLocked(): Assert.IsTrue(l.Obtain(), "failed to obtain lock, got exception: {0}", l.FailureReason); Assert.IsTrue(l.IsLocked()); Assert.IsTrue(l2.IsLocked()); l.Dispose(); Assert.IsFalse(l.IsLocked()); Assert.IsFalse(l2.IsLocked()); } // Verify: NativeFSLockFactory works correctly if the lock file exists [Test] public virtual void TestNativeFSLockFactoryLockExists() { DirectoryInfo tempDir = CreateTempDir("testNativeFsLockFactory"); // Touch the lock file var lockFile = new FileInfo(Path.Combine(tempDir.FullName, "test.lock")); using (lockFile.Create()){}; var l = (new NativeFSLockFactory(tempDir)).MakeLock("test.lock"); Assert.IsTrue(l.Obtain(), "failed to obtain lock, got exception: {0}", l.FailureReason); l.Dispose(); Assert.IsFalse(l.IsLocked(), "failed to release lock, got exception: {0}", l.FailureReason); if (lockFile.Exists) { lockFile.Delete(); } } // Verify: NativeFSLockFactory assigns null as lockPrefix if the lockDir is inside directory [Test] public virtual void TestNativeFSLockFactoryPrefix() { DirectoryInfo fdir1 = CreateTempDir("TestLockFactory.8"); DirectoryInfo fdir2 = CreateTempDir("TestLockFactory.8.Lockdir"); Directory dir1 = NewFSDirectory(fdir1, new NativeFSLockFactory(fdir1)); // same directory, but locks are stored somewhere else. The prefix of the lock factory should != null Directory dir2 = NewFSDirectory(fdir1, new NativeFSLockFactory(fdir2)); string prefix1 = dir1.LockFactory.LockPrefix; Assert.IsNull(prefix1, "Lock prefix for lockDir same as directory should be null"); string prefix2 = dir2.LockFactory.LockPrefix; Assert.IsNotNull(prefix2, "Lock prefix for lockDir outside of directory should be not null"); dir1.Dispose(); dir2.Dispose(); System.IO.Directory.Delete(fdir1.FullName, true); System.IO.Directory.Delete(fdir2.FullName, true); } // Verify: default LockFactory has no prefix (ie // write.lock is stored in index): [Test] public virtual void TestDefaultFSLockFactoryPrefix() { // Make sure we get null prefix, which wont happen if setLockFactory is ever called. DirectoryInfo dirName = CreateTempDir("TestLockFactory.10"); Directory dir = new SimpleFSDirectory(dirName); Assert.IsNull(dir.LockFactory.LockPrefix, "Default lock prefix should be null"); dir.Dispose(); dir = new MMapDirectory(dirName); Assert.IsNull(dir.LockFactory.LockPrefix, "Default lock prefix should be null"); dir.Dispose(); dir = new NIOFSDirectory(dirName); Assert.IsNull(dir.LockFactory.LockPrefix, "Default lock prefix should be null"); dir.Dispose(); System.IO.Directory.Delete(dirName.FullName, true); } private class WriterThread : ThreadJob { private readonly TestLockFactory outerInstance; private readonly Directory dir; private readonly int numIteration; public bool HitException { get; private set; } = false; public WriterThread(TestLockFactory outerInstance, int numIteration, Directory dir) { this.outerInstance = outerInstance; this.numIteration = numIteration; this.dir = dir; } public override void Run() { IndexWriter writer = null; for (int i = 0; i < this.numIteration; i++) { try { writer = new IndexWriter(dir, (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))).SetOpenMode(OpenMode.APPEND)); } catch (IOException e) { if (e.ToString().IndexOf(" timed out:", StringComparison.Ordinal) == -1) { HitException = true; Console.WriteLine("Stress Test Index Writer: creation hit unexpected IOException: " + e.ToString()); Console.Out.Write(e.StackTrace); } else { // lock obtain timed out // NOTE: we should at some point // consider this a failure? The lock // obtains, across IndexReader & // IndexWriters should be "fair" (ie // FIFO). } } catch (Exception e) { HitException = true; Console.WriteLine("Stress Test Index Writer: creation hit unexpected exception: " + e.ToString()); Console.Out.Write(e.StackTrace); break; } if (writer != null) { try { outerInstance.AddDoc(writer); } catch (IOException e) { HitException = true; Console.WriteLine("Stress Test Index Writer: addDoc hit unexpected exception: " + e.ToString()); Console.Out.Write(e.StackTrace); break; } try { writer.Dispose(); } catch (IOException e) { HitException = true; Console.WriteLine("Stress Test Index Writer: close hit unexpected exception: " + e.ToString()); Console.Out.Write(e.StackTrace); break; } writer = null; } } } } private class SearcherThread : ThreadJob { private readonly TestLockFactory outerInstance; private readonly Directory dir; private readonly int numIteration; public bool HitException { get; private set; } = false; public SearcherThread(TestLockFactory outerInstance, int numIteration, Directory dir) { this.outerInstance = outerInstance; this.numIteration = numIteration; this.dir = dir; } public override void Run() { IndexReader reader = null; IndexSearcher searcher = null; Query query = new TermQuery(new Term("content", "aaa")); for (int i = 0; i < this.numIteration; i++) { try { reader = DirectoryReader.Open(dir); searcher = NewSearcher( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION OuterInstance, #endif reader); } catch (Exception e) { HitException = true; Console.WriteLine("Stress Test Index Searcher: create hit unexpected exception: " + e.ToString()); Console.Out.Write(e.StackTrace); break; } try { searcher.Search(query, null, 1000); } catch (IOException e) { HitException = true; Console.WriteLine("Stress Test Index Searcher: search hit unexpected exception: " + e.ToString()); Console.Out.Write(e.StackTrace); break; } // System.out.println(hits.Length() + " total results"); try { reader.Dispose(); } catch (IOException e) { HitException = true; Console.WriteLine("Stress Test Index Searcher: close hit unexpected exception: " + e.ToString()); Console.Out.Write(e.StackTrace); break; } } } } public class MockLockFactory : LockFactory { private readonly TestLockFactory outerInstance; public MockLockFactory(TestLockFactory outerInstance) { this.outerInstance = outerInstance; } public bool LockPrefixSet; public IDictionary<string, Lock> LocksCreated = /*CollectionsHelper.SynchronizedMap(*/new Dictionary<string, Lock>()/*)*/; public int MakeLockCount = 0; public override string LockPrefix { set { base.LockPrefix = value; LockPrefixSet = true; } } public override Lock MakeLock(string lockName) { lock (this) { Lock @lock = new MockLock(this); LocksCreated[lockName] = @lock; MakeLockCount++; return @lock; } } public override void ClearLock(string specificLockName) { } public class MockLock : Lock { private readonly TestLockFactory.MockLockFactory outerInstance; public MockLock(TestLockFactory.MockLockFactory outerInstance) { this.outerInstance = outerInstance; } public int LockAttempts; public override bool Obtain() { LockAttempts++; return true; } protected override void Dispose(bool disposing) { // do nothing } public override bool IsLocked() { return false; } } } private void AddDoc(IndexWriter writer) { Document doc = new Document(); doc.Add(NewTextField("content", "aaa", Field.Store.NO)); writer.AddDocument(doc); } } }
// Copyright (c) 2007-2012 Michael Chapman // http://ipaddresscontrollib.googlecode.com // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Text; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; namespace IPAddressControlLib { [DesignerAttribute( typeof( IpAddressControlDesigner ) )] public class IPAddressControl : ContainerControl { #region Public Constants public const int FieldCount = 4; #endregion // Public Constants #region Public Events public event EventHandler<FieldChangedEventArgs> FieldChangedEvent; #endregion //Public Events #region Public Properties [Browsable( true )] public bool AllowInternalTab { get { foreach ( FieldControl fc in _fieldControls ) { return fc.TabStop; } return false; } set { foreach ( FieldControl fc in _fieldControls ) { fc.TabStop = value; } } } [Browsable( true )] public bool AnyBlank { get { foreach ( FieldControl fc in _fieldControls ) { if ( fc.Blank ) { return true; } } return false; } } [Browsable( true )] public bool AutoHeight { get { return _autoHeight; } set { _autoHeight= value; if ( _autoHeight ) { AdjustSize(); } } } [Browsable( false )] public int Baseline { get { NativeMethods.Textmetric textMetric = GetTextMetrics( Handle, Font ); int offset = textMetric.tmAscent + 1; switch ( BorderStyle ) { case BorderStyle.Fixed3D: offset += Fixed3DOffset.Height; break; case BorderStyle.FixedSingle: offset += FixedSingleOffset.Height; break; } return offset; } } [Browsable( true )] public bool Blank { get { foreach ( FieldControl fc in _fieldControls ) { if ( !fc.Blank ) { return false; } } return true; } } [Browsable( true )] public BorderStyle BorderStyle { get { return _borderStyle; } set { _borderStyle = value; AdjustSize(); Invalidate(); } } [Browsable( false )] public override bool Focused { get { foreach ( FieldControl fc in _fieldControls ) { if ( fc.Focused ) { return true; } } return false; } } [Browsable( false ), DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public IPAddress IPAddress { get { return new IPAddress( GetAddressBytes() ); } set { Clear(); if ( null == value ) { return; } if ( value.AddressFamily == AddressFamily.InterNetwork ) { SetAddressBytes( value.GetAddressBytes() ); } } } [Browsable( true )] public override Size MinimumSize { get { return CalculateMinimumSize(); } } [Browsable( true )] public bool ReadOnly { get { return _readOnly; } set { _readOnly = value; foreach ( FieldControl fc in _fieldControls ) { fc.ReadOnly = _readOnly; } foreach ( DotControl dc in _dotControls ) { dc.ReadOnly = _readOnly; } Invalidate(); } } [Bindable(true)] [Browsable(true)] [DesignerSerializationVisibility( DesignerSerializationVisibility.Visible )] public override string Text { get { StringBuilder sb = new StringBuilder(); ; for ( int index = 0; index < _fieldControls.Length; ++index ) { sb.Append( _fieldControls[ index ].Text ); if ( index < _dotControls.Length ) { sb.Append( _dotControls[ index ].Text ); } } return sb.ToString(); } set { Clear(); if ( null == value ) { return; } List<string> separators = new List<string>(); foreach ( DotControl dc in _dotControls ) { separators.Add( dc.Text ); } string[] fields = Parse( value, separators.ToArray() ); for ( int i = 0; i < Math.Min( _fieldControls.Length, fields.Length ); ++i ) { _fieldControls[ i ].Text = fields[ i ]; } } } #endregion // Public Properties #region Public Methods public void Clear() { foreach ( FieldControl fc in _fieldControls ) { fc.Clear(); } } public byte[] GetAddressBytes() { byte[] bytes = new byte[FieldCount]; for ( int index = 0; index < FieldCount; ++index ) { bytes[index] = _fieldControls[index].Value; } return bytes; } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", Justification = "Using Bytes seems more informative than SetAddressValues." )] public void SetAddressBytes( byte[] bytes ) { Clear(); if ( bytes == null ) { return; } int length = Math.Min( FieldCount, bytes.Length ); for ( int i = 0; i < length; ++i ) { _fieldControls[i].Text = bytes[i].ToString( CultureInfo.InvariantCulture ); } } public void SetFieldFocus( int fieldIndex ) { if ( ( fieldIndex >= 0 ) && ( fieldIndex < FieldCount ) ) { _fieldControls[fieldIndex].TakeFocus( Direction.Forward, Selection.All ); } } public void SetFieldRange( int fieldIndex, byte rangeLower, byte rangeUpper ) { if ( ( fieldIndex >= 0 ) && ( fieldIndex < FieldCount ) ) { _fieldControls[fieldIndex].RangeLower = rangeLower; _fieldControls[fieldIndex].RangeUpper = rangeUpper; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for ( int index = 0; index < FieldCount; ++index ) { sb.Append( _fieldControls[index].ToString() ); if ( index < _dotControls.Length ) { sb.Append( _dotControls[index].ToString() ); } } return sb.ToString(); } #endregion Public Methods #region Constructors public IPAddressControl() { BackColor = SystemColors.Window; ResetBackColorChanged(); for ( int index = 0; index < _fieldControls.Length; ++index ) { _fieldControls[index] = new FieldControl(); _fieldControls[index].CreateControl(); _fieldControls[index].FieldIndex = index; _fieldControls[index].Name = "FieldControl" + index.ToString( CultureInfo.InvariantCulture ); _fieldControls[index].Parent = this; _fieldControls[index].CedeFocusEvent += new EventHandler<CedeFocusEventArgs>( OnCedeFocus ); _fieldControls[index].Click += new EventHandler( OnSubControlClicked ); _fieldControls[index].DoubleClick += new EventHandler( OnSubControlDoubleClicked ); _fieldControls[index].GotFocus += new EventHandler( OnFieldGotFocus ); _fieldControls[index].KeyDown += new KeyEventHandler( OnFieldKeyDown ); _fieldControls[index].KeyPress += new KeyPressEventHandler( OnFieldKeyPressed ); _fieldControls[index].KeyUp += new KeyEventHandler( OnFieldKeyUp ); _fieldControls[index].LostFocus += new EventHandler( OnFieldLostFocus ); _fieldControls[index].MouseClick += new MouseEventHandler( OnSubControlMouseClicked ); _fieldControls[index].MouseDoubleClick += new MouseEventHandler( OnSubControlMouseDoubleClicked ); _fieldControls[index].MouseEnter += new EventHandler( OnSubControlMouseEntered ); _fieldControls[index].MouseHover += new EventHandler( OnSubControlMouseHovered ); _fieldControls[index].MouseLeave += new EventHandler( OnSubControlMouseLeft ); _fieldControls[index].MouseMove += new MouseEventHandler( OnSubControlMouseMoved ); _fieldControls[index].PasteEvent += new EventHandler<PasteEventArgs>( OnPaste ); _fieldControls[index].PreviewKeyDown += new PreviewKeyDownEventHandler( OnFieldPreviewKeyDown ); _fieldControls[index].TextChangedEvent += new EventHandler<TextChangedEventArgs>( OnFieldTextChanged ); Controls.Add( _fieldControls[index] ); if ( index < ( FieldCount - 1 ) ) { _dotControls[index] = new DotControl(); _dotControls[index].CreateControl(); _dotControls[index].Name = "DotControl" + index.ToString( CultureInfo.InvariantCulture ); _dotControls[index].Parent = this; _dotControls[index].Click += new EventHandler( OnSubControlClicked ); _dotControls[index].DoubleClick += new EventHandler( OnSubControlDoubleClicked ); _dotControls[index].MouseClick += new MouseEventHandler( OnSubControlMouseClicked ); _dotControls[index].MouseDoubleClick += new MouseEventHandler( OnSubControlMouseDoubleClicked ); _dotControls[index].MouseEnter += new EventHandler( OnSubControlMouseEntered ); _dotControls[index].MouseHover += new EventHandler( OnSubControlMouseHovered ); _dotControls[index].MouseLeave += new EventHandler( OnSubControlMouseLeft ); _dotControls[index].MouseMove += new MouseEventHandler( OnSubControlMouseMoved ); Controls.Add( _dotControls[index] ); } } SetStyle( ControlStyles.AllPaintingInWmPaint, true ); SetStyle( ControlStyles.ContainerControl, true ); SetStyle( ControlStyles.OptimizedDoubleBuffer, true ); SetStyle( ControlStyles.ResizeRedraw, true ); SetStyle( ControlStyles.UserPaint, true ); SetStyle( ControlStyles.FixedWidth, true ); SetStyle( ControlStyles.FixedHeight, true ); Cursor = Cursors.IBeam; AutoScaleDimensions = new SizeF( 96F, 96F ); AutoScaleMode = AutoScaleMode.Dpi; Size = MinimumSize; DragEnter += new DragEventHandler( IPAddressControl_DragEnter ); DragDrop += new DragEventHandler( IPAddressControl_DragDrop ); } #endregion // Constructors #region Protected Methods protected override void Dispose( bool disposing ) { if ( disposing ) { Cleanup(); } base.Dispose( disposing ); } protected override void OnBackColorChanged( EventArgs e ) { base.OnBackColorChanged( e ); _backColorChanged = true; } protected override void OnFontChanged( EventArgs e ) { base.OnFontChanged( e ); AdjustSize(); } protected override void OnGotFocus( EventArgs e ) { base.OnGotFocus( e ); _focused = true; _fieldControls[0].TakeFocus( Direction.Forward, Selection.All ); } protected override void OnLostFocus( EventArgs e ) { if ( !Focused ) { _focused = false; base.OnLostFocus( e ); } } protected override void OnMouseEnter( EventArgs e ) { if ( !_hasMouse ) { _hasMouse = true; base.OnMouseEnter( e ); } } protected override void OnMouseLeave( EventArgs e ) { if ( !HasMouse ) { base.OnMouseLeave( e ); _hasMouse = false; } } protected override void OnPaint( PaintEventArgs e ) { if ( null == e ) { throw new ArgumentNullException( "e" ); } base.OnPaint( e ); Color backColor = BackColor; if ( !_backColorChanged ) { if ( !Enabled || ReadOnly ) { backColor = SystemColors.Control; } } using ( SolidBrush backgroundBrush = new SolidBrush( backColor ) ) { e.Graphics.FillRectangle( backgroundBrush, ClientRectangle ); } Rectangle rectBorder = new Rectangle( ClientRectangle.Left, ClientRectangle.Top, ClientRectangle.Width - 1, ClientRectangle.Height - 1 ); switch ( BorderStyle ) { case BorderStyle.Fixed3D: if ( Application.RenderWithVisualStyles ) { using ( Pen pen = new Pen( VisualStyleInformation.TextControlBorder ) ) { e.Graphics.DrawRectangle( pen, rectBorder ); } rectBorder.Inflate( -1, -1 ); e.Graphics.DrawRectangle( SystemPens.Window, rectBorder ); } else { ControlPaint.DrawBorder3D( e.Graphics, ClientRectangle, Border3DStyle.Sunken ); } break; case BorderStyle.FixedSingle: ControlPaint.DrawBorder( e.Graphics, ClientRectangle, SystemColors.WindowFrame, ButtonBorderStyle.Solid ); break; } } protected override void OnSizeChanged( EventArgs e ) { base.OnSizeChanged( e ); AdjustSize(); } #endregion // Protected Methods #region Private Properties private bool HasMouse { get { return DisplayRectangle.Contains( PointToClient( MousePosition ) ); } } #endregion // Private Properties #region Private Methods private void AdjustSize() { Size newSize = MinimumSize; if ( Width > newSize.Width ) { newSize.Width = Width; } if ( Height > newSize.Height ) { newSize.Height = Height; } if ( AutoHeight ) { Size = new Size( newSize.Width, MinimumSize.Height ); } else { Size = newSize; } LayoutControls(); } private Size CalculateMinimumSize() { Size minimumSize = new Size( 0, 0 ); foreach ( FieldControl fc in _fieldControls ) { minimumSize.Width += fc.Width; minimumSize.Height = Math.Max( minimumSize.Height, fc.Height ); } foreach ( DotControl dc in _dotControls ) { minimumSize.Width += dc.Width; minimumSize.Height = Math.Max( minimumSize.Height, dc.Height ); } switch ( BorderStyle ) { case BorderStyle.Fixed3D: minimumSize.Width += 6; minimumSize.Height += ( GetSuggestedHeight() - minimumSize.Height ); break; case BorderStyle.FixedSingle: minimumSize.Width += 4; minimumSize.Height += ( GetSuggestedHeight() - minimumSize.Height ); break; } return minimumSize; } private void Cleanup() { foreach ( DotControl dc in _dotControls ) { Controls.Remove( dc ); dc.Dispose(); } foreach ( FieldControl fc in _fieldControls ) { Controls.Remove( fc ); fc.Dispose(); } _dotControls = null; _fieldControls = null; } private int GetSuggestedHeight() { int height = 0; using ( TextBox reference = new TextBox() ) { reference.AutoSize = true; reference.BorderStyle = BorderStyle; reference.Font = Font; height = reference.Height; } return height; } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1806", Justification = "What should be done if ReleaseDC() doesn't work?" )] private static NativeMethods.Textmetric GetTextMetrics( IntPtr hwnd, Font font ) { IntPtr hdc = NativeMethods.GetWindowDC( hwnd ); NativeMethods.Textmetric textMetric; IntPtr hFont = font.ToHfont(); try { IntPtr hFontPrevious = NativeMethods.SelectObject( hdc, hFont ); NativeMethods.GetTextMetrics( hdc, out textMetric ); NativeMethods.SelectObject( hdc, hFontPrevious ); } finally { NativeMethods.ReleaseDC( hwnd, hdc ); NativeMethods.DeleteObject( hFont ); } return textMetric; } private void IPAddressControl_DragDrop( object sender, System.Windows.Forms.DragEventArgs e ) { Text = e.Data.GetData( DataFormats.Text ).ToString(); } private void IPAddressControl_DragEnter( object sender, System.Windows.Forms.DragEventArgs e ) { if ( e.Data.GetDataPresent( DataFormats.Text ) ) { e.Effect = DragDropEffects.Copy; } else { e.Effect = DragDropEffects.None; } } private void LayoutControls() { SuspendLayout(); int difference = Width - MinimumSize.Width; Debug.Assert( difference >= 0 ); int numOffsets = _fieldControls.Length + _dotControls.Length + 1; int div = difference / ( numOffsets ); int mod = difference % ( numOffsets ); int[] offsets = new int[numOffsets]; for ( int index = 0; index < numOffsets; ++index ) { offsets[index] = div; if ( index < mod ) { ++offsets[index]; } } int x = 0; int y = 0; switch ( BorderStyle ) { case BorderStyle.Fixed3D: x = Fixed3DOffset.Width; y = Fixed3DOffset.Height; break; case BorderStyle.FixedSingle: x = FixedSingleOffset.Width; y = FixedSingleOffset.Height; break; } int offsetIndex = 0; x += offsets[offsetIndex++]; for ( int i = 0; i < _fieldControls.Length; ++i ) { _fieldControls[i].Location = new Point( x, y ); x += _fieldControls[i].Width; if ( i < _dotControls.Length ) { x += offsets[offsetIndex++]; _dotControls[i].Location = new Point( x, y ); x += _dotControls[i].Width; x += offsets[offsetIndex++]; } } ResumeLayout( false ); } private void OnCedeFocus( Object sender, CedeFocusEventArgs e ) { switch ( e.Action ) { case Action.Home: _fieldControls[0].TakeFocus( Action.Home ); return; case Action.End: _fieldControls[FieldCount - 1].TakeFocus( Action.End ); return; case Action.Trim: if ( e.FieldIndex == 0 ) { return; } _fieldControls[e.FieldIndex - 1].TakeFocus( Action.Trim ); return; } if ( ( e.Direction == Direction.Reverse && e.FieldIndex == 0 ) || ( e.Direction == Direction.Forward && e.FieldIndex == ( FieldCount - 1 ) ) ) { return; } int fieldIndex = e.FieldIndex; if ( e.Direction == Direction.Forward ) { ++fieldIndex; } else { --fieldIndex; } _fieldControls[fieldIndex].TakeFocus( e.Direction, e.Selection ); } private void OnFieldGotFocus( Object sender, EventArgs e ) { if ( !_focused ) { _focused = true; base.OnGotFocus( EventArgs.Empty ); } } private void OnFieldKeyDown( Object sender, KeyEventArgs e ) { OnKeyDown( e ); } private void OnFieldKeyPressed( Object sender, KeyPressEventArgs e ) { OnKeyPress( e ); } private void OnFieldPreviewKeyDown( Object sender, PreviewKeyDownEventArgs e ) { OnPreviewKeyDown( e ); } private void OnFieldKeyUp( Object sender, KeyEventArgs e ) { OnKeyUp( e ); } private void OnFieldLostFocus( Object sender, EventArgs e ) { if ( !Focused ) { _focused = false; base.OnLostFocus( EventArgs.Empty ); } } private void OnFieldTextChanged( Object sender, TextChangedEventArgs e ) { if ( null != FieldChangedEvent ) { FieldChangedEventArgs args = new FieldChangedEventArgs(); args.FieldIndex = e.FieldIndex; args.Text = e.Text; FieldChangedEvent( this, args ); } OnTextChanged( EventArgs.Empty ); } private void OnPaste( Object sender, PasteEventArgs e ) { Text = e.Text; } private void OnSubControlClicked( object sender, EventArgs e ) { OnClick( e ); } private void OnSubControlDoubleClicked( object sender, EventArgs e ) { OnDoubleClick( e ); } private void OnSubControlMouseClicked( object sender, MouseEventArgs e ) { OnMouseClick( e ); } private void OnSubControlMouseDoubleClicked( object sender, MouseEventArgs e ) { OnMouseDoubleClick( e ); } private void OnSubControlMouseEntered( object sender, EventArgs e ) { OnMouseEnter( e ); } private void OnSubControlMouseHovered( object sender, EventArgs e ) { OnMouseHover( e ); } private void OnSubControlMouseLeft( object sender, EventArgs e ) { OnMouseLeave( e ); } private void OnSubControlMouseMoved( object sender, MouseEventArgs e ) { OnMouseMove( e ); } private static String[] Parse( String text, String[] separators ) { List<String> result = new List<String>(); int textIndex = 0; int index = 0; for ( index = 0; index < separators.Length; ++index ) { int findIndex = text.IndexOf( separators[ index ], textIndex, StringComparison.Ordinal ); if ( findIndex >= 0 ) { result.Add( text.Substring( textIndex, findIndex - textIndex ) ); textIndex = findIndex + separators[ index ].Length; } else { break; } } result.Add( text.Substring( textIndex ) ); return result.ToArray(); } // a hack to remove an FxCop warning private void ResetBackColorChanged() { _backColorChanged = false; } #endregion Private Methods #region Private Data private bool _autoHeight = true; private bool _backColorChanged; private BorderStyle _borderStyle = BorderStyle.Fixed3D; private DotControl[] _dotControls = new DotControl[FieldCount - 1]; private FieldControl[] _fieldControls = new FieldControl[FieldCount]; private bool _focused; private bool _hasMouse; private bool _readOnly; private Size Fixed3DOffset = new Size( 3, 3 ); private Size FixedSingleOffset = new Size( 2, 2 ); #endregion // Private Data } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; namespace Orleans.Runtime { public enum CounterStorage { DontStore, LogOnly, LogAndTable } public interface ICounter { string Name { get; } bool IsValueDelta { get; } string GetValueString(); string GetDeltaString(); void ResetCurrent(); string GetDisplayString(); CounterStorage Storage { get; } } internal interface ICounter<out T> : ICounter { T GetCurrentValue(); } internal class CounterStatistic : ICounter<long> { [ThreadStatic] private static List<long> perOrleansThreadCounters; [ThreadStatic] private static bool isOrleansManagedThread; private static readonly Dictionary<string, CounterStatistic> registeredStatistics; private static readonly object lockable; private static int nextId; private static readonly HashSet<List<long>> allThreadCounters; private readonly int id; private long last; private bool firstStatDisplay; private Func<long, long> valueConverter; private long nonOrleansThreadsCounter; // one for all non-Orleans threads private readonly bool isHidden; public string Name { get; private set; } public bool UseDelta { get; private set; } public CounterStorage Storage { get; private set; } static CounterStatistic() { registeredStatistics = new Dictionary<string, CounterStatistic>(); allThreadCounters = new HashSet<List<long>>(); nextId = 0; lockable = new object(); } // Must be called while Lockable is locked private CounterStatistic(string name, bool useDelta, CounterStorage storage, bool isHidden) { Name = name; UseDelta = useDelta; Storage = storage; id = Interlocked.Increment(ref nextId); last = 0; firstStatDisplay = true; valueConverter = null; nonOrleansThreadsCounter = 0; this.isHidden = isHidden; } internal static void SetOrleansManagedThread() { if (!isOrleansManagedThread) { lock (lockable) { isOrleansManagedThread = true; perOrleansThreadCounters = new List<long>(); allThreadCounters.Add(perOrleansThreadCounters); } } } public static CounterStatistic FindOrCreate(StatisticName name) { return FindOrCreate_Impl(name, true, CounterStorage.LogAndTable, false); } public static CounterStatistic FindOrCreate(StatisticName name, bool useDelta, bool isHidden = false) { return FindOrCreate_Impl(name, useDelta, CounterStorage.LogAndTable, isHidden); } public static CounterStatistic FindOrCreate(StatisticName name, CounterStorage storage, bool isHidden = false) { return FindOrCreate_Impl(name, true, storage, isHidden); } public static CounterStatistic FindOrCreate(StatisticName name, bool useDelta, CounterStorage storage, bool isHidden = false) { return FindOrCreate_Impl(name, useDelta, storage, isHidden); } private static CounterStatistic FindOrCreate_Impl(StatisticName name, bool useDelta, CounterStorage storage, bool isHidden) { lock (lockable) { CounterStatistic stat; if (registeredStatistics.TryGetValue(name.Name, out stat)) { return stat; } var ctr = new CounterStatistic(name.Name, useDelta, storage, isHidden); registeredStatistics[name.Name] = ctr; return ctr; } } static public bool Delete(string name) { lock (lockable) { return registeredStatistics.Remove(name); } } public CounterStatistic AddValueConverter(Func<long, long> converter) { this.valueConverter = converter; return this; } public void Increment() { IncrementBy(1); } public void DecrementBy(long n) { IncrementBy(-n); } // Orleans-managed threads aggregate stats in per thread local storage list. // For non Orleans-managed threads (.NET IO completion port threads, thread pool timer threads) we don't want to allocate a thread local storage, // since we don't control how many of those threads are created (could lead to too much thread local storage allocated). // Thus, for non Orleans-managed threads, we use a counter shared between all those threads and Interlocked.Add it (creating small contention). public void IncrementBy(long n) { if (isOrleansManagedThread) { while (perOrleansThreadCounters.Count <= id) { perOrleansThreadCounters.Add(0); } perOrleansThreadCounters[id] = perOrleansThreadCounters[id] + n; } else { if (n == 1) { Interlocked.Increment(ref nonOrleansThreadsCounter); } else { Interlocked.Add(ref nonOrleansThreadsCounter, n); } } } /// <summary> /// Returns the current value /// </summary> /// <returns></returns> public long GetCurrentValue() { List<List<long>> lists; lock (lockable) { lists = allThreadCounters.ToList(); } // Where(list => list.Count > id) takes only list from threads that actualy have value for this counter. // The whole way we store counters is very ineffecient and better be re-written. long val = Interlocked.Read(ref nonOrleansThreadsCounter); foreach(var list in lists.Where(list => list.Count > id)) { val += list[id]; } return val; // return lists.Where(list => list.Count > id).Aggregate<List<long>, long>(0, (current, list) => current + list[id]) + nonOrleansThreadsCounter; } // does not reset delta public long GetCurrentValueAndDelta(out long delta) { long currentValue = GetCurrentValue(); delta = UseDelta ? (currentValue - last) : 0; return currentValue; } public bool IsValueDelta { get { return UseDelta; } } public void ResetCurrent() { var currentValue = GetCurrentValue(); last = currentValue; } public string GetValueString() { long current = GetCurrentValue(); if (valueConverter != null) { try { current = valueConverter(current); } catch (Exception) { } } return current.ToString(CultureInfo.InvariantCulture); } public string GetDeltaString() { long current = GetCurrentValue(); long delta = UseDelta ? (current - last) : 0; if (valueConverter != null) { try { delta = valueConverter(delta); } catch (Exception) { } } return delta.ToString(CultureInfo.InvariantCulture); } public string GetDisplayString() { long delta; long current = GetCurrentValueAndDelta(out delta); if (firstStatDisplay) { delta = 0; // Special case: don't output first delta firstStatDisplay = false; } if (valueConverter != null) { try { current = valueConverter(current); } catch (Exception) { } try { delta = valueConverter(delta); } catch (Exception) { } } if (delta == 0) { return String.Format("{0}.Current={1}", Name, current.ToString(CultureInfo.InvariantCulture)); } else { return String.Format("{0}.Current={1}, Delta={2}", Name, current.ToString(CultureInfo.InvariantCulture), delta.ToString(CultureInfo.InvariantCulture)); } } public override string ToString() { return GetDisplayString(); } public static void AddCounters(List<ICounter> list, Func<CounterStatistic, bool> predicate) { lock (lockable) { list.AddRange(registeredStatistics.Values.Where( c => !c.isHidden && predicate(c))); } } } }